function alterDisplay(&$rows) { $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument(); require_once 'api/v2/Contact.php'; require_once 'CRM/Contribute/DAO/ContributionType.php'; foreach ($rows as $rowNum => $row) { if (array_key_exists('civicrm_contribution_contact_id', $row)) { $contact_id = $row['civicrm_contribution_contact_id']; $params = array('contact_id' => $contact_id, 'return.external_identifier' => 1); $contactArray = civicrm_contact_get($params); if (!empty($contactArray[$contact_id]['external_identifier'])) { $rows[$rowNum]['civicrm_contribution_contact_id'] = $contactArray[$contact_id]['external_identifier']; } } if (array_key_exists('civicrm_contribution_payment_instrument_id', $row)) { $payment_intrument_id = $row['civicrm_contribution_payment_instrument_id']; $payment_intrument_name = $paymentInstruments[$payment_intrument_id]; $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $payment_intrument_name; } if (array_key_exists('civicrm_contribution_contribution_type_id', $row)) { $contribution_type_id = $row['civicrm_contribution_contribution_type_id']; $dao =& new CRM_Contribute_DAO_ContributionType(); $dao->id = $contribution_type_id; $dao->find(true); $contribution_type_name = $dao->name; $rows[$rowNum]['civicrm_contribution_contribution_type_id'] = $contribution_type_name; } if (array_key_exists('civicrm_contribution_contact_name', $row)) { $contact_id = $row['civicrm_contribution_contact_name']; $params = array('contact_id' => $contact_id, 'return.display_name' => 1); $contactArray = civicrm_contact_get($params); if (!empty($contactArray[$contact_id]['display_name'])) { $rows[$rowNum]['civicrm_contribution_contact_name'] = $contactArray[$contact_id]['display_name']; $url = 'civicrm/contact/view'; $urlParams = "reset=1&cid={$contact_id}"; $contact_url = CRM_Utils_System::url($url, $urlParams); $rows[$rowNum]['civicrm_contribution_contact_name_link'] = $contact_url; } } } //print_r ($rows);exit; }
/** * Find differences between contacts. */ function findDifferences($mainId, $otherId) { require_once 'api/v2/Contact.php'; $mainParams = array('contact_id' => (int) $mainId); $otherParams = array('contact_id' => (int) $otherId); // API 2 has to have the requested fields spelt-out for it foreach (self::$validFields as $field) { $mainParams["return.{$field}"] = $otherParams["return.{$field}"] = 1; } $main =& civicrm_contact_get($mainParams); $other =& civicrm_contact_get($otherParams); //CRM-4524 $main = reset($main); $other = reset($other); if ($main['contact_type'] != $other['contact_type']) { return false; } $diffs = array(); foreach (self::$validFields as $validField) { if (CRM_Utils_Array::value($validField, $main) != CRM_Utils_Array::value($validField, $other)) { $diffs['contact'][] = $validField; } } require_once 'CRM/Core/BAO/CustomValueTable.php'; $mainEvs =& CRM_Core_BAO_CustomValueTable::getEntityValues($mainId); $otherEvs =& CRM_Core_BAO_CustomValueTable::getEntityValues($otherId); $keys = array_keys($mainEvs) + array_keys($otherEvs); foreach ($keys as $key) { if ($mainEvs[$key] != $otherEvs[$key]) { $diffs['custom'][] = $key; } } return $diffs; }
static function civicrm_direct_debit_civicrm_pageRun_produceSetUpLetter($mandate_id, $contact_id, $default_template, $return_content = false, $contribution_id, $first_collectionDate) { //$sql = "SELECT * FROM civicrm_value_bank_details WHERE id = %1"; //$params = array( 1 => array( $entity_id , 'Integer' )); //$dao = CRM_Core_DAO::executeQuery( $sql, $params ); //$dao->fetch( ) //$contribution_id = $dao->entity_id; ## Get the contribution details //require_once 'CRM/Contribute/DAO/Contribution.php'; //$contribution_dao =& new CRM_Contribute_DAO_Contribution( ); //$contribution_dao->get($contribution_id); //$contribution_date = $contribution_dao->receive_date; //$contribution_date = strtotime(date("d/m/Y", strtotime($contribution_date))); //$contribution_date = date('mdY', $contribution_date); //require_once 'CRM/Core/DAO'; $fiscal_template = $default_template; $date = date('d/m/y'); //$amount = $dao->amount; require_once 'CRM/Contribute/DAO/Contribution.php'; $contrib_dao = new CRM_Contribute_DAO_Contribution(); $contrib_dao->id = $contribution_id; $contrib_dao->find(true); require_once "api/v2/Contact.php"; $contactParams = array('id' => $contact_id); $contact =& civicrm_contact_get($contactParams); require_once "CRM/Mailing/BAO/Mailing.php"; $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->body_text = $fiscal_template; $mailing->body_html = $fiscal_template; $tokens = $mailing->getTokens(); //print_r ($tokens);exit; require_once "CRM/Utils/Token.php"; if ($contact_id) { $fiscal_template = CRM_Utils_Token::replaceContactTokens($fiscal_template, $contact, false, $tokens['html']); } //$address = preg_replace("/\n/","<br>",$dao->address); $mandate_sql = "SELECT * FROM civicrm_value_bank_details bd WHERE bd.id = %1"; $mandate_params = array(1 => array($mandate_id, 'Integer')); $mandate_dao = CRM_Core_DAO::executeQuery($mandate_sql, $mandate_params); $mandate_dao->fetch(); $day_of_collection = $_ENV['collectionDayArray'][$mandate_dao->collection_day] . " of every month"; $fiscal_template = str_replace('{invoice_number}', $receipt_number, $fiscal_template); $fiscal_template = str_replace('{invoice_date}', $date, $fiscal_template); $fiscal_template = str_replace('{amount}', $contrib_dao->total_amount, $fiscal_template); $fiscal_template = str_replace('{first_collection_date}', $first_collectionDate, $fiscal_template); $fiscal_template = str_replace('{day_of_collection}', $day_of_collection, $fiscal_template); $fiscal_template = str_replace('{account_name}', $mandate_dao->account_name, $fiscal_template); $fiscal_template = str_replace('{account_number}', $mandate_dao->account_number, $fiscal_template); $fiscal_template = str_replace('{sort_code}', $mandate_dao->sort_code, $fiscal_template); $final_template = $fiscal_template; //$final_template .= "<div STYLE='page-break-after: always'></div>"; //echo $final_template;exit; $file_name = "SetUp_Letter_" . $contact_id . ".pdf"; $fileContent = self::civicrm_direct_debit_civicrm_pageRun_html2pdf($final_template, $file_name, "external"); require_once "CRM/Core/Config.php"; $config =& CRM_Core_Config::singleton(); $csv_path = $config->customFileUploadDir; //$csv_path = "sites/default/files/civicrm/custom"; $filePathName = "{$csv_path}/{$file_name}"; $handle = fopen($filePathName, 'w'); file_put_contents($filePathName, $fileContent); fclose($handle); return array('content' => $final_template, 'file_name' => $file_name); /*if ($return_content) return $final_template; else return $file_name;*/ }
public function get_contact($key, $params) { $this->verify($key); require_once 'api/v2/Contact.php'; return civicrm_contact_get($params); }
function sendInvoiceMail($email, $displayName, $fromEmail, $fileName, $filePathName, $obj, $contactID, $contribution) { ## getting contact detail require_once 'api/v2/Contact.php'; $contactParams = array('id' => $contactID); $contact =& civicrm_contact_get($contactParams); ## Check the contribution type to work out which email template we should be using //print_r($contribution); exit; $contributionTypeId = $contribution->contribution_type_id; if ($contributionTypeId == '2') { ## Contribution Type - Membership $emailTemplateName = 'Membership Invoice'; $params['bcc'] = '*****@*****.**'; } if ($contributionTypeId == '4') { ## Contribution Type - Events $emailTemplateName = 'Participant Invoice'; $params['bcc'] = '*****@*****.**'; } ## getting invoice mail template $query = "SELECT * FROM civicrm_msg_template WHERE msg_title = '{$emailTemplateName}' AND is_active=1"; $dao = CRM_Core_DAO::executeQuery($query); if (!$dao->fetch()) { print "Not able to get Email Template"; exit; } $text = $dao->msg_text; $html = $dao->msg_html; $subject = $dao->msg_subject; ################################################### require_once "CRM/Mailing/BAO/Mailing.php"; $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->body_text = $text; $mailing->body_html = $html; $tokens = $mailing->getTokens(); require_once "CRM/Utils/Token.php"; $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, true, $tokens['text']); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, true, $tokens['text']); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); if ($contactID) { $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, false, $tokens['text']); $text = CRM_Utils_Token::replaceContactTokens($text, $contact, false, $tokens['text']); $html = CRM_Utils_Token::replaceContactTokens($html, $contact, false, $tokens['html']); } // parse the three elements with Smarty require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); $smarty =& CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } ################################################### $params['text'] = $text; $params['html'] = $html; $params['subject'] = $subject; // assigning from email $params['from'] = $fromEmail; #### live ###### uncomment it $params['toName'] = $displayName; $params['toEmail'] = $email; #### test ###### comment it #$params['toName'] = "Test"; #$params['toEmail'] = '*****@*****.**'; # Left this in as hard coded for now as the default from email address doesn't seem to work # We can probably do something with the contribution type for the from email addresses $params['from'] = '*****@*****.**'; $attach = array('fullPath' => $filePathName, 'mime_type' => 'pdf', 'cleanName' => $fileName); ## Commented out to test if attachments are causing the problem $params['attachments'] = array($fileName => $attach); require_once 'CRM/Utils/Mail.php'; // Comment to abort sending email $sent = CRM_Utils_Mail::send($params); if ($sent) { echo "<br />Invoice sent <b>successfully</b> - {$email}</b><br /><br />"; ## Insert a record into Log table - civicrm_mtl_invoice_log $contribution_id = $contribution->id; } else { echo "<br />Invoice sent <b>faliure</b> - <b>{$email}</b>{$sent->message}<br /><br />"; } //please comment this before setting up in LIVE //exit; }
/** * Send an email from the specified template based on an array of params * * @param array $params a string-keyed array of function params, see function body for details * * @return array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates */ static function sendTemplate($params) { $defaults = array('groupName' => null, 'valueName' => null, 'contactId' => null, 'tplParams' => array(), 'from' => null, 'toName' => null, 'toEmail' => null, 'cc' => null, 'bcc' => null, 'replyTo' => null, 'attachments' => null, 'isTest' => false); $params = array_merge($defaults, $params); if (!$params['groupName'] or !$params['valueName']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value missing.")); } // fetch the three elements from the db based on option_group and option_value names $query = 'SELECT msg_subject subject, msg_text text, msg_html html FROM civicrm_msg_template mt JOIN civicrm_option_value ov ON workflow_id = ov.id JOIN civicrm_option_group og ON ov.option_group_id = og.id WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String')); $dao = CRM_Core_DAO::executeQuery($query, $sqlParams); $dao->fetch(); if (!$dao->N) { CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName']))); } $subject = $dao->subject; $text = $dao->text; $html = $dao->html; // add the test banner (if requested) if ($params['isTest']) { $query = "SELECT msg_subject subject, msg_text text, msg_html html\n FROM civicrm_msg_template mt\n JOIN civicrm_option_value ov ON workflow_id = ov.id\n JOIN civicrm_option_group og ON ov.option_group_id = og.id\n WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1"; $testDao = CRM_Core_DAO::executeQuery($query); $testDao->fetch(); $subject = $testDao->subject . $subject; $text = $testDao->text . $text; $html = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $html); } // replace tokens in the three elements require_once 'CRM/Utils/Token.php'; require_once 'CRM/Core/BAO/Domain.php'; require_once 'api/v2/Contact.php'; require_once 'CRM/Mailing/BAO/Mailing.php'; $domain = CRM_Core_BAO_Domain::getDomain(); if ($params['contactId']) { $contactParams = array('contact_id' => $params['contactId']); $contact =& civicrm_contact_get($contactParams); } // replace tokens in subject as if it was the text body foreach (array('subject' => 'text', 'text' => 'text', 'html' => 'html') as $type => $tokenType) { if (!${$type}) { continue; } // skip all of the below if the given part is missing $bodyType = "body_{$tokenType}"; $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->{$bodyType} = ${$type}; $tokens = $mailing->getTokens(); ${$type} = CRM_Utils_Token::replaceDomainTokens(${$type}, $domain, true, $tokens[$tokenType]); if ($params['contactId']) { ${$type} = CRM_Utils_Token::replaceContactTokens(${$type}, $contact, false, $tokens[$tokenType]); } } // strip whitespace from ends and turn into a single line $subject = "{strip}{$subject}{/strip}"; // parse the three elements with Smarty require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); $smarty =& CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } foreach (array('subject', 'text', 'html') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } // send the template, honouring the target user’s preferences (if any) $sent = false; if ($params['toEmail']) { $contactParams = array('email' => $params['toEmail']); $contact =& civicrm_contact_get($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $text = null; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $html = null; } require_once 'CRM/Utils/Mail.php'; $sent = CRM_Utils_Mail::send($params['from'], $params['toName'], $params['toEmail'], $subject, $text, $params['cc'], $params['bcc'], $params['replyTo'], $html, $params['attachments']); } return array($sent, $subject, $text, $html); }
/** * Function for validation * * @param array $params (ref.) an assoc array of name/value pairs * * @return mixed true or array of errors * @access public * @static */ static function formRule($params, $files, $self) { if (CRM_Utils_Array::value('_qf_Import_refresh', $_POST)) { return true; } $errors = array(); $template = CRM_Core_Smarty::singleton(); if (isset($params['html_message'])) { $htmlMessage = str_replace(array("\n", "\r"), ' ', $params['html_message']); $htmlMessage = str_replace("'", "\\'", $htmlMessage); $template->assign('htmlContent', $htmlMessage); } require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); require_once 'CRM/Mailing/BAO/Mailing.php'; $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->id = $self->_mailingID; $mailing->find(true); $session = CRM_Core_Session::singleton(); $values = array('contact_id' => $session->get('userID')); require_once 'api/v2/Contact.php'; $contact =& civicrm_contact_get($values); //CRM-4524 $contact = reset($contact); $verp = array_flip(array('optOut', 'reply', 'unsubscribe', 'resubscribe', 'owner')); foreach ($verp as $key => $value) { $verp[$key]++; } $urls = array_flip(array('forward', 'optOutUrl', 'unsubscribeUrl', 'resubscribeUrl')); foreach ($urls as $key => $value) { $urls[$key]++; } require_once 'CRM/Mailing/BAO/Component.php'; // set $header and $footer foreach (array('header', 'footer') as $part) { ${$part} = array(); if ($params["{$part}_id"]) { //echo "found<p>"; $component = new CRM_Mailing_BAO_Component(); $component->id = $params["{$part}_id"]; $component->find(true); ${$part}['textFile'] = $component->body_text; ${$part}['htmlFile'] = $component->body_html; $component->free(); } else { ${$part}['htmlFile'] = ${$part}['textFile'] = ''; } } require_once 'CRM/Utils/Token.php'; $skipTextFile = $self->get('skipTextFile'); $skipHtmlFile = $self->get('skipHtmlFile'); if (!$params['upload_type']) { if ((!isset($files['textFile']) || !file_exists($files['textFile']['tmp_name'])) && (!isset($files['htmlFile']) || !file_exists($files['htmlFile']['tmp_name']))) { if (!($skipTextFile || $skipHtmlFile)) { $errors['textFile'] = ts('Please provide either a Text or HTML formatted message - or both.'); } } } else { if (!CRM_Utils_Array::value('text_message', $params) && !CRM_Utils_Array::value('html_message', $params)) { $errors['html_message'] = ts('Please provide either a Text or HTML formatted message - or both.'); } if (CRM_Utils_Array::value('saveTemplate', $params) && !CRM_Utils_Array::value('saveTemplateName', $params)) { $errors['saveTemplateName'] = ts('Please provide a Template Name.'); } } foreach (array('text', 'html') as $file) { if (!$params['upload_type'] && !file_exists(CRM_Utils_Array::value('tmp_name', $files[$file . 'File']))) { continue; } if ($params['upload_type'] && !$params[$file . '_message']) { continue; } if (!$params['upload_type']) { $str = file_get_contents($files[$file . 'File']['tmp_name']); $name = $files[$file . 'File']['name']; } else { $str = $params[$file . '_message']; $str = $file == 'html' ? str_replace('%7B', '{', str_replace('%7D', '}', $str)) : $str; $name = $file . ' message'; } /* append header/footer */ $str = $header[$file . 'File'] . $str . $footer[$file . 'File']; $dataErrors = array(); /* First look for missing tokens */ $err = CRM_Utils_Token::requiredTokens($str); if ($err !== true) { foreach ($err as $token => $desc) { $dataErrors[] = '<li>' . ts('This message is missing a required token - {%1}: %2', array(1 => $token, 2 => $desc)) . '</li>'; } } /* Do a full token replacement on a dummy verp, the current * contact and domain, and the first organization. */ // here we make a dummy mailing object so that we // can retrieve the tokens that we need to replace // so that we do get an invalid token error // this is qute hacky and I hope that there might // be a suggestion from someone on how to // make it a bit more elegant require_once 'CRM/Mailing/BAO/Mailing.php'; $dummy_mail = new CRM_Mailing_BAO_Mailing(); $mess = "body_{$file}"; $dummy_mail->{$mess} = $str; $tokens = $dummy_mail->getTokens(); $str = CRM_Utils_Token::replaceSubscribeInviteTokens($str); $str = CRM_Utils_Token::replaceDomainTokens($str, $domain, null, $tokens[$file]); $str = CRM_Utils_Token::replaceMailingTokens($str, $mailing, null, $tokens[$file]); $str = CRM_Utils_Token::replaceOrgTokens($str, $org); $str = CRM_Utils_Token::replaceActionTokens($str, $verp, $urls, null, $tokens[$file]); $str = CRM_Utils_Token::replaceContactTokens($str, $contact, null, $tokens[$file]); $unmatched = CRM_Utils_Token::unmatchedTokens($str); if (!empty($unmatched) && 0) { foreach ($unmatched as $token) { $dataErrors[] = '<li>' . ts('Invalid token code') . ' {' . $token . '}</li>'; } } if (!empty($dataErrors)) { $errors[$file . 'File'] = ts('The following errors were detected in %1:', array(1 => $name)) . ' <ul>' . implode('', $dataErrors) . '</ul><br /><a href="' . CRM_Utils_System::docURL2('Sample CiviMail Messages', true) . '" target="_blank">' . ts('More information on required tokens...') . '</a>'; } } require_once 'CRM/Core/BAO/MessageTemplates.php'; $templateName = CRM_Core_BAO_MessageTemplates::getMessageTemplates(); if (CRM_Utils_Array::value('saveTemplate', $params) && in_array(CRM_Utils_Array::value('saveTemplateName', $params), $templateName)) { $errors['saveTemplate'] = ts('Duplicate Template Name.'); } return empty($errors) ? true : $errors; }
function preProcess() { require_once 'api/v2/Contact.php'; require_once 'CRM/Core/BAO/CustomGroup.php'; require_once 'CRM/Core/OptionGroup.php'; require_once 'CRM/Core/OptionValue.php'; if (!CRM_Core_Permission::check('administer CiviCRM')) { CRM_Core_Error::fatal(ts('You do not have access to this page')); } $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, true); $oid = CRM_Utils_Request::retrieve('oid', 'Positive', $this, true); $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive', $this, false); $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, false); $session =& CRM_Core_Session::singleton(); // context fixed. if ($rgid) { $urlParam = "reset=1&action=browse&rgid={$rgid}"; if ($gid) { $urlParam .= "&gid={$gid}"; } $session->pushUserContext(CRM_Utils_system::url('civicrm/admin/dedupefind', $urlParam)); } // ensure that oid is not the current user, if so refuse to do the merge if ($session->get('userID') == $oid) { $display_name = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $oid, 'display_name'); $message = ts('The contact record which is linked to the currently logged in user account - \'%1\' - cannot be deleted.', array(1 => $display_name)); CRM_Core_Error::statusBounce($message); } $diffs = CRM_Dedupe_Merger::findDifferences($cid, $oid); $mainParams = array('contact_id' => $cid, 'return.display_name' => 1); $otherParams = array('contact_id' => $oid, 'return.display_name' => 1); // API 2 has to have the requested fields spelt-out for it foreach (CRM_Dedupe_Merger::$validFields as $field) { $mainParams["return.{$field}"] = $otherParams["return.{$field}"] = 1; } $main =& civicrm_contact_get($mainParams); //CRM-4524 $main = reset($main); if ($main['contact_id'] != $cid) { CRM_Core_Error::fatal(ts('The main contact record does not exist')); } $other =& civicrm_contact_get($otherParams); //CRM-4524 $other = reset($other); if ($other['contact_id'] != $oid) { CRM_Core_Error::fatal(ts('The other contact record does not exist')); } $this->assign('contact_type', $main['contact_type']); $this->assign('main_name', $main['display_name']); $this->assign('other_name', $other['display_name']); $this->assign('main_cid', $main['contact_id']); $this->assign('other_cid', $other['contact_id']); $this->_cid = $cid; $this->_oid = $oid; $this->_rgid = $rgid; $this->_contactType = $main['contact_type']; $this->addElement('checkbox', 'toggleSelect', null, null, array('onclick' => "return toggleCheckboxVals('move_',this);")); require_once "CRM/Contact/DAO/Contact.php"; $fields =& CRM_Contact_DAO_Contact::fields(); // FIXME: there must be a better way foreach (array('main', 'other') as $moniker) { $contact =& ${$moniker}; $specialValues[$moniker] = array('preferred_communication_method' => $contact['preferred_communication_method']); $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method')); CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names); } foreach (CRM_Core_OptionValue::getFields() as $field => $params) { $fields[$field]['title'] = $params['title']; } if (!isset($diffs['contact'])) { $diffs['contact'] = array(); } foreach ($diffs['contact'] as $field) { foreach (array('main', 'other') as $moniker) { $contact =& ${$moniker}; $value = CRM_Utils_Array::value($field, $contact); $label = isset($specialValues[$moniker][$field]) ? $specialValues[$moniker]["{$field}_display"] : $value; if ($fields[$field]['type'] == CRM_Utils_Type::T_DATE) { if ($value) { $value = str_replace('-', '', $value); $label = CRM_Utils_Date::customFormat($label); } else { $value = "null"; } } elseif ($fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) { if ($label === '0') { $label = ts('[ ]'); } if ($label === '1') { $label = ts('[x]'); } } $rows["move_{$field}"][$moniker] = $label; if ($moniker == 'other') { if ($value === null) { $value = 'null'; } if ($value === 0 or $value === '0') { $value = $this->_qfZeroBug; } $this->addElement('advcheckbox', "move_{$field}", null, null, null, $value); } } $rows["move_{$field}"]['title'] = $fields[$field]['title']; } // handle location blocks. require_once 'api/v2/Location.php'; $mainParams['version'] = $otherParams['version'] = '3.0'; $locations['main'] =& civicrm_location_get($mainParams); $locations['other'] =& civicrm_location_get($otherParams); $allLocationTypes = CRM_Core_PseudoConstant::locationType(); $mainLocAddress = array(); foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) { $name = strtolower($block); foreach (array('main', 'other') as $moniker) { $blockValue = CRM_Utils_Array::value($name, $locations[$moniker], array()); if (empty($blockValue)) { $locValue[$moniker][$name] = 0; $locLabel[$moniker][$name] = array(); $locTypes[$moniker][$name] = array(); } else { $locValue[$moniker][$name] = true; foreach ($blockValue as $count => $blkValues) { $fldName = $name; $locTypeId = $blkValues['location_type_id']; if ($name == 'im') { $fldName = 'name'; } if ($name == 'address') { $fldName = 'display'; } $locLabel[$moniker][$name][$count] = $blkValues[$fldName]; $locTypes[$moniker][$name][$count] = $locTypeId; if ($moniker == 'main' && $name == 'address') { $mainLocAddress["main_{$locTypeId}"] = $blkValues[$fldName]; $this->_locBlockIds['main']['address'][$locTypeId] = $blkValues['id']; } else { $this->_locBlockIds[$moniker][$name][$count] = $blkValues['id']; } } } } if ($locValue['other'][$name] != 0) { foreach ($locLabel['other'][$name] as $count => $value) { $locTypeId = $locTypes['other'][$name][$count]; $rows["move_location_{$name}_{$count}"]['other'] = $value; $rows["move_location_{$name}_{$count}"]['main'] = $locLabel['main'][$name][$count]; $rows["move_location_{$name}_{$count}"]['title'] = ts('%1:%2:%3', array(1 => $block, 2 => $count, 3 => $allLocationTypes[$locTypeId])); $this->addElement('advcheckbox', "move_location_{$name}_{$count}"); // make sure default location type is always on top $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId); $locTypeValues = $allLocationTypes; $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]); unset($locTypeValues[$mainLocTypeId]); // keep 1-1 mapping for address - location type. $js = null; if ($name == 'address' && !empty($mainLocAddress)) { $js = array('onChange' => "mergeAddress( this, {$count} );"); } $this->addElement('select', "location[{$name}][{$count}][locTypeId]", null, $defaultLocType + $locTypeValues, $js); if ($name != 'address') { $this->addElement('advcheckbox', "location[{$name}][{$count}][operation]", null, ts('add new')); } } } } $this->assign('mainLocAddress', json_encode($mainLocAddress)); // handle custom fields $mainTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, $this->_cid, -1); $otherTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, $this->_oid, -1); if (!isset($diffs['custom'])) { $diffs['custom'] = array(); } foreach ($otherTree as $gid => $group) { $foundField = false; if (!isset($group['fields'])) { continue; } foreach ($group['fields'] as $fid => $field) { if (in_array($fid, $diffs['custom'])) { if (!$foundField) { $rows["custom_group_{$gid}"]['title'] = $group['title']; $foundField = true; } if (is_array($mainTree[$gid]['fields'][$fid]['customValue'])) { foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field); } } if (is_array($otherTree[$gid]['fields'][$fid]['customValue'])) { foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field); $value = $values['data'] ? $values['data'] : $this->_qfZeroBug; } } $rows["move_custom_{$fid}"]['title'] = $field['label']; $this->addElement('advcheckbox', "move_custom_{$fid}", null, null, null, $value); } } } $this->assign('rows', $rows); // add the related tables and unset the ones that don't sport any of the duplicate contact's info $relTables = CRM_Dedupe_Merger::relTables(); $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($oid); foreach ($relTables as $name => $null) { if (!in_array($name, $activeRelTables)) { unset($relTables[$name]); continue; } $this->addElement('checkbox', "move_{$name}"); $relTables[$name]['main_url'] = str_replace('$cid', $cid, $relTables[$name]['url']); $relTables[$name]['other_url'] = str_replace('$cid', $oid, $relTables[$name]['url']); } foreach ($relTables as $name => $null) { $relTables["move_{$name}"] = $relTables[$name]; unset($relTables[$name]); } $this->assign('rel_tables', $relTables); }
/** * Compose a message * * @param int $job_id ID of the Job associated with this message * @param int $event_queue_id ID of the EventQueue * @param string $hash Hash of the EventQueue * @param string $contactId ID of the Contact * @param string $email Destination address * @param string $recipient To: of the recipient * @param boolean $test Is this mailing a test? * @param boolean $isForward Is this mailing compose for forward? * @param string $fromEmail email address of who is forwardinf it. * @return object The mail object * @access public */ public function &compose($job_id, $event_queue_id, $hash, $contactId, $email, &$recipient, $test, $contactDetails, &$attachments, $isForward = false, $fromEmail = null) { require_once 'api/v2/Contact.php'; require_once 'CRM/Utils/Token.php'; require_once 'CRM/Activity/BAO/Activity.php'; $config = CRM_Core_Config::singleton(); $knownTokens = $this->getTokens(); if ($this->_domain == null) { require_once 'CRM/Core/BAO/Domain.php'; $this->_domain =& CRM_Core_BAO_Domain::getDomain(); } list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward); //set from email who is forwarding it and not original one. if ($fromEmail) { unset($headers['From']); $headers['From'] = "<{$fromEmail}>"; } if (defined('CIVICRM_MAIL_SMARTY')) { require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); } if ($contactDetails) { $contact = $contactDetails; } else { $params = array('contact_id' => $contactId); $contact =& civicrm_contact_get($params); //CRM-4524 $contact = reset($contact); if (!$contact || is_a($contact, 'CRM_Core_Error')) { return null; } // also call the hook to get contact details require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id); } $pTemplates = $this->getPreparedTemplates(); $pEmails = array(); foreach ($pTemplates as $type => $pTemplate) { $html = $type == 'html' ? true : false; $pEmails[$type] = array(); $pEmail =& $pEmails[$type]; $template =& $pTemplates[$type]['template']; $tokens =& $pTemplates[$type]['tokens']; $idx = 0; if (!empty($tokens)) { foreach ($tokens as $idx => $token) { $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id); array_push($pEmail, $template[$idx]); array_push($pEmail, $token_data); } } else { array_push($pEmail, $template[$idx]); } if (isset($template[$idx + 1])) { array_push($pEmail, $template[$idx + 1]); } } $html = null; if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) { $html =& $pEmails['html']; } $text = null; if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) { $text =& $pEmails['text']; } // push the tracking url on to the html email if necessary if ($this->open_tracking && $html) { array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL . "extern/open.php?q={$event_queue_id}\" width='1' height='1' alt='' border='0'>"); } $message = new Mail_mime("\n"); if (defined('CIVICRM_MAIL_SMARTY')) { $smarty = CRM_Core_Smarty::singleton(); // also add the contact tokens to the template $smarty->assign_by_ref('contact', $contact); } $mailParams = $headers; if ($text && ($test || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both' || $contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))) { $textBody = join('', $text); if (defined('CIVICRM_MAIL_SMARTY')) { $smarty->security = true; $textBody = $smarty->fetch("string:{$textBody}"); $smarty->security = false; } $mailParams['text'] = $textBody; } if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both'))) { $htmlBody = join('', $html); if (defined('CIVICRM_MAIL_SMARTY')) { $smarty->security = true; $htmlBody = $smarty->fetch("string:{$htmlBody}"); $smarty->security = false; } $mailParams['html'] = $htmlBody; } $mailParams['attachments'] = $attachments; $mailingSubject = CRM_Utils_Array::value('subject', $pEmails); if (is_array($mailingSubject)) { $mailingSubject = join('', $mailingSubject); } $mailParams['Subject'] = $mailingSubject; $mailParams['toName'] = $contact['display_name']; $mailParams['toEmail'] = $email; require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::alterMailParams($mailParams); if (!empty($mailParams['text'])) { $message->setTxtBody($mailParams['text']); } if (!empty($mailParams['html'])) { $message->setHTMLBody($mailParams['html']); } if (!empty($mailParams['attachments'])) { foreach ($mailParams['attachments'] as $fileID => $attach) { $message->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']); } } $headers['To'] = "{$mailParams['toName']} <{$mailParams['toEmail']}>"; $headers['Precedence'] = 'bulk'; // Will test in the mail processor if the X-VERP is set in the bounced email. // (As an option to replace real VERP for those that can't set it up) $headers['X-CiviMail-Bounce'] = $verp['bounce']; //CRM-5058 //token replacement of subject $headers['Subject'] = $mailingSubject; CRM_Utils_Mail::setMimeParams($message); $headers = $message->headers($headers); //get formatted recipient $recipient = $headers['To']; // make sure we unset a lot of stuff unset($verp); unset($urls); unset($params); unset($contact); unset($ids); return $message; }
/** * Test civicrm_contact_get(,true) with one match */ public function testContactGetOldParamsOneMatch() { // Insert a row in civicrm_contact creating contact 17 $op = new PHPUnit_Extensions_Database_Operation_Insert(); $op->execute($this->_dbconn, new PHPUnit_Extensions_Database_DataSet_XMLDataSet(dirname(__FILE__) . '/dataset/contact_17.xml')); $params = array('first_name' => 'Test'); $result = civicrm_contact_get($params, true); $this->assertTrue(is_array($result)); $this->assertFalse(array_key_exists('is_error', $result)); $this->assertEquals(17, $result['contact_id']); }
/** * Build the form * * @access public * @return void */ function buildQuickForm() { $attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur'); $action = CRM_Utils_Array::value('action', $_REQUEST, ''); $cid = CRM_Utils_Request::retrieve('cid', 'Integer', $this); $id = CRM_Utils_Request::retrieve('id', 'Integer', $this); require_once 'api/v2/Contact.php'; $params = array('contact_id' => $cid); $contact_details =& civicrm_contact_get($params); CRM_Utils_System::setTitle('Setup Recurring Payment - ' . $contact_details[$cid]['display_name']); //$mandatIdArray = array(''=>'--select--'); $sql = "SELECT * FROM civicrm_value_bank_details WHERE entity_id = '{$cid}'"; //AND authorization_date IS NOT NULL AND authorization_file IS NOT NULL $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { $mandatIdArray[$dao->id] = $dao->id; } //$form->add( 'text', 'mandate_id', ts('Mandate ID'), array( 'maxlength' => 10 ) , false ); //echo $action;exit; if ($action == 'update') { $sql = "SELECT * FROM civicrm_contribution_recur WHERE id = '{$id}'"; $dao = CRM_Core_DAO::executeQuery($sql); if ($dao->fetch()) { $defaults = array('amount' => $dao->amount, 'frequency_interval' => $dao->frequency_interval, 'frequency_unit' => $dao->frequency_unit, 'start_date' => $dao->start_date, 'processor_id' => $dao->processor_id, 'next_sched_contribution' => $dao->next_sched_contribution); if (CRM_Utils_Array::value('start_date', $defaults) && !empty($dao->start_date) && $dao->start_date != '0000-00-00') { list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['start_date'], 'activityDate'); } else { $defaults['start_date'] = ""; } if (CRM_Utils_Array::value('next_sched_contribution', $defaults) && !empty($dao->next_sched_contribution) && $dao->next_sched_contribution != '0000-00-00') { list($defaults['next_sched_contribution'], $defaults['next_sched_contribution_time']) = CRM_Utils_Date::setDateDefaults($defaults['next_sched_contribution'], 'activityDate'); } else { $defaults['next_sched_contribution'] = ""; } } $this->addElement('hidden', 'id', $id); } if (count($mandatIdArray) == 0) { require_once 'CRM/Utils/Type.php'; $customGroupName = CRM_Utils_Type::escape('Direct_Debit_Mandate', 'String'); $DDMandategroupId = CRM_Core_DAO::getFieldValue("CRM_Core_DAO_CustomGroup", $customGroupName, 'id', 'name'); $this->assign('no_mandate_for_contact', 1); $this->assign('groupId', $DDMandategroupId); } $this->add('select', 'processor_id', ts('Mandate ID'), $mandatIdArray, true); $this->add('text', 'amount', ts('Amount'), $attributes['label'], true); $this->add('text', 'frequency_interval', ts('Every'), array('maxlength' => 2, 'size' => 2), true); //$form->addRule( 'frequency_interval', // ts( 'Frequency must be a whole number (EXAMPLE: Every 3 months).' ), 'integer' ); $frUnits = implode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_OptionGroup::values('recur_frequency_units')); $units = array(); $unitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $frUnits); $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units'); foreach ($unitVals as $key => $val) { if (array_key_exists($val, $frequencyUnits)) { $units[$val] = $frequencyUnits[$val]; if (CRM_Utils_Array::value('is_recur_interval', $form->_values) || $className == 'CRM_Contribute_Form_Contribution') { $units[$val] = "{$frequencyUnits[$val]}(s)"; } } } $frequencyUnit =& $this->add('select', 'frequency_unit', null, $units, true); // FIXME: Ideally we should freeze select box if there is only // one option but looks there is some problem /w QF freeze. //if ( count( $units ) == 1 ) { //$frequencyUnit->freeze( ); //} //$this->add( 'text', 'installments', ts( 'installments' ), $attributes['installments'] ); $this->addDate('start_date', ts('Start Date'), true, array('formatType' => 'activityDate')); $this->addDate('next_sched_contribution', ts('Next Scheduled Date'), true, array('formatType' => 'activityDate')); $this->addDate('end_date', ts('End Date'), false, array('formatType' => 'activityDate')); $this->setDefaults($defaults); $this->addElement('hidden', 'action', $action); $this->addElement('hidden', 'cid', $cid); $this->assign('cid', $cid); //$this->addFormRule( array( 'CRM_Package_Form_Package', 'formRule' ) ); $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'spacing' => ' ', 'isDefault' => true))); }
function civicrm_pcp_search_owner(&$params) { if( ! is_array($params) ) { return civicrm_create_error( 'Params need to be of type array!' ); } civicrm_verify_mandatory ($params,null,array ('search')); require_once 'api/v2/Contact.php'; $search_term = CRM_Utils_Array::value( 'search', $params, TRUE ); $query = "SELECT DISTINCT(cc.id) as id, pcp.title, CONCAT_WS( ' :: ', display_name, sort_name, email, phone, street_address, city, ste.name, coy.name ) as data FROM civicrm_pcp pcp left join civicrm_contact cc on ( pcp.contact_id = cc.id ) LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 ) LEFT JOIN civicrm_phone phe ON ( cc.id = phe.contact_id AND phe.is_primary = 1 ) LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) LEFT JOIN civicrm_state_province ste ON ( sts.state_province_id = ste.id ) LEFT JOIN civicrm_country coy ON ( sts.country_id = coy.id ) WHERE pcp.title like '%" . mysql_real_escape_string($search_term) . "%' or sort_name LIKE '%" . mysql_real_escape_string($search_term) . "%' or display_name LIKE '%" . mysql_real_escape_string($search_term) . "%' ORDER BY sort_name"; $dao = CRM_Core_DAO::executeQuery( $query ); while ( $dao->fetch( ) ) { // we don't care about our very strange data string //$civi_matches[$dao->id] = $dao->data; $params = array( 'contact_id' => $dao->id ); $contact = civicrm_contact_get($params); $contact = array_pop($contact); $contact['pcp_title'] = $dao->title; $civi_matches[$dao->id] = $contact; } $results = array('Results' => $civi_matches); return $results; }
/** * Compose a message * * @param int $job_id ID of the Job associated with this message * @param int $event_queue_id ID of the EventQueue * @param string $hash Hash of the EventQueue * @param string $contactId ID of the Contact * @param string $email Destination address * @param string $recipient To: of the recipient * @param boolean $test Is this mailing a test? * @param boolean $isForward Is this mailing compose for forward? * @param string $fromEmail email address of who is forwardinf it. * @return object The mail object * @access public */ public function &compose($job_id, $event_queue_id, $hash, $contactId, $email, &$recipient, $test, $contactDetails, &$attachments, $isForward = false, $fromEmail = null) { require_once 'api/v2/Contact.php'; require_once 'CRM/Utils/Token.php'; require_once 'CRM/Activity/BAO/Activity.php'; $config =& CRM_Core_Config::singleton(); $knownTokens = $this->getTokens(); if ($this->_domain == null) { require_once 'CRM/Core/BAO/Domain.php'; $this->_domain =& CRM_Core_BAO_Domain::getDomain(); } list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward); //set from email who is forwarding it and not original one. if ($fromEmail) { unset($headers['From']); $headers['From'] = "<{$fromEmail}>"; } if ($contactDetails) { $contact = $contactDetails; } else { $params = array('contact_id' => $contactId); $contact =& civicrm_contact_get($params); //CRM-4524 $contact = reset($contact); if (!$contact || is_a($contact, 'CRM_Core_Error')) { return null; } // also call the hook to get contact details require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id); } $pTemplates = $this->getPreparedTemplates(); $pEmails = array(); foreach ($pTemplates as $type => $pTemplate) { $html = $type == 'html' ? true : false; $pEmails[$type] = array(); $pEmail =& $pEmails[$type]; $template =& $pTemplates[$type]['template']; $tokens =& $pTemplates[$type]['tokens']; $idx = 0; if (!empty($tokens)) { foreach ($tokens as $idx => $token) { $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id); array_push($pEmail, $template[$idx]); array_push($pEmail, $token_data); } } else { array_push($pEmail, $template[$idx]); } if (isset($template[$idx + 1])) { array_push($pEmail, $template[$idx + 1]); } } $html = null; if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) { $html =& $pEmails['html']; } $text = null; if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) { $text =& $pEmails['text']; } // push the tracking url on to the html email if necessary if ($this->open_tracking && $html) { array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL . "extern/open.php?q={$event_queue_id}\" width='1' height='1' alt='' border='0'>"); } // we need to wrap Mail_mime because PEAR is apparently unable to fix // a six-year-old bug (PEAR bug #30) in Mail_mime::_encodeHeaders() // this fixes CRM-5466 require_once 'CRM/Utils/Mail/FixedMailMIME.php'; $message =& new CRM_Utils_Mail_FixedMailMIME("\n"); if (defined('CIVICRM_MAIL_SMARTY')) { $smarty =& CRM_Core_Smarty::singleton(); // also add the contact tokens to the template $smarty->assign_by_ref('contact', $contact); } if ($text && ($test || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both' || $contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))) { $textBody = join('', $text); if (defined('CIVICRM_MAIL_SMARTY')) { $textBody = $smarty->fetch("string:{$textBody}"); } $message->setTxtBody($textBody); } if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both'))) { $htmlBody = join('', $html); if (defined('CIVICRM_MAIL_SMARTY')) { $htmlBody = $smarty->fetch("string:{$htmlBody}"); } $message->setHTMLBody($htmlBody); } if (!empty($attachments)) { foreach ($attachments as $fileID => $attach) { $message->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']); } } $recipient = "{$contact['display_name']} <{$email}>"; $headers['To'] = $recipient; //CRM-5058 //token replacement of subject $headers['Subject'] = join('', $pEmails['subject']); CRM_Utils_Mail::setMimeParams($message); $message->headers($headers); // make sure we unset a lot of stuff unset($verp); unset($urls); unset($params); unset($contact); unset($ids); return $message; }