Exemplo n.º 1
0
 /**
  * Perform an upgrade without using the web-frontend
  *
  * @param bool $enablePrint
  *
  * @throws Exception
  * @return array, with keys:
  *   - message: string, HTML-ish blob
  */
 public function run($enablePrint = TRUE)
 {
     // lets get around the time limit issue if possible for upgrades
     if (!ini_get('safe_mode')) {
         set_time_limit(0);
     }
     $upgrade = new CRM_Upgrade_Form();
     list($currentVer, $latestVer) = $upgrade->getUpgradeVersions();
     if ($error = $upgrade->checkUpgradeableVersion($currentVer, $latestVer)) {
         throw new Exception($error);
     }
     // Disable our SQL triggers
     CRM_Core_DAO::dropTriggers();
     // CRM-11156
     $preUpgradeMessage = NULL;
     $upgrade->setPreUpgradeMessage($preUpgradeMessage, $currentVer, $latestVer);
     $postUpgradeMessageFile = CRM_Utils_File::tempnam('civicrm-post-upgrade');
     $queueRunner = new CRM_Queue_Runner(array('title' => ts('CiviCRM Upgrade Tasks'), 'queue' => CRM_Upgrade_Form::buildQueue($currentVer, $latestVer, $postUpgradeMessageFile)));
     $queueResult = $queueRunner->runAll();
     if ($queueResult !== TRUE) {
         $errorMessage = CRM_Core_Error::formatTextException($queueResult['exception']);
         CRM_Core_Error::debug_log_message($errorMessage);
         if ($enablePrint) {
             print $errorMessage;
         }
         throw $queueResult['exception'];
         // FIXME test
     }
     CRM_Upgrade_Form::doFinish();
     $message = file_get_contents($postUpgradeMessageFile);
     return array('latestVer' => $latestVer, 'message' => $message, 'text' => CRM_Utils_String::htmlToText($message));
 }
 function __construct()
 {
     $this->initialize();
     CRM_Utils_System::authenticateScript(TRUE);
     //log the execution of script
     CRM_Core_Error::debug_log_message('CiviReportMail.php');
 }
Exemplo n.º 3
0
function run()
{
    session_start();
    require_once '../civicrm.config.php';
    require_once 'CRM/Core/Config.php';
    $config = CRM_Core_Config::singleton();
    require_once 'Console/Getopt.php';
    $shortOptions = "n:p:k:pre";
    $longOptions = array('name=', 'pass='******'key=', 'prefix=');
    $getopt = new Console_Getopt();
    $args = $getopt->readPHPArgv();
    array_shift($args);
    list($valid, $dontCare) = $getopt->getopt2($args, $shortOptions, $longOptions);
    $vars = array('name' => 'n', 'pass' => 'p', 'key' => 'k', 'prefix' => 'pre');
    foreach ($vars as $var => $short) {
        ${$var} = NULL;
        foreach ($valid as $v) {
            if ($v[0] == $short || $v[0] == "--{$var}") {
                ${$var} = $v[1];
                break;
            }
        }
        if (!${$var}) {
            ${$var} = CRM_Utils_Array::value($var, $_REQUEST);
        }
        $_REQUEST[$var] = ${$var};
    }
    // this does not return on failure
    // require_once 'CRM/Utils/System.php';
    CRM_Utils_System::authenticateScript(TRUE, $name, $pass);
    //log the execution of script
    CRM_Core_Error::debug_log_message('NormalizePhone.php');
    // process all phones
    processPhones($config, $prefix);
}
 function run()
 {
     if (CRM_Utils_System::authenticateKey()) {
         $request_type = CRM_Utils_Request::retrieve('type', 'String');
         $request_data = CRM_Utils_Request::retrieve('data', 'String');
         $config = CRM_Core_Config::singleton();
         if ($config->debug) {
             $request_data_log = print_r($request_data, TRUE);
             CRM_Core_Error::debug_log_message("Mailchimp Webhook Request [{$request_type}]: \n{$request_data_log}");
         }
         $function_name = 'self::mailchimpWebhook' . ucwords($request_type);
         if (is_callable($function_name)) {
             // Set a canary to prevent CiviMailchimp hooks from firing, which
             // would trigger updates back to Mailchimp, resulting in an endless
             // loop.
             civimailchimp_static('mailchimp_do_not_run_hooks', TRUE);
             try {
                 call_user_func($function_name, $request_data);
             } catch (Exception $e) {
                 $error = array('code' => get_class($e), 'message' => $e->getMessage(), 'exception' => $e);
                 $message = "Mailchimp Webhook Request [{$request_type}]: {$error['code']}: {$error['message']}";
                 CRM_CiviMailchimp_BAO_SyncLog::saveMessage('error', 'mailchimp_to_civicrm', $message, $request_data);
                 CRM_Core_Error::debug_var('Fatal Error Details', $error);
                 CRM_Core_Error::backtrace('backTrace', TRUE);
                 throw $e;
             }
         }
     }
     parent::run();
 }
 /**
  * Save values.
  */
 public function postProcess()
 {
     $values = $this->exportValues();
     try {
         $result = civicrm_api3('Setting', 'create', array('statelegemail_key' => $values['key']));
         $success = TRUE;
     } catch (CiviCRM_API3_Exception $e) {
         $error = $e->getMessage();
         CRM_Core_Error::debug_log_message(t('API Error: %1', array(1 => $error, 'domain' => 'com.aghstrategies.statelegemail')));
         CRM_Core_Session::setStatus(ts('Error saving Sunlight Foundation API key', array('domain' => 'com.aghstrategies.statelegemail')), 'Error', 'error');
         $success = FALSE;
     }
     try {
         $result = civicrm_api3('Setting', 'create', array('statelegemail_states' => $values['states']));
     } catch (CiviCRM_API3_Exception $e) {
         $error = $e->getMessage();
         CRM_Core_Error::debug_log_message(t('API Error: %1', array(1 => $error, 'domain' => 'com.aghstrategies.statelegemail')));
         CRM_Core_Session::setStatus(ts('Error saving enabled states', array('domain' => 'com.aghstrategies.statelegemail')), 'Error', 'error');
         $success = FALSE;
     }
     if ($success) {
         CRM_Core_Session::setStatus(ts('You have successfully updated the state legislator petition settings.', array('domain' => 'com.aghstrategies.statelegemail')), 'Settings saved', 'success');
     }
     parent::postProcess();
 }
Exemplo n.º 6
0
 /** 
  * Build and run the query to select all contributions
  * matching the criteria, and try to create a snapshot
  *
  * @return snapshot creation result/error
  */
 public static function createSnapshot($values)
 {
     // prepare timestamps
     $raw_from_ts = $values['donrec_contribution_horizon_from'];
     $raw_to_ts = $values['donrec_contribution_horizon_to'];
     $date_from = CRM_Utils_DonrecHelper::convertDate($raw_from_ts, -1);
     $date_to = CRM_Utils_DonrecHelper::convertDate($raw_to_ts, 1);
     $formatted_date_from = date('Y-m-d H:i:s', $date_from);
     $formatted_date_to = date('Y-m-d H:i:s', $date_to);
     $query_date_limit = "";
     if ($date_from) {
         $query_date_limit .= "AND `receive_date` >= '{$formatted_date_from}'";
     }
     if ($date_to) {
         $query_date_limit .= " AND `receive_date` <= '{$formatted_date_to}'";
     }
     // get table- and column name
     $table_query = "SELECT `cg`.`table_name`,\n                           `cf`.`column_name`\n                    FROM `civicrm_custom_group` AS cg,\n                         `civicrm_custom_field` AS cf\n                    WHERE `cg`.`name` = 'zwb_donation_receipt_item'\n                      AND `cf`.`custom_group_id` = `cg`.`id`\n                      AND `cf`.`name` = 'status'";
     $results = CRM_Core_DAO::executeQuery($table_query);
     $custom_group_table = NULL;
     $status_column = NULL;
     while ($results->fetch()) {
         $custom_group_table = $results->table_name;
         $status_column = $results->column_name;
     }
     if ($custom_group_table == NULL || $status_column == NULL) {
         // something went wrong here
         CRM_Core_Error::debug_log_message("de.systopia.donrec: error: custom_group_table or status_column is empty!");
         return array();
     }
     // calculate main selector clause
     if (!empty($values['contact_id'])) {
         $contact_id = (int) $values['contact_id'];
         $main_selector = "`contact_id` = {$contact_id}";
     } elseif (!empty($values['contact_ids'])) {
         $contact_ids = implode(',', $values['contact_ids']);
         $main_selector = "`contact_id` IN ({$contact_ids})";
     } elseif (!empty($values['contribution_ids'])) {
         $contribution_ids = implode(',', $values['contribution_ids']);
         $main_selector = "`civicrm_contribution`.`id` IN ({$contribution_ids})";
     } else {
         CRM_Core_Error::debug_log_message("de.systopia.donrec: error: no selector data found in params!");
         $main_selector = "FALSE";
     }
     // get financial type selector clause
     $profile = new CRM_Donrec_Logic_Profile($values['profile']);
     $financialTypeClause = $profile->getContributionTypesClause();
     // run the main query
     $query = "SELECT `civicrm_contribution`.`id`\n              FROM (`civicrm_contribution`)\n              LEFT JOIN `{$custom_group_table}` AS existing_receipt\n                  ON  `civicrm_contribution`.`id` = existing_receipt.`entity_id`\n                  AND existing_receipt.`{$status_column}` = 'ORIGINAL'\n              WHERE\n                  ({$main_selector})\n                  {$query_date_limit}\n                  AND {$financialTypeClause}\n                  AND (`non_deductible_amount` = 0 OR `non_deductible_amount` IS NULL)\n                  AND `contribution_status_id` = 1\n                  AND `is_test` = 0\n                  AND `currency` = 'EUR'\n                  AND existing_receipt.`entity_id` IS NULL;";
     // execute the query
     $result = CRM_Core_DAO::executeQuery($query);
     // build array
     $contributionIds = array();
     while ($result->fetch()) {
         $contributionIds[] = $result->id;
     }
     // finally, build the snapshot with it
     return CRM_Donrec_Logic_Snapshot::create($contributionIds, CRM_Donrec_Logic_Settings::getLoggedInContactID(), $formatted_date_from, $formatted_date_to, $values['profile']);
 }
Exemplo n.º 7
0
 /**
  * Handle the final step of the queue
  */
 static function onEnd(CRM_Queue_TaskContext $ctx)
 {
     //CRM_Utils_System::redirect('civicrm/demo-queue/done');
     CRM_Core_Error::debug_log_message('finished task');
     //$ctx->logy->info($message); // PEAR Log interface -- broken, PHP error
     //CRM_Core_DAO::executeQuery('select from alsdkjfasdf'); // broken, PEAR error
     //throw new Exception('whoz'); // broken, exception
 }
 /**
  * Connect to API and create test fixtures in Mailchimp and CiviCRM.
  */
 public static function setUpBeforeClass()
 {
     $api = CRM_Mailchimp_Utils::getMailchimpApi(TRUE);
     //$api->setLogFacility(function($m){print $m;});
     $api->setLogFacility(function ($m) {
         CRM_Core_Error::debug_log_message($m, FALSE, 'mailchimp');
     });
     static::createMailchimpFixtures();
 }
 /**
  * Retrieve the participant roles.
  *
  * @return array
  *   The roles, by ID.
  */
 public function getRoles()
 {
     try {
         $result = civicrm_api3('Participant', 'getoptions', array('field' => "participant_role_id", 'context' => "search"));
     } catch (CiviCRM_API3_Exception $e) {
         $error = $e->getMessage();
         CRM_Core_Error::debug_log_message(ts('API Error finding role options: %1', array('domain' => 'com.aghstrategies.eventpermissions', 1 => $error)));
     }
     return empty($result['values']) ? array() : $result['values'];
 }
 function __construct()
 {
     $config = CRM_Core_Config::singleton();
     //this does not return on failure
     require_once 'CRM/Utils/System.php';
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_System::authenticateScript(TRUE);
     //log the execution time of script
     CRM_Core_Error::debug_log_message('ParticipantProcessor.php');
 }
Exemplo n.º 11
0
 function __construct()
 {
     $config = CRM_Core_Config::singleton();
     // this does not return on failure
     require_once 'CRM/Utils/System.php';
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_System::authenticateScript(TRUE);
     $config->cleanURL = 1;
     //log the execution time of script
     CRM_Core_Error::debug_log_message('UpdatePledgeRecord.php');
 }
Exemplo n.º 12
0
 static function sync($contactId)
 {
     // get visa required value
     $getInfo = array('entity_id' => $contactId, 'return.Extended_Demographics:Is_Visa_Required' => 1);
     $isVisaRequired = civicrm_api3('custom_value', 'get', $getInfo);
     $isVisaRequired = $isVisaRequired['count'] ? $isVisaRequired['values']["{$isVisaRequired['id']}"][0] : 0;
     // this api call will get visa expiration date
     // of immigration records for the contact
     $getInfo = array('entity_id' => $contactId, 'return.Immigration:End_Date' => 1);
     $immigrationDateInfo = civicrm_api3('custom_value', 'get', $getInfo);
     $lastestVisaExpirationDate = NULL;
     if ($immigrationDateInfo['count'] > 0) {
         $lastestVisaExpirationDate = $immigrationDateInfo['values']["{$immigrationDateInfo['id']}"]['latest'];
     }
     // activity processing if immigration data found
     if ($immigrationDateInfo['count']) {
         // get 'Visa Expiration' activity for this contact
         $activityTypeId = CRM_Core_OptionGroup::getValue('activity_type', 'Visa Expiration', 'name');
         $activityStatuses = CRM_Core_OptionGroup::values('activity_status', FALSE, FALSE, FALSE, NULL, 'name');
         // to check if visa expiration activity exists for the input target_contact_id
         $activityGetParams = array('contact_id' => $contactId, 'activity_type_id' => $activityTypeId, 'sequential' => 1);
         // note : using filter 'activity_type_id' in combination with 'contact_id' filter doesn't work
         $activities = civicrm_api3('activity', 'get', $activityGetParams);
         $activityId = NULL;
         $count = 0;
         foreach ($activities['values'] as $val) {
             if ($val['activity_type_id'] != $activityTypeId || !array_key_exists('targets', $val)) {
                 continue;
             }
             $activityId = $val['id'];
             $count++;
         }
         if ($count) {
             $activityParams = array();
             $activityParams['status_id'] = $isVisaRequired ? CRM_Utils_Array::key('Scheduled', $activityStatuses) : CRM_Utils_Array::key('Cancelled', $activityStatuses);
             $activityParams['activity_date_time'] = $lastestVisaExpirationDate;
             // check if count is one, if not log a error
             if ($count > 1) {
                 // update the last activity and log a error
                 $logError = "Multiple 'Visa Expiration' activities exists for target contact with id : {$contactId}, so updating last activity with id : {$activityId}";
                 CRM_Core_Error::debug_log_message($logError);
             }
             $activityParams['id'] = $activityId;
             $result = civicrm_api3('activity', 'create', $activityParams);
         } else {
             // if no activity create a new one only if 'visa is required'
             if ($isVisaRequired) {
                 $activityParams = array('target_contact_id' => $contactId, 'activity_type_id' => $activityTypeId, 'subject' => 'Visa Expiration', 'activity_date_time' => $lastestVisaExpirationDate, 'status_id' => CRM_Utils_Array::key('Scheduled', $activityStatuses), 'details' => 'Visa Expiration');
                 $result = civicrm_api3('activity', 'create', $activityParams);
             }
         }
     }
     // end of if for immgration info check
 }
Exemplo n.º 13
0
 function __construct()
 {
     $this->initialize();
     $config = CRM_Core_Config::singleton();
     require_once 'CRM/Utils/Request.php';
     require_once 'CRM/Core/PseudoConstant.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     // this does not return on failure
     CRM_Utils_System::authenticateScript(TRUE);
     //log the execution time of script
     CRM_Core_Error::debug_log_message('UpdateGreeting.php');
 }
Exemplo n.º 14
0
 /**
  * Logs with an arbitrary level.
  *
  * @param mixed $level
  * @param string $message
  * @param array $context
  */
 public function log($level, $message, array $context = array())
 {
     // FIXME: This flattens a $context a bit prematurely. When integrating
     // with external/CMS logs, we should pass through $context.
     if (!empty($context)) {
         if (isset($context['exception'])) {
             $context['exception'] = CRM_Core_Error::formatTextException($context['exception']);
         }
         $message .= "\n" . print_r($context, 1);
     }
     CRM_Core_Error::debug_log_message($message, FALSE, '', $this->map[$level]);
 }
Exemplo n.º 15
0
 /**
  * We have two coding conventions for writing to log. Make sure that they work together.
  *
  * This tests a theory about what caused CRM-10766.
  */
 function testMixLog()
 {
     CRM_Core_Error::debug_log_message("static-1");
     $logger = CRM_Core_Error::createDebugLogger();
     CRM_Core_Error::debug_log_message("static-2");
     $logger->info('obj-1');
     CRM_Core_Error::debug_log_message("static-3");
     $logger->info('obj-2');
     CRM_Core_Error::debug_log_message("static-4");
     $logger2 = CRM_Core_Error::createDebugLogger();
     $logger2->info('obj-3');
     CRM_Core_Error::debug_log_message("static-5");
     $this->assertLogRegexp('/static-1.*static-2.*obj-1.*static-3.*obj-2.*static-4.*obj-3.*static-5/s');
 }
/**
 * ContributionRecur.AmendDDAmount 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_contribution_recur_amendddamount($params)
{
    if (array_key_exists('contact_id', $params) && array_key_exists('amount', $params) && array_key_exists('contribution_recur_id', $params)) {
        $iContactId = $params['contact_id'];
        $iContributionRecurId = $params['contribution_recur_id'];
        $iAmount = $params['amount'];
        $iContributionPageId = null;
        $iRelatedContactId = null;
        $iOnBehalfDupeAlert = null;
        $aContribParam['contactID'] = $iContactId;
        $aContribParam['contributionRecurID'] = $iContributionRecurId;
        $aContribParam['contributionPageID'] = $iContributionPageId;
        $aContribParam['relatedContactID'] = $iRelatedContactID;
        $aContribParam['onBehalfDupeAlert'] = $iOnBehalfDupeAlert;
        $aParams = array('version' => '3', 'sequential' => '1', 'contact_id' => $iContactId);
        $aResult = civicrm_api('Membership', 'getsingle', $aParams);
        if (civicrm_error($aResult)) {
            $sMsg = "Error locating Membership record for contact id {$iContactId}";
            CRM_Core_Error::debug_log_message($sMsg);
            return civicrm_api3_create_error($sMsg);
        }
        $aContribParam['membershipID'] = $aResult['membership_id'];
        $aParams = array('version' => '3', 'sequential' => '1', 'contribution_recur_id' => $iContributionRecurId);
        $aResult = civicrm_api('Contribution', 'getsingle', $aParams);
        if (civicrm_error($aResult)) {
            $sMsg = "Error locating Contribution record for contribution_recur_id {$iContributionRecurId}";
            CRM_Core_Error::debug_log_message($sMsg);
            return civicrm_api3_create_error($sMsg);
        }
        $aContribParam['contributionID'] = $aResult['id'];
        $SmartDebitIPN = new CRM_Core_Payment_SmartDebitIPN();
        $oResult = $SmartDebitIPN->main('contribute', $aContribParam);
        if ($oResult === false) {
            $sMsg = "Error when changing DD Amount using Smart Debit.";
            CRM_Core_Error::debug_log_message($sMsg);
            return civicrm_api3_create_error($sMsg);
        }
        $aParams = array('version' => '3', 'sequential' => '1', 'id' => $iContributionRecurId, 'amount' => $iAmount);
        $aResult = civicrm_api('ContributionRecur', 'update', $aParams);
        if (civicrm_error($aResult)) {
            $sMsg = "Error when updating the Amount in ContributionRecur.";
            CRM_Core_Error::debug_log_message($sMsg);
            return civicrm_api3_create_error($sMsg);
        }
        return civicrm_api3_create_success();
    } else {
        throw new API_Exception('Missing Mandatory parameters: contact_id, contribution_id, and contribution_recur_id');
    }
}
Exemplo n.º 17
0
function run()
{
    session_start();
    require_once '../civicrm.config.php';
    require_once 'CRM/Core/Config.php';
    $config =& CRM_Core_Config::singleton();
    // this does not return on failure
    CRM_Utils_System::authenticateScript(true);
    //log the execution of script
    CRM_Core_Error::debug_log_message('civimail.cronjob.php');
    // load bootstrap to call hooks
    require_once 'CRM/Utils/System.php';
    CRM_Utils_System::loadBootStrap();
    // we now use DB locks on a per job basis
    processQueue($config->mailerJobSize);
}
Exemplo n.º 18
0
 /**
  * Retrieve the value of a setting from the DB table.
  *
  * @param string $group
  *   The group name of the item (deprecated).
  * @param string $name
  *   (required) The name under which this item is stored.
  * @param int $componentID
  *   The optional component ID (so componenets can share the same name space).
  * @param string $defaultValue
  *   The default value to return for this setting if not present in DB.
  * @param int $contactID
  *   If set, this is a contactID specific setting, else its a global setting.
  *
  * @param int $domainID
  *
  * @return mixed
  *   The data if present in the setting table, else null
  */
 public static function getItem($group, $name = NULL, $componentID = NULL, $defaultValue = NULL, $contactID = NULL, $domainID = NULL)
 {
     /** @var \Civi\Core\SettingsManager $manager */
     $manager = \Civi::service('settings_manager');
     $settings = $contactID === NULL ? $manager->getBagByDomain($domainID) : $manager->getBagByContact($domainID, $contactID);
     if ($name === NULL) {
         CRM_Core_Error::debug_log_message("Deprecated: Group='{$group}'. Name should be provided.\n");
     }
     if ($componentID !== NULL) {
         CRM_Core_Error::debug_log_message("Deprecated: Group='{$group}'. Name='{$name}'. Component should be omitted\n");
     }
     if ($defaultValue !== NULL) {
         CRM_Core_Error::debug_log_message("Deprecated: Group='{$group}'. Name='{$name}'. Defaults should come from metadata\n");
     }
     return $name ? $settings->get($name) : $settings->all();
 }
 /**
  *
  */
 function __construct()
 {
     // you can run this program either from an apache command, or from the cli
     if (php_sapi_name() == "cli") {
         require_once "cli.php";
         $cli = new civicrm_cli();
         //if it doesn't die, it's authenticated
     } else {
         //from the webserver
         $this->initialize();
         $config = CRM_Core_Config::singleton();
         // this does not return on failure
         CRM_Utils_System::authenticateScript(TRUE);
         //log the execution time of script
         CRM_Core_Error::debug_log_message('UpdateMembershipReminderDate.php');
     }
 }
Exemplo n.º 20
0
 /**
  * Determine whether downloading is supported.
  *
  * @return array
  *   list of error messages; empty if OK
  */
 public function checkRequirements()
 {
     $errors = array();
     if (!$this->containerDir || !is_dir($this->containerDir) || !is_writable($this->containerDir)) {
         $civicrmDestination = urlencode(CRM_Utils_System::url('civicrm/admin/extensions', 'reset=1'));
         $url = CRM_Utils_System::url('civicrm/admin/setting/path', "reset=1&civicrmDestination={$civicrmDestination}");
         $errors[] = array('title' => ts('Directory Unwritable'), 'message' => ts("Your extensions directory is not set or is not writable. Click <a href='%1'>here</a> to set the extensions directory.", array(1 => $url)));
     }
     if (!class_exists('ZipArchive')) {
         $errors[] = array('title' => ts('ZIP Support Required'), 'message' => ts('You will not be able to install extensions at this time because your installation of PHP does not support ZIP archives. Please ask your system administrator to install the standard PHP-ZIP extension.'));
     }
     if (empty($errors) && !CRM_Utils_HttpClient::singleton()->isRedirectSupported()) {
         CRM_Core_Session::setStatus(ts('WARNING: The downloader may be unable to download files which require HTTP redirection. This may be a configuration issue with PHP\'s open_basedir or safe_mode.'));
         CRM_Core_Error::debug_log_message('WARNING: The downloader may be unable to download files which require HTTP redirection. This may be a configuration issue with PHP\'s open_basedir or safe_mode.');
     }
     return $errors;
 }
/**
 * ContributionRecur.Exists 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_contribution_recur_exists($params)
{
    if (array_key_exists('contact_id', $params)) {
        $aOptions = array('sort' => 'id DESC', 'limit' => 1);
        $aResults = civicrm_api("ContributionRecur", "get", array('version' => '3', 'q' => 'civicrm/ajax/rest', 'sequential' => '1', 'contact_id' => $params['contact_id'], 'is_active' => '1', 'options' => $aOptions));
        if ($aResults['is_error'] == 1) {
            CRM_Core_Error::debug_log_message("Error:{$aResults['error_message']}");
        }
        // ALTERNATIVE: $returnValues = array(); // OK, success
        // ALTERNATIVE: $returnValues = array("Some value"); // OK, return a single value
        // Spec: civicrm_api3_create_success($values = 1, $params = array(), $entity = NULL, $action = NULL)
        //return civicrm_api3_create_success( $returnValues, $params, 'NewEntity', 'NewAction' );
        return civicrm_api3_create_success($aResults['values'][0]);
    } else {
        throw new API_Exception('Missing Contact ID');
    }
}
Exemplo n.º 22
0
 /**
  * generate the final result
  *
  * @return array:
  *          'is_error': set if there is a fatal error
  *          'log': array with keys: 'type', 'level', 'timestamp', 'message'
  *          'download_url: URL to download the result
  *          'download_name: suggested file name for the download
  */
 public function wrapUp($snapshot_id, $is_test, $is_bulk)
 {
     $reply = array();
     // create the zip file
     $config = CRM_Core_Config::singleton();
     $preferredFileName = ts("donation_receipts.zip", array('domain' => 'de.systopia.donrec'));
     $archiveFileName = CRM_Donrec_Logic_File::makeFileName(ts("donation_receipts", array('domain' => 'de.systopia.donrec')), ".zip");
     $zip = new ZipArchive();
     $snapshot = CRM_Donrec_Logic_Snapshot::get($snapshot_id);
     $ids = $snapshot->getIds();
     $toRemove = array();
     if ($zip->open($archiveFileName, ZIPARCHIVE::CREATE) === TRUE) {
         foreach ($ids as $id) {
             $proc_info = $snapshot->getProcessInformation($id);
             if (!empty($proc_info)) {
                 $filename = isset($proc_info['PDF']['pdf_file']) ? $proc_info['PDF']['pdf_file'] : FALSE;
                 if ($filename) {
                     $toRemove[$id] = $filename;
                     $opResult = $zip->addFile($filename, basename($filename));
                     CRM_Donrec_Logic_Exporter::addLogEntry($reply, "adding <span title='{$filename}'>created PDF file</span> to <span title='{$archiveFileName}'>ZIP archive</span> ({$opResult})", CRM_Donrec_Logic_Exporter::LOG_TYPE_DEBUG);
                 }
             }
         }
         if (!$zip->close()) {
             CRM_Donrec_Logic_Exporter::addLogEntry($reply, 'zip->close() returned false!', CRM_Donrec_Logic_Exporter::LOG_TYPE_ERROR);
         }
     } else {
         CRM_Donrec_Logic_Exporter::addLogEntry($reply, sprintf('PDF processing failed: Could not open zip file '), CRM_Donrec_Logic_Exporter::LOG_TYPE_FATAL);
         return $reply;
     }
     $file = CRM_Donrec_Logic_File::createTemporaryFile($archiveFileName, $preferredFileName);
     CRM_Core_Error::debug_log_message("de.systopia.donrec: resulting ZIP file URL is '{$file}'.");
     if (!empty($file)) {
         $reply['download_name'] = $preferredFileName;
         $reply['download_url'] = $file;
     }
     // remove loose pdf files or store them
     CRM_Donrec_Logic_Exporter::addLogEntry($reply, 'Removing temporary PDF files.', CRM_Donrec_Logic_Exporter::LOG_TYPE_DEBUG);
     foreach ($toRemove as $file) {
         unlink($file);
     }
     CRM_Donrec_Logic_Exporter::addLogEntry($reply, 'PDF generation process ended.', CRM_Donrec_Logic_Exporter::LOG_TYPE_INFO);
     return $reply;
 }
 /**
  * Installs option group and options for project relationships.
  */
 public function installProjectRelationships()
 {
     try {
         civicrm_api3('OptionGroup', 'create', array('name' => CRM_Volunteer_BAO_ProjectContact::RELATIONSHIP_OPTION_GROUP, 'title' => 'Volunteer Project Relationship', 'description' => ts("Used to describe a contact's relationship to a project at large (e.g., beneficiary, manager). Not to be confused with contact-to-contact relationships.", array('domain' => 'org.civicrm.volunteer')), 'is_reserved' => 1, 'is_active' => 1));
     } catch (Exception $e) {
         $msg = 'Exception thrown in ' . __METHOD__ . '. Likely the option group already exists.';
         CRM_Core_Error::debug_log_message($msg, FALSE, 'org.civicrm.volunteer');
     }
     $optionDefaults = array('is_active' => 1, 'is_reserved' => 1, 'option_group_id' => CRM_Volunteer_BAO_ProjectContact::RELATIONSHIP_OPTION_GROUP);
     $options = array(array('name' => 'volunteer_owner', 'label' => ts('Owner', array('domain' => 'org.civicrm.volunteer')), 'description' => ts('This contact owns the volunteer project. Useful if restricting edit/delete privileges.', array('domain' => 'org.civicrm.volunteer')), 'value' => 1, 'weight' => 1), array('name' => 'volunteer_manager', 'label' => ts('Manager', array('domain' => 'org.civicrm.volunteer')), 'description' => ts('This contact manages the volunteers in a project and will receive related notifications, etc.', array('domain' => 'org.civicrm.volunteer')), 'value' => 2, 'weight' => 2), array('name' => 'volunteer_beneficiary', 'label' => ts('Beneficiary', array('domain' => 'org.civicrm.volunteer')), 'description' => ts('This contact benefits from the volunteer project (e.g., if organizations are brokering volunteers to other orgs).', array('domain' => 'org.civicrm.volunteer')), 'value' => 3, 'weight' => 3));
     foreach ($options as $opt) {
         $optionValueParams = array_merge($optionDefaults, $opt);
         $getOptionValues = civicrm_api3('OptionValue', 'get', $optionValueParams);
         // In the case of a user reinstalling CiviVolunteer we don't want duplicate options.
         if ($getOptionValues['count'] == 0) {
             civicrm_api3('OptionValue', 'create', $optionValueParams);
         }
     }
 }
 /**
  * Find the activity type ID for petitions.
  *
  * @return int
  *   The activity type ID.
  */
 public static function getPetitionActivityType()
 {
     $cache = CRM_Utils_Cache::singleton();
     $petitionActivityType = $cache->get('petitionemail_petitionActivityType');
     if (empty($petitionActivityType)) {
         try {
             $petitionTypeParams = array('name' => "activity_type", 'api.OptionValue.getsingle' => array('option_group_id' => '$value.id', 'name' => "Petition", 'options' => array('limit' => 1)), 'options' => array('limit' => 1));
             $petitionTypeInfo = civicrm_api3('OptionGroup', 'getsingle', $petitionTypeParams);
         } catch (CiviCRM_API3_Exception $e) {
             $error = $e->getMessage();
             CRM_Core_Error::debug_log_message(t('API Error: %1', array(1 => $error, 'domain' => 'com.aghstrategies.petitionemail')));
         }
         if (empty($petitionTypeInfo['api.OptionValue.getsingle']['value'])) {
             return;
         } else {
             $petitionActivityType = $petitionTypeInfo['api.OptionValue.getsingle']['value'];
             $cache->set('petitionemail_petitionActivityType', $petitionActivityType);
         }
     }
     return $petitionActivityType;
 }
Exemplo n.º 25
0
 /**
  * Call generic ajax forms.
  *
  */
 public static function run()
 {
     $className = CRM_Utils_Type::escape($_REQUEST['class_name'], 'String');
     $type = '';
     if (!empty($_REQUEST['type'])) {
         $type = CRM_Utils_Type::escape($_REQUEST['type'], 'String');
     }
     if (!$className) {
         CRM_Core_Error::fatal(ts('Invalid className: %1', array(1 => $className)));
     }
     $fnName = NULL;
     if (isset($_REQUEST['fn_name'])) {
         $fnName = CRM_Utils_Type::escape($_REQUEST['fn_name'], 'String');
     }
     if (!self::checkAuthz($type, $className, $fnName)) {
         CRM_Utils_System::civiExit();
     }
     switch ($type) {
         case 'method':
             call_user_func(array($className, $fnName));
             break;
         case 'page':
         case 'class':
         case '':
             // FIXME: This is done to maintain current wire protocol, but it might be
             // simpler to just require different 'types' for pages and forms
             if (preg_match('/^CRM_[a-zA-Z0-9]+_Page_Inline_/', $className)) {
                 $page = new $className();
                 $page->run();
             } else {
                 $wrapper = new CRM_Utils_Wrapper();
                 $wrapper->run($className);
             }
             break;
         default:
             CRM_Core_Error::debug_log_message('Unsupported inline request type: ' . var_export($type, TRUE));
     }
     CRM_Utils_System::civiExit();
 }
 /**
  * Add a Mailchimp subscriber to a CiviCRM Group.
  */
 static function mailchimpWebhookSubscribe($request_data)
 {
     $config = CRM_Core_Config::singleton();
     if ($config->debug) {
         $request_data_log = print_r($request_data, TRUE);
         CRM_Core_Error::debug_log_message("Mailchimp Webhook Request [subscribe]: \nSearching for contacts with the following data.\n{$request_data_log}");
     }
     $contacts = CRM_CiviMailchimp_Utils::getContactsWithPrimaryOrBulkEmail($request_data['email'], FALSE);
     if (empty($contacts)) {
         $mailchimp_contact = CRM_CiviMailchimp_Utils::createContactFromMailchimpRequest($request_data);
         if ($config->debug) {
             $request_data_log = print_r($mailchimp_contact, TRUE);
             CRM_Core_Error::debug_log_message("Mailchimp Webhook Request [subscribe]: \nExisting contact not found, so a new contact record was created with the following details.\n{$request_data_log}");
         }
     } else {
         $mailchimp_contact = $contacts[0];
         if ($config->debug) {
             $request_data_log = print_r($mailchimp_contact, TRUE);
             CRM_Core_Error::debug_log_message("Mailchimp Webhook Request [subscribe]: \nExisting contact found with the following details.\n{$request_data_log}");
         }
     }
     CRM_CiviMailchimp_Utils::addContactToGroup($mailchimp_contact, $request_data['list_id']);
 }
Exemplo n.º 27
0
 /**
  * This function sends request and receives response from
  * the processor
  */
 public function doDirectPayment(&$params)
 {
     if ($params['is_recur'] == TRUE) {
         CRM_Core_Error::fatal(ts('%1 - recurring payments not implemented', array(1 => $paymentProcessor)));
     }
     if (!defined('CURLOPT_SSLCERT')) {
         CRM_Core_Error::fatal(ts('%1 - Gateway requires curl with SSL support', array(1 => $paymentProcessor)));
     }
     /**********************************************************
      * Create the array of variables to be sent to the processor from the $params array
      * passed into this function
      **********************************************************/
     $requestFields = self::mapProcessorFieldstoParams($params);
     /**********************************************************
      * create FirstData request object
      **********************************************************/
     require_once 'FirstData/lphp.php';
     //  $mylphp=new lphp;
     /**********************************************************
      * define variables for connecting with the gateway
      **********************************************************/
     # Name and location of certificate file
     $key = $this->_paymentProcessor['password'];
     # Your store number
     $requestFields["configfile"] = $this->_paymentProcessor['user_name'];
     $port = "1129";
     $host = $this->_paymentProcessor['url_site'] . ":" . $port . "/LSGSXML";
     //----------------------------------------------------------------------------------------------------
     // Check to see if we have a duplicate before we send
     //----------------------------------------------------------------------------------------------------
     if ($this->checkDupe($params['invoiceID'], CRM_Utils_Array::value('contributionID', $params))) {
         return self::errorExit(9003, 'It appears that this transaction is a duplicate.  Have you already submitted the form once?  If so there may have been a connection problem.  Check your email for a receipt from eWAY.  If you do not receive a receipt within 2 hours you can try your transaction again.  If you continue to have problems please contact the site administrator.');
     }
     //----------------------------------------------------------------------------------------------------
     // Convert to XML using function provided by payment processor
     //----------------------------------------------------------------------------------------------------
     $requestxml = lphp::buildXML($requestFields);
     /*----------------------------------------------------------------------------------------------------
       // Send to the payment information using cURL
       /----------------------------------------------------------------------------------------------------
        */
     $ch = curl_init($host);
     if (!$ch) {
         return self::errorExit(9004, 'Could not initiate connection to payment gateway');
     }
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $requestxml);
     curl_setopt($ch, CURLOPT_SSLCERT, $key);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL') ? 2 : 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'verifySSL'));
     // return the result on success, FALSE on failure
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_TIMEOUT, 36000);
     // ensures any Location headers are followed
     if (ini_get('open_basedir') == '' && ini_get('safe_mode') == 'Off') {
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     }
     // Send the data out over the wire
     //--------------------------------
     $responseData = curl_exec($ch);
     //----------------------------------------------------------------------------------------------------
     // See if we had a curl error - if so tell 'em and bail out
     //
     // NOTE: curl_error does not return a logical value (see its documentation), but
     //       a string, which is empty when there was no error.
     //----------------------------------------------------------------------------------------------------
     if (curl_errno($ch) > 0 || strlen(curl_error($ch)) > 0) {
         $errorNum = curl_errno($ch);
         $errorDesc = curl_error($ch);
         // Paranoia - in the unlikley event that 'curl' errno fails
         if ($errorNum == 0) {
             $errorNum = 9005;
         }
         // Paranoia - in the unlikley event that 'curl' error fails
         if (strlen($errorDesc) == 0) {
             $errorDesc = "Connection to payment gateway failed";
         }
         if ($errorNum == 60) {
             return self::errorExit($errorNum, "Curl error - " . $errorDesc . " Try this link for more information http://curl.haxx.se/docs/sslcerts.html");
         }
         return self::errorExit($errorNum, "Curl error - " . $errorDesc . " your key is located at " . $key . " the url is " . $host . " xml is " . $requestxml . " processor response = " . $processorResponse);
     }
     //----------------------------------------------------------------------------------------------------
     // If null data returned - tell 'em and bail out
     //
     // NOTE: You will not necessarily get a string back, if the request failed for
     //       any reason, the return value will be the boolean false.
     //----------------------------------------------------------------------------------------------------
     if ($responseData === FALSE || strlen($responseData) == 0) {
         return self::errorExit(9006, "Error: Connection to payment gateway failed - no data returned.");
     }
     //----------------------------------------------------------------------------------------------------
     // If gateway returned no data - tell 'em and bail out
     //----------------------------------------------------------------------------------------------------
     if (empty($responseData)) {
         return self::errorExit(9007, "Error: No data returned from payment gateway.");
     }
     //----------------------------------------------------------------------------------------------------
     // Success so far - close the curl and check the data
     //----------------------------------------------------------------------------------------------------
     curl_close($ch);
     //----------------------------------------------------------------------------------------------------
     // Payment successfully sent to gateway - process the response now
     //----------------------------------------------------------------------------------------------------
     //
     $processorResponse = lphp::decodeXML($responseData);
     // transaction failed, print the reason
     if ($processorResponse["r_approved"] != "APPROVED") {
         return self::errorExit(9009, "Error: [" . $processorResponse['r_error'] . "] - from payment processor");
     } else {
         //-----------------------------------------------------------------------------------------------------
         // Cross-Check - the unique 'TrxnReference' we sent out should match the just received 'TrxnReference'
         //
         // this section not used as the processor doesn't appear to pass back our invoice no. Code in eWay model if
         // used later
         //-----------------------------------------------------------------------------------------------------
         //=============
         // Success !
         //=============
         $params['trxn_result_code'] = $processorResponse['r_message'];
         $params['trxn_id'] = $processorResponse['r_ref'];
         CRM_Core_Error::debug_log_message("r_authresponse " . $processorResponse['r_authresponse']);
         CRM_Core_Error::debug_log_message("r_code " . $processorResponse['r_code']);
         CRM_Core_Error::debug_log_message("r_tdate " . $processorResponse['r_tdate']);
         CRM_Core_Error::debug_log_message("r_avs " . $processorResponse['r_avs']);
         CRM_Core_Error::debug_log_message("r_ordernum " . $processorResponse['r_ordernum']);
         CRM_Core_Error::debug_log_message("r_error " . $processorResponse['r_error']);
         CRM_Core_Error::debug_log_message("csp " . $processorResponse['r_csp']);
         CRM_Core_Error::debug_log_message("r_message " . $processorResponse['r_message']);
         CRM_Core_Error::debug_log_message("r_ref " . $processorResponse['r_ref']);
         CRM_Core_Error::debug_log_message("r_time " . $processorResponse['r_time']);
         return $params;
     }
 }
Exemplo n.º 28
0
 /**
  * @param $input
  * @param $ids
  * @param $objects
  * @param bool $recur
  * @param bool $first
  */
 function single(&$input, &$ids, &$objects, $recur = FALSE, $first = FALSE)
 {
     $contribution =& $objects['contribution'];
     // make sure the invoice is valid and matches what we have in the contribution record
     if (!$recur || $recur && $first) {
         if ($contribution->invoice_id != $input['invoice']) {
             CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
             echo "Failure: Invoice values dont match between database and IPN request<p>contribution is" . $contribution->invoice_id . " and input is " . $input['invoice'];
             return FALSE;
         }
     } else {
         $contribution->invoice_id = md5(uniqid(rand(), TRUE));
     }
     if (!$recur) {
         if ($contribution->total_amount != $input['amount']) {
             CRM_Core_Error::debug_log_message("Amount values dont match between database and IPN request");
             echo "Failure: Amount values dont match between database and IPN request<p>";
             return FALSE;
         }
     } else {
         $contribution->total_amount = $input['amount'];
     }
     $transaction = new CRM_Core_Transaction();
     $participant =& $objects['participant'];
     $membership =& $objects['membership'];
     $status = $input['paymentStatus'];
     if ($status == 'Denied' || $status == 'Failed' || $status == 'Voided') {
         return $this->failed($objects, $transaction);
     } elseif ($status == 'Pending') {
         return $this->pending($objects, $transaction);
     } elseif ($status == 'Refunded' || $status == 'Reversed') {
         return $this->cancelled($objects, $transaction);
     } elseif ($status != 'Completed') {
         return $this->unhandled($objects, $transaction);
     }
     // check if contribution is already completed, if so we ignore this ipn
     if ($contribution->contribution_status_id == 1) {
         $transaction->commit();
         CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
         echo "Success: Contribution has already been handled<p>";
         return TRUE;
     }
     $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
 }
Exemplo n.º 29
0
 /**
  * @param $from
  * @param $body
  * @param null $to
  * @param int $trackID
  *
  * @return self|null|object
  * @throws CRM_Core_Exception
  */
 public function processInbound($from, $body, $to = NULL, $trackID = NULL)
 {
     $formatFrom = $this->formatPhone($this->stripPhone($from), $like, "like");
     $escapedFrom = CRM_Utils_Type::escape($formatFrom, 'String');
     $fromContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE "%' . $escapedFrom . '"');
     if (!$fromContactID) {
         // unknown mobile sender -- create new contact
         // use fake @mobile.sms email address for new contact since civi
         // requires email or name for all contacts
         $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
         $phoneloc = array_search('Home', $locationTypes);
         $phonetype = array_search('Mobile', $phoneTypes);
         $stripFrom = $this->stripPhone($from);
         $contactparams = array('contact_type' => 'Individual', 'email' => array(1 => array('location_type_id' => $phoneloc, 'email' => $stripFrom . '@mobile.sms')), 'phone' => array(1 => array('phone_type_id' => $phonetype, 'location_type_id' => $phoneloc, 'phone' => $stripFrom)));
         $fromContact = CRM_Contact_BAO_Contact::create($contactparams, FALSE, TRUE, FALSE);
         $fromContactID = $fromContact->id;
     }
     if ($to) {
         $to = CRM_Utils_Type::escape($to, 'String');
         $toContactID = CRM_Core_DAO::singleValueQuery('SELECT contact_id FROM civicrm_phone JOIN civicrm_contact ON civicrm_contact.id = civicrm_phone.contact_id WHERE !civicrm_contact.is_deleted AND phone LIKE "%' . $to . '"');
     } else {
         $toContactID = $fromContactID;
     }
     if ($fromContactID) {
         $actStatusIDs = array_flip(CRM_Core_OptionGroup::values('activity_status'));
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Inbound SMS', 'name');
         // note: lets not pass status here, assuming status will be updated by callback
         $activityParams = array('source_contact_id' => $toContactID, 'target_contact_id' => $fromContactID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'status_id' => $actStatusIDs['Completed'], 'details' => $body, 'phone_number' => $from);
         if ($trackID) {
             $trackID = CRM_Utils_Type::escape($trackID, 'String');
             $activityParams['result'] = $trackID;
         }
         $result = CRM_Activity_BAO_Activity::create($activityParams);
         CRM_Core_Error::debug_log_message("Inbound SMS recorded for cid={$fromContactID}.");
         return $result;
     }
 }
Exemplo n.º 30
0
 function getBillingID(&$ids)
 {
     // get the billing location type
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
     // CRM-8108 remove the ts around the Billing locationtype
     //$ids['billing'] =  array_search( ts('Billing'),  $locationTypes );
     $ids['billing'] = array_search('Billing', $locationTypes);
     if (!$ids['billing']) {
         CRM_Core_Error::debug_log_message(ts('Please set a location type of %1', array(1 => 'Billing')));
         echo "Failure: Could not find billing location type<p>";
         return FALSE;
     }
     return TRUE;
 }