/** * Test retrieve Soft Contribution through AJAX */ public function testGetSoftContributionSelector() { $softTypes = array(3, 2, 5); $amounts = array('100', '600', '150'); // create sample soft contribution for contact foreach ($this->_primaryContacts as $seq => $contactId) { $this->callAPISuccess('Contribution', 'create', array('contact_id' => $contactId, 'receive_date' => date('Ymd'), 'total_amount' => $amounts[$seq], 'financial_type_id' => 1, 'non_deductible_amount' => '10', 'contribution_status_id' => 1, 'soft_credit' => array('1' => array('contact_id' => $this->_softContactId, 'amount' => $amounts[$seq], 'soft_credit_type_id' => $softTypes[$seq])))); } $_GET = array_merge($this->_params, array('cid' => $this->_softContactId, 'context' => 'contribution')); $softCreditList = CRM_Contribute_Page_AJAX::getSoftContributionRows(); foreach ($this->_fields as $columnName) { $_GET['columns'][] = array('data' => $columnName); } // get the results in descending order $_GET['order'] = array('0' => array('column' => 0, 'dir' => 'desc')); $amountSortedList = CRM_Contribute_Page_AJAX::getSoftContributionRows(); $this->assertEquals(3, $softCreditList['recordsTotal']); $this->assertEquals(3, $amountSortedList['recordsTotal']); rsort($amounts); foreach ($amounts as $key => $amount) { $amount = CRM_Utils_Money::format($amount, 'USD'); $this->assertEquals($amount, $amountSortedList['data'][$key]['amount']); } // sort with soft credit types $_GET['order'][0]['column'] = 1; foreach ($softTypes as $id) { $softLabels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $id); } rsort($softLabels); $softTypeSortedList = CRM_Contribute_Page_AJAX::getSoftContributionRows(); foreach ($softLabels as $key => $labels) { $this->assertEquals($labels, $softTypeSortedList['data'][$key]['sct_label']); } }
/** * Get CiviCRM domain details * {@getfields domain_create} * @example DomainGet.php */ function civicrm_api3_domain_get($params) { $params['version'] = CRM_Utils_Array::value('domain_version', $params); unset($params['version']); $bao = new CRM_Core_BAO_Domain(); if (CRM_Utils_Array::value('current_domain', $params)) { $domainBAO = CRM_Core_Config::domainID(); $params['id'] = $domainBAO; } _civicrm_api3_dao_set_filter($bao, $params, true, 'domain'); $domains = _civicrm_api3_dao_to_array($bao, $params, true, 'domain'); foreach ($domains as $domain) { if (!empty($domain['contact_id'])) { $values = array(); $locparams = array('contact_id' => $domain['contact_id']); $values['location'] = CRM_Core_BAO_Location::getValues($locparams, TRUE); $address_array = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'state_province_id', 'postal_code', 'country_id', 'geo_code_1', 'geo_code_2'); if (!empty($values['location']['email'])) { $domain['domain_email'] = CRM_Utils_Array::value('email', $values['location']['email'][1]); } if (!empty($values['location']['phone'])) { $domain['domain_phone'] = array('phone_type' => CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', CRM_Utils_Array::value('phone_type_id', $values['location']['phone'][1])), 'phone' => CRM_Utils_Array::value('phone', $values['location']['phone'][1])); } if (!empty($values['location']['address'])) { foreach ($address_array as $value) { $domain['domain_address'][$value] = CRM_Utils_Array::value($value, $values['location']['address'][1]); } } list($domain['from_name'], $domain['from_email']) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE); $domains[$domain['id']] = array_merge($domains[$domain['id']], $domain); } } return civicrm_api3_create_success($domains, $params, 'domain', 'get', $bao); }
/** * View details of a recurring contribution. */ public function view() { $recur = new CRM_Contribute_DAO_ContributionRecur(); $recur->id = $this->_id; if ($recur->find(TRUE)) { $values = array(); CRM_Core_DAO::storeValues($recur, $values); // if there is a payment processor ID, get the name of the payment processor if (!empty($values['payment_processor_id'])) { $values['payment_processor'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $values['payment_processor_id'], 'name'); } $idFields = array('contribution_status_id', 'campaign_id'); if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($values['id'])) { $idFields[] = 'financial_type_id'; } foreach ($idFields as $idField) { if (!empty($values[$idField])) { $values[substr($idField, 0, -3)] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', $idField, $values[$idField]); } } // Get financial type name if (!empty($values['financial_type_id'])) { $values['financial_type_name'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'financial_type_id', $values['financial_type_id']); } // Get Paid By label if (!empty($values['payment_instrument_id'])) { $values['payment_instrument'] = CRM_Core_OptionGroup::getLabel('payment_instrument', $values['payment_instrument_id']); } $this->assign('recur', $values); $this->assign('customDataType', 'ContributionRecur'); $groupTree = CRM_Core_BAO_CustomGroup::getTree('ContributionRecur', $this, $this->_id); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); } }
/** * View details of a note. */ public function view() { $note = new CRM_Core_DAO_Note(); $note->id = $this->_id; if ($note->find(TRUE)) { $values = array(); CRM_Core_DAO::storeValues($note, $values); $values['privacy'] = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Note', 'privacy', $values['privacy']); $this->assign('note', $values); } $comments = CRM_Core_BAO_Note::getNoteTree($values['id'], 1); if (!empty($comments)) { $this->assign('comments', $comments); } // add attachments part $currentAttachmentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_note', $this->_id); $this->assign('currentAttachmentInfo', $currentAttachmentInfo); }
/** * View details of a recurring contribution. */ public function view() { $recur = new CRM_Contribute_DAO_ContributionRecur(); $recur->id = $this->_id; if ($recur->find(TRUE)) { $values = array(); CRM_Core_DAO::storeValues($recur, $values); // if there is a payment processor ID, get the name of the payment processor if (!empty($values['payment_processor_id'])) { $values['payment_processor'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $values['payment_processor_id'], 'name'); } // get contribution status label if (!empty($values['contribution_status_id'])) { $values['contribution_status'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', 'contribution_status_id', $values['contribution_status_id']); } $this->assign('recur', $values); } }
/** * View details of a recurring contribution. */ public function view() { $recur = new CRM_Contribute_DAO_ContributionRecur(); $recur->id = $this->_id; if ($recur->find(TRUE)) { $values = array(); CRM_Core_DAO::storeValues($recur, $values); // if there is a payment processor ID, get the name of the payment processor if (!empty($values['payment_processor_id'])) { $values['payment_processor'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $values['payment_processor_id'], 'name'); } $idFields = array('contribution_status_id', 'campaign_id'); if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($values['id'])) { $idFields[] = 'financial_type_id'; } foreach ($idFields as $idField) { if (!empty($values[$idField])) { $values[substr($idField, 0, -3)] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', $idField, $values[$idField]); } } $this->assign('recur', $values); } }
/** * returns all the rows in the given offset and rowCount * * @param enum $action the action being performed * @param int $offset the row number to start from * @param int $rowCount the number of rows to return * @param string $sort the sql string that describes the sort order * @param enum $output what should the result set include (web/email/csv) * * @return int the total number of rows for this action */ function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { $multipleFields = array('url'); //$sort object processing for location fields if ($sort) { $vars = $sort->_vars; $varArray = array(); foreach ($vars as $key => $field) { $field = $vars[$key]; $fieldArray = explode('-', $field['name']); $fieldType = CRM_Utils_Array::value('2', $fieldArray); if (is_numeric(CRM_Utils_Array::value('1', $fieldArray))) { if (!in_array($fieldType, $multipleFields)) { $locationType = new CRM_Core_DAO_LocationType(); $locationType->id = $fieldArray[1]; $locationType->find(TRUE); if ($fieldArray[0] == 'email' || $fieldArray[0] == 'im' || $fieldArray[0] == 'phone') { $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "-1`"; } else { $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "`"; } } else { $field['name'] = "`website-" . $fieldArray[1] . "-{$fieldType}`"; } } $varArray[$key] = $field; } $sort->_vars = $varArray; } $additionalWhereClause = 'contact_a.is_deleted = 0'; $returnQuery = NULL; if ($this->_multiRecordTableName) { $returnQuery = TRUE; } $result = $this->_query->searchQuery($offset, $rowCount, $sort, NULL, NULL, NULL, NULL, $returnQuery, $additionalWhereClause); if ($returnQuery) { $resQuery = preg_replace('/GROUP BY contact_a.id[\\s]+ORDER BY/', ' ORDER BY', $result); $result = CRM_Core_DAO::executeQuery($resQuery); } // process the result of the query $rows = array(); // check if edit is configured in profile settings if ($this->_gid) { $editLink = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'is_edit_link'); } //FIXME : make sure to handle delete separately. CRM-4418 $mask = CRM_Core_Action::mask(array(CRM_Core_Permission::getPermission())); if ($editLink && $mask & CRM_Core_Permission::EDIT) { // do not allow edit for anon users in joomla frontend, CRM-4668 $config = CRM_Core_Config::singleton(); if (!$config->userFrameworkFrontend) { $this->_editLink = TRUE; } } $links = self::links($this->_map, $this->_editLink, $this->_linkToUF, $this->_profileIds); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $names = array(); static $skipFields = array('group', 'tag'); foreach ($this->_fields as $key => $field) { // skip pseudo fields if (substr($key, 0, 9) == 'phone_ext') { continue; } if (!empty($field['in_selector']) && !in_array($key, $skipFields)) { if (strpos($key, '-') !== FALSE) { $value = explode('-', $key); $fieldName = CRM_Utils_Array::value(0, $value); $id = CRM_Utils_Array::value(1, $value); $type = CRM_Utils_Array::value(2, $value); if (!in_array($fieldName, $multipleFields)) { $locationTypeName = NULL; if (is_numeric($id)) { $locationTypeName = CRM_Utils_Array::value($id, $locationTypes); } else { if ($id == 'Primary') { $locationTypeName = 1; } } if (!$locationTypeName) { continue; } $locationTypeName = str_replace(' ', '_', $locationTypeName); if (in_array($fieldName, array('phone', 'im', 'email'))) { if ($type) { $names[] = "{$locationTypeName}-{$fieldName}-{$type}"; } else { $names[] = "{$locationTypeName}-{$fieldName}"; } } else { $names[] = "{$locationTypeName}-{$fieldName}"; } } else { $names[] = "website-{$id}-{$fieldName}"; } } elseif ($field['name'] == 'id') { $names[] = 'contact_id'; } else { $names[] = $field['name']; } } } $multipleSelectFields = array('preferred_communication_method' => 1); $multiRecordTableId = NULL; if ($this->_multiRecordTableName) { $multiRecordTableId = "{$this->_multiRecordTableName}_id"; } // we need to determine of overlay profile should be shown $showProfileOverlay = CRM_Core_BAO_UFGroup::showOverlayProfile(); while ($result->fetch()) { $this->_query->convertToPseudoNames($result); if (isset($result->country)) { // the query returns the untranslated country name $i18n = CRM_Core_I18n::singleton(); $result->country = $i18n->translate($result->country); } $row = array(); $empty = TRUE; $row[] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id, $showProfileOverlay); if ($result->sort_name) { $row[] = $result->sort_name; $empty = FALSE; } else { continue; } foreach ($names as $name) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $row[] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$name}, $cfID, $this->_options, $result->contact_id); } elseif (substr($name, -4) == '-url' && !empty($result->{$name})) { $url = CRM_Utils_System::fixURL($result->{$name}); $typeId = substr($name, 0, -4) . "-website_type_id"; $typeName = CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Website', 'website_type_id', $result->{$typeId}); if ($typeName) { $row[] = "<a href=\"{$url}\">{$result->{$name}} ({$typeName})</a>"; } else { $row[] = "<a href=\"{$url}\">{$result->{$name}}</a>"; } } elseif ($name == 'preferred_language') { $row[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $result->{$name}); } elseif ($multipleSelectFields && array_key_exists($name, $multipleSelectFields)) { $paramsNew = array($name => $result->{$name}); $name = array($name => array('newName' => $name, 'groupName' => $name)); CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE); $row[] = $paramsNew[$key]; } elseif (strpos($name, '-im')) { if (!empty($result->{$name})) { $providerId = $name . "-provider_id"; $providerName = CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $result->{$providerId}); $row[] = $result->{$name} . " ({$providerName})"; } else { $row[] = ''; } } elseif (strpos($name, '-phone-')) { $phoneExtField = str_replace('phone', 'phone_ext', $name); if (isset($result->{$phoneExtField})) { $row[] = $result->{$name} . " (" . $result->{$phoneExtField} . ")"; } else { $row[] = $result->{$name}; } } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) { $dname = $name . '_display'; $row[] = $result->{$dname}; } elseif (in_array($name, array('birth_date', 'deceased_date'))) { $row[] = CRM_Utils_Date::customFormat($result->{$name}); } elseif (isset($result->{$name})) { $row[] = $result->{$name}; } else { $row[] = ''; } if (!empty($result->{$name})) { $empty = FALSE; } } $newLinks = $links; $params = array('id' => $result->contact_id, 'gid' => implode(',', $this->_profileIds)); // pass record id param to view url for multi record view if ($multiRecordTableId && $newLinks) { if ($result->{$multiRecordTableId}) { if ($newLinks[CRM_Core_Action::VIEW]['url'] == 'civicrm/profile/view') { $newLinks[CRM_Core_Action::VIEW]['qs'] .= "&multiRecord=view&recordId=%%recordId%%&allFields=1"; $params['recordId'] = $result->{$multiRecordTableId}; } } } if ($this->_linkToUF) { $ufID = CRM_Core_BAO_UFMatch::getUFId($result->contact_id); if (!$ufID) { unset($newLinks[CRM_Core_Action::PROFILE]); } else { $params['ufID'] = $ufID; } } $row[] = CRM_Core_Action::formLink($newLinks, $mask, $params, ts('more'), FALSE, 'profile.selector.row', 'Contact', $result->contact_id); if (!$empty) { $rows[] = $row; } } return $rows; }
/** * Get output of financial transactions. * * @param bool $return * Return result. This parameter allows the output to be unit tested. * * @return string */ public static function getFinancialTransactionsList($return = FALSE) { $sortMapper = array(0 => '', 1 => '', 2 => 'sort_name', 3 => 'amount', 4 => 'trxn_id', 5 => 'transaction_date', 6 => 'payment_method', 7 => 'status', 8 => 'name'); $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer'); $return = isset($_REQUEST['return']) ? CRM_Utils_Type::escape($_REQUEST['return'], 'Boolean') : FALSE; $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0; $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25; $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL; $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc'; $context = isset($_REQUEST['context']) ? CRM_Utils_Type::escape($_REQUEST['context'], 'String') : NULL; $entityID = isset($_REQUEST['entityID']) ? CRM_Utils_Type::escape($_REQUEST['entityID'], 'String') : NULL; $notPresent = isset($_REQUEST['notPresent']) ? CRM_Utils_Type::escape($_REQUEST['notPresent'], 'String') : NULL; $statusID = isset($_REQUEST['statusID']) ? CRM_Utils_Type::escape($_REQUEST['statusID'], 'String') : NULL; $search = isset($_REQUEST['search']) ? TRUE : FALSE; $params = $_POST; if ($sort && $sortOrder) { $params['sortBy'] = $sort . ' ' . $sortOrder; } $returnvalues = array('civicrm_financial_trxn.payment_instrument_id as payment_method', 'civicrm_contribution.contact_id as contact_id', 'civicrm_contribution.id as contributionID', 'contact_a.sort_name', 'civicrm_financial_trxn.total_amount as amount', 'civicrm_financial_trxn.trxn_id as trxn_id', 'contact_a.contact_type', 'contact_a.contact_sub_type', 'civicrm_financial_trxn.trxn_date as transaction_date', 'name', 'civicrm_contribution.currency as currency', 'civicrm_financial_trxn.status_id as status', 'civicrm_financial_trxn.check_number as check_number'); $columnHeader = array('contact_type' => '', 'sort_name' => ts('Contact Name'), 'amount' => ts('Amount'), 'trxn_id' => ts('Trxn ID'), 'transaction_date' => ts('Received'), 'payment_method' => ts('Payment Method'), 'status' => ts('Status'), 'name' => ts('Type')); if ($sort && $sortOrder) { $params['sortBy'] = $sort . ' ' . $sortOrder; } $params['page'] = $offset / $rowCount + 1; $params['rp'] = $rowCount; $params['context'] = $context; $params['offset'] = ($params['page'] - 1) * $params['rp']; $params['rowCount'] = $params['rp']; $params['sort'] = CRM_Utils_Array::value('sortBy', $params); $params['total'] = 0; // get batch list if (isset($notPresent)) { $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params); if ($search) { $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, $params, TRUE); } else { $unassignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, $notPresent, NULL, TRUE); } while ($unassignedTransactions->fetch()) { $unassignedTransactionsCount[] = $unassignedTransactions->id; } if (!empty($unassignedTransactionsCount)) { $params['total'] = count($unassignedTransactionsCount); } } else { $financialItem = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues, NULL, $params); $assignedTransactions = CRM_Batch_BAO_Batch::getBatchFinancialItems($entityID, $returnvalues); while ($assignedTransactions->fetch()) { $assignedTransactionsCount[] = $assignedTransactions->id; } if (!empty($assignedTransactionsCount)) { $params['total'] = count($assignedTransactionsCount); } } $financialitems = array(); while ($financialItem->fetch()) { $row[$financialItem->id] = array(); foreach ($columnHeader as $columnKey => $columnValue) { if ($financialItem->contact_sub_type && $columnKey == 'contact_type') { $row[$financialItem->id][$columnKey] = $financialItem->contact_sub_type; continue; } $row[$financialItem->id][$columnKey] = $financialItem->{$columnKey}; if ($columnKey == 'sort_name' && $financialItem->{$columnKey}) { $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid=" . $financialItem->contact_id); $row[$financialItem->id][$columnKey] = '<a href=' . $url . '>' . $financialItem->{$columnKey} . '</a>'; } elseif ($columnKey == 'payment_method' && $financialItem->{$columnKey}) { $row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $financialItem->{$columnKey}); if ($row[$financialItem->id][$columnKey] == 'Check') { $checkNumber = $financialItem->check_number ? ' (' . $financialItem->check_number . ')' : ''; $row[$financialItem->id][$columnKey] = $row[$financialItem->id][$columnKey] . $checkNumber; } } elseif ($columnKey == 'amount' && $financialItem->{$columnKey}) { $row[$financialItem->id][$columnKey] = CRM_Utils_Money::format($financialItem->{$columnKey}, $financialItem->currency); } elseif ($columnKey == 'transaction_date' && $financialItem->{$columnKey}) { $row[$financialItem->id][$columnKey] = CRM_Utils_Date::customFormat($financialItem->{$columnKey}); } elseif ($columnKey == 'status' && $financialItem->{$columnKey}) { $row[$financialItem->id][$columnKey] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $financialItem->{$columnKey}); } } if ($statusID == CRM_Core_OptionGroup::getValue('batch_status', 'Open')) { if (isset($notPresent)) { $js = "enableActions('x')"; $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_x_" . $financialItem->id . "' name='mark_x_" . $financialItem->id . "' value='1' onclick={$js}></input>"; $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(CRM_Financial_Form_BatchTransaction::links(), NULL, array('id' => $financialItem->id, 'contid' => $financialItem->contributionID, 'cid' => $financialItem->contact_id), ts('more'), FALSE, 'financialItem.batch.row', 'FinancialItem', $financialItem->id); } else { $js = "enableActions('y')"; $row[$financialItem->id]['check'] = "<input type='checkbox' id='mark_y_" . $financialItem->id . "' name='mark_y_" . $financialItem->id . "' value='1' onclick={$js}></input>"; $row[$financialItem->id]['action'] = CRM_Core_Action::formLink(CRM_Financial_Page_BatchTransaction::links(), NULL, array('id' => $financialItem->id, 'contid' => $financialItem->contributionID, 'cid' => $financialItem->contact_id), ts('more'), FALSE, 'financialItem.batch.row', 'FinancialItem', $financialItem->id); } } else { $row[$financialItem->id]['check'] = NULL; $tempBAO = new CRM_Financial_Page_BatchTransaction(); $links = $tempBAO->links(); unset($links['remove']); $row[$financialItem->id]['action'] = CRM_Core_Action::formLink($links, NULL, array('id' => $financialItem->id, 'contid' => $financialItem->contributionID, 'cid' => $financialItem->contact_id), ts('more'), FALSE, 'financialItem.batch.row', 'FinancialItem', $financialItem->id); } $row[$financialItem->id]['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage(CRM_Utils_Array::value('contact_sub_type', $row[$financialItem->id]) ? CRM_Utils_Array::value('contact_sub_type', $row[$financialItem->id]) : CRM_Utils_Array::value('contact_type', $row[$financialItem->id]), FALSE, $financialItem->contact_id); $financialitems = $row; } $iFilteredTotal = $iTotal = $params['total']; $selectorElements = array('check', 'contact_type', 'sort_name', 'amount', 'trxn_id', 'transaction_date', 'payment_method', 'status', 'name', 'action'); if ($return) { return CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements); } CRM_Utils_System::setHttpHeader('Content-Type', 'application/json'); echo CRM_Utils_JSON::encodeDataTableSelector($financialitems, $sEcho, $iTotal, $iFilteredTotal, $selectorElements); CRM_Utils_System::civiExit(); }
/** * Populate option labels for this object's fields. * * @throws exception if called directly on the base class */ public function getOptionLabels() { $fields = $this->fields(); if ($fields === NULL) { throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO'); } foreach ($fields as $field) { $name = CRM_Utils_Array::value('name', $field); if ($name && isset($this->{$name})) { $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->{$name}); if ($label !== FALSE) { // Append 'label' onto the field name $labelName = $name . '_label'; $this->{$labelName} = $label; } } } }
/** * @param $rows */ function alterDisplay(&$rows) { // custom code to alter rows $entryFound = FALSE; foreach ($rows as $rowNum => $row) { if (array_key_exists('civicrm_grant_grant_type_id', $row)) { if ($value = $row['civicrm_grant_grant_type_id']) { $rows[$rowNum]['civicrm_grant_grant_type_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Grant_DAO_Grant', 'grant_type_id', $value); } $entryFound = TRUE; } if (array_key_exists('civicrm_grant_status_id', $row)) { if ($value = $row['civicrm_grant_status_id']) { $rows[$rowNum]['civicrm_grant_status_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Grant_DAO_Grant', 'status_id', $value); } $entryFound = TRUE; } if (array_key_exists('civicrm_grant_grant_report_received', $row)) { if ($value = $row['civicrm_grant_grant_report_received']) { if ($value == 1) { $value = 'Yes'; } else { $value = 'No'; } $rows[$rowNum]['civicrm_grant_grant_report_received'] = $value; } $entryFound = TRUE; } if (!$entryFound) { break; } } }
/** * Format getlist output * * @see _civicrm_api3_generic_getlist_output * * @param array $result * @param array $request * @param string $entity * @param array $fields * * @return array */ function _civicrm_api3_uf_group_getlist_output($result, $request, $entity, $fields) { $output = array(); if (!empty($result['values'])) { foreach ($result['values'] as $row) { $data = array('id' => $row[$request['id_field']], 'label' => $row[$request['label_field']]); if (!empty($request['description_field'])) { $data['description'] = array(); foreach ((array) $request['description_field'] as $field) { if (!empty($row[$field])) { // Special formatting for group_type field if ($field == 'group_type') { $groupTypes = CRM_UF_Page_Group::extractGroupTypes($row[$field]); $data['description'][] = CRM_UF_Page_Group::formatGroupTypes($groupTypes); continue; } if (!isset($fields[$field]['pseudoconstant'])) { $data['description'][] = $row[$field]; } else { $data['description'][] = CRM_Core_PseudoConstant::getLabel(_civicrm_api3_get_BAO($entity), $field, $row[$field]); } } } } if (!empty($request['image_field'])) { $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : ''; } $output[] = $data; } } return $output; }
/** * @param $token * @param $contact * @param bool $html * @param bool $returnBlankToken * @param bool $escapeSmarty * * @return bool|mixed|null|string */ public static function getContactTokenReplacement($token, &$contact, $html = FALSE, $returnBlankToken = FALSE, $escapeSmarty = FALSE) { if (self::$_tokens['contact'] == NULL) { /* This should come from UF */ self::$_tokens['contact'] = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields('All')), array('checksum', 'contact_id')); } // Construct value from $token and $contact $value = NULL; $noReplace = FALSE; // Support legacy tokens $token = CRM_Utils_Array::value($token, self::legacyContactTokens(), $token); // check if the token we were passed is valid // we have to do this because this function is // called only when we find a token in the string if (!in_array($token, self::$_tokens['contact'])) { $noReplace = TRUE; } elseif ($token == 'checksum') { $hash = CRM_Utils_Array::value('hash', $contact); $contactID = CRM_Utils_Array::retrieveValueRecursive($contact, 'contact_id'); $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID, NULL, NULL, $hash); $value = "cs={$cs}"; } else { $value = CRM_Utils_Array::retrieveValueRecursive($contact, $token); // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label ) if (is_array($value)) { $value = $value[1]; } elseif ($value && is_numeric($value)) { $allFields = CRM_Contact_BAO_Contact::exportableFields('All'); if (!empty($allFields[$token]['pseudoconstant'])) { $value = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $token, $value); } } } if (!$html) { $value = str_replace('&', '&', $value); } // if null then return actual token if ($returnBlankToken && !$value) { $noReplace = TRUE; } if ($noReplace) { $value = "{contact.{$token}}"; } if ($escapeSmarty && !($returnBlankToken && $noReplace)) { // $returnBlankToken means the caller wants to do further attempts at // processing unreplaced tokens -- so don't escape them yet in this case. $value = self::tokenEscapeSmarty($value); } return $value; }
/** * Where clause for a single field. * * CRM-17120 adds a test that checks the Qill on some of these parameters. * However, I couldn't find a way, other than via test, to access the * case_activity options in the code below and invalid sql was returned. * Perhaps the options are just legacy? * * Also, CRM-17120 locks in the Qill - but it probably is not quite right as I * see 'Activity Type = Scheduled' (rather than activity status). * * See CRM_Case_BAO_QueryTest for more. * * @param array $values * @param CRM_Contact_BAO_Query $query */ public static function whereClauseSingle(&$values, &$query) { list($name, $op, $value, $grouping, $wildcard) = $values; $val = $names = array(); switch ($name) { case 'case_type_id': case 'case_type': case 'case_status': case 'case_status_id': case 'case_id': if (strpos($name, 'type')) { $name = 'case_type_id'; $label = 'Case Type(s)'; } elseif (strpos($name, 'status')) { $name = 'status_id'; $label = 'Case Status(s)'; } else { $name = 'id'; $label = 'Case ID'; } $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.{$name}", $op, $value, "Integer"); list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Case_DAO_Case', $name, $value, $op); $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $label, 2 => $op, 3 => $value)); $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; return; case 'case_owner': case 'case_mycases': if (!empty($value)) { if ($value == 2) { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_relationship.contact_id_b", $op, $userID, 'Int'); $query->_qill[$grouping][] = ts('Case %1 My Cases', array(1 => $op)); $query->_tables['case_relationship'] = $query->_whereTables['case_relationship'] = 1; } elseif ($value == 1) { $query->_qill[$grouping][] = ts('Case %1 All Cases', array(1 => $op)); $query->_where[$grouping][] = "civicrm_case_contact.contact_id = contact_a.id"; } $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; } return; case 'case_deleted': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.is_deleted", $op, $value, 'Boolean'); if ($value) { $query->_qill[$grouping][] = ts("Find Deleted Cases"); } $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; return; case 'case_activity_subject': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.subject", $op, $value, 'String'); $query->_qill[$grouping][] = ts("Activity Subject %1 '%2'", array(1 => $op, 2 => $value)); $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_subject': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.subject", $op, $value, 'String'); $query->_qill[$grouping][] = ts("Case Subject %1 '%2'", array(1 => $op, 2 => $value)); $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_source_contact_id': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case_reporter.sort_name", $op, $value, 'String'); $query->_qill[$grouping][] = ts("Activity Reporter %1 '%2'", array(1 => $op, 2 => $value)); $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case_reporter'] = $query->_whereTables['civicrm_case_reporter'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_recent_activity_date': $date = CRM_Utils_Date::format($value); $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_date_time", $op, $date, 'Date'); if ($date) { $date = CRM_Utils_Date::customFormat($date); $query->_qill[$grouping][] = ts("Activity Actual Date %1 %2", array(1 => $op, 2 => $date)); } $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_scheduled_activity_date': $date = CRM_Utils_Date::format($value); $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_date_time", $op, $date, 'Date'); if ($date) { $date = CRM_Utils_Date::customFormat($date); $query->_qill[$grouping][] = ts("Activity Schedule Date %1 %2", array(1 => $op, 2 => $date)); } $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_recent_activity_type': $names = $value; if (($activityType = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'activity_type_id', $value)) != FALSE) { $names = $activityType; } $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_type_id", $op, $value, 'Int'); $query->_qill[$grouping][] = ts("Activity Type %1 %2", array(1 => $op, 2 => $names)); $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['case_activity_type'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_activity_status_id': $names = $value; if (($activityStatus = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'status_id', $value)) != FALSE) { $names = $activityStatus; } $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.status_id", $op, $value, 'Int'); $query->_qill[$grouping][] = ts("Activity Type %1 %2", array(1 => $op, 2 => $names)); $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['case_activity_status'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_activity_duration': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.duration", $op, $value, 'Int'); $query->_qill[$grouping][] = ts("Activity Duration %1 %2", array(1 => $op, 2 => $value)); $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_activity_medium_id': $names = $value; if (($activityMedium = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'medium_id', $value)) != FALSE) { $names = $activityMedium; } $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.medium_id", $op, $value, 'Int'); $query->_qill[$grouping][] = ts("Activity Medium %1 %2", array(1 => $op, 2 => $names)); $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['case_activity_medium'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_activity_details': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.details", $op, $value, 'String'); $query->_qill[$grouping][] = ts("Activity Details %1 '%2'", array(1 => $op, 2 => $value)); $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_activity_is_auto': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.is_auto", $op, $value, 'Boolean'); $query->_qill[$grouping][] = ts("Activity Auto Genrated %1 '%2'", array(1 => $op, 2 => $value)); $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; // adding where clause for case_role // adding where clause for case_role case 'case_role': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_relation_type.name_b_a", $op, $value, 'String'); $query->_qill[$grouping][] = ts("Role in Case %1 '%2'", array(1 => $op, 2 => $value)); $query->_tables['case_relation_type'] = $query->_whereTables['case_relationship_type'] = 1; $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; return; case 'case_from_start_date_low': case 'case_from_start_date_high': $query->dateQueryBuilder($values, 'civicrm_case', 'case_from_start_date', 'start_date', 'Start Date'); return; case 'case_to_end_date_low': case 'case_to_end_date_high': $query->dateQueryBuilder($values, 'civicrm_case', 'case_to_end_date', 'end_date', 'End Date'); return; case 'case_start_date': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.start_date", $op, $value, 'Int'); $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; return; case 'case_end_date': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.end_date", $op, $value, 'Int'); $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; return; case 'case_taglist': $taglist = $value; $value = array(); foreach ($taglist as $val) { if ($val) { $val = explode(',', $val); foreach ($val as $tId) { if (is_numeric($tId)) { $value[$tId] = 1; } } } } case 'case_tags': $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE)); if (is_array($value)) { foreach ($value as $k => $v) { if ($v) { $val[$k] = $k; $names[] = $tags[$k]; } } } $query->_where[$grouping][] = " civicrm_case_tag.tag_id IN (" . implode(',', $val) . " )"; $query->_qill[$grouping][] = ts('Case Tags %1', array(1 => $op)) . ' ' . implode(' ' . ts('or') . ' ', $names); $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1; $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1; $query->_tables['civicrm_case_tag'] = $query->_whereTables['civicrm_case_tag'] = 1; return; } }
/** * Alter display of rows. * * Iterate through the rows retrieved via SQL and make changes for display purposes, * such as rendering contacts as links. * * @param array $rows * Rows generated by SQL, with an array for each row. */ public function alterDisplay(&$rows) { $entryFound = FALSE; $dispname_flag = $phone_flag = $email_flag = 0; $prev_email = $prev_dispname = $prev_phone = NULL; foreach ($rows as $rowNum => $row) { // Link constituent (contributor) to contribution detail if (array_key_exists('civicrm_contact_display_name_constituent', $row) && array_key_exists('civicrm_contact_id_constituent', $row)) { $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail', 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id_constituent'], $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $rows[$rowNum]['civicrm_contact_display_name_constituent_link'] = $url; $rows[$rowNum]['civicrm_contact_display_name_constituent_hover'] = ts('List all direct contribution(s) from this contact.'); $entryFound = TRUE; } // convert soft credit contact name to link if (array_key_exists('civicrm_contact_display_name_creditor', $row) && !empty($rows[$rowNum]['civicrm_contact_display_name_creditor']) && array_key_exists('civicrm_contact_id_creditor', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contact_id_creditor'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_display_name_creditor_link'] = $url; $rows[$rowNum]['civicrm_contact_display_name_creditor_hover'] = ts("view contact summary"); } // make subtotals look nicer if (array_key_exists('civicrm_contact_id_constituent', $row) && !$row['civicrm_contact_id_constituent']) { $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields); $entryFound = TRUE; } // convert campaign_id to campaign title if (array_key_exists('civicrm_contribution_campaign_id', $row)) { if ($value = $row['civicrm_contribution_campaign_id']) { $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value]; $entryFound = TRUE; } } //convert soft_credit_type_id into label if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) { $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $row['civicrm_contribution_soft_soft_credit_type_id']); } //handle gender if (array_key_exists('civicrm_contact_gender_id', $row)) { if ($value = $row['civicrm_contact_gender_id']) { $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'); $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value]; } $entryFound = TRUE; } // display birthday in the configured custom format if (array_key_exists('civicrm_contact_birth_date', $row)) { $birthDate = $row['civicrm_contact_birth_date']; if ($birthDate) { $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d'); } $entryFound = TRUE; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } } $this->removeDuplicates($rows); }
/** * Fetch the object and store the values in the values array. * * @param array $params * Input parameters to find object. * @param array $values * Output values of the object. * * @return CRM_Contact_BAO_Contact|null * The found object or null */ public static function getValues(&$params, &$values) { $contact = new CRM_Contact_BAO_Contact(); $contact->copyValues($params); if ($contact->find(TRUE)) { CRM_Core_DAO::storeValues($contact, $values); $privacy = array(); foreach (self::$_commPrefs as $name) { if (isset($contact->{$name})) { $privacy[$name] = $contact->{$name}; } } if (!empty($privacy)) { $values['privacy'] = $privacy; } // communication Prefferance $preffComm = $comm = array(); $comm = explode(CRM_Core_DAO::VALUE_SEPARATOR, $contact->preferred_communication_method); foreach ($comm as $value) { $preffComm[$value] = 1; } $temp = 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($temp, $names, FALSE); $values['preferred_communication_method'] = $preffComm; $values['preferred_communication_method_display'] = CRM_Utils_Array::value('preferred_communication_method_display', $temp); $preferredMailingFormat = CRM_Core_SelectValues::pmf(); $values['preferred_mail_format'] = $preferredMailingFormat[$contact->preferred_mail_format]; // get preferred languages if (!empty($contact->preferred_language)) { $values['preferred_language'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $contact->preferred_language); } // Calculating Year difference if ($contact->birth_date) { $birthDate = CRM_Utils_Date::customFormat($contact->birth_date, '%Y%m%d'); if ($birthDate < date('Ymd')) { $age = CRM_Utils_Date::calculateAge($birthDate); $values['age']['y'] = CRM_Utils_Array::value('years', $age); $values['age']['m'] = CRM_Utils_Array::value('months', $age); } list($values['birth_date']) = CRM_Utils_Date::setDateDefaults($contact->birth_date, 'birth'); $values['birth_date_display'] = $contact->birth_date; } if ($contact->deceased_date) { list($values['deceased_date']) = CRM_Utils_Date::setDateDefaults($contact->deceased_date, 'birth'); $values['deceased_date_display'] = $contact->deceased_date; } $contact->contact_id = $contact->id; return $contact; } return NULL; }
/** * Get list of pledges In Honor of contact Ids. * * @param int $honorId * In Honor of Contact ID. * * @return array * return the list of pledge fields */ public static function getHonorContacts($honorId) { $params = array(); $honorDAO = new CRM_Contribute_DAO_ContributionSoft(); $honorDAO->contact_id = $honorId; $honorDAO->find(); // get all status. while ($honorDAO->fetch()) { $pledgePaymentDAO = new CRM_Pledge_DAO_PledgePayment(); $pledgePaymentDAO->contribution_id = $honorDAO->contribution_id; if ($pledgePaymentDAO->find(TRUE)) { $pledgeDAO = new CRM_Pledge_DAO_Pledge(); $pledgeDAO->id = $pledgePaymentDAO->pledge_id; if ($pledgeDAO->find(TRUE)) { $params[$pledgeDAO->id] = array('honor_type' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $honorDAO->soft_credit_type_id), 'honorId' => $pledgeDAO->contact_id, 'amount' => $pledgeDAO->amount, 'status' => CRM_Contribute_PseudoConstant::contributionStatus($pledgeDAO->status_id), 'create_date' => $pledgeDAO->create_date, 'acknowledge_date' => $pledgeDAO->acknowledge_date, 'type' => CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $pledgeDAO->financial_type_id, 'name'), 'display_name' => CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $pledgeDAO->contact_id, 'display_name')); } } } return $params; }
/** * convert the pseudo constants id's to their names * * @param reference parameter $dao * @param bool $return * * @return array */ function convertToPseudoNames(&$dao, $return = FALSE) { if (empty($this->_pseudoConstantsSelect)) { return; } $values = array(); foreach ($this->_pseudoConstantsSelect as $key => $value) { if (CRM_Utils_Array::value('sorting', $this->_pseudoConstantsSelect[$key])) { continue; } if (property_exists($dao, $value['idCol'])) { $val = $dao->{$value}['idCol']; if (CRM_Utils_System::isNull($val)) { $dao->{$key} = NULL; } elseif ($baoName = CRM_Utils_Array::value('bao', $value, NULL)) { //preserve id value $idColumn = "{$key}_id"; $dao->{$idColumn} = $val; $dao->{$value}['pseudoField'] = $dao->{$key} = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val); } elseif ($value['pseudoField'] == 'state_province_abbreviation') { $dao->{$key} = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val); } else { $labels = CRM_Core_OptionGroup::values($value['pseudoField']); $dao->{$key} = $labels[$val]; } // return converted values in array format if ($return) { if (strpos($key, '-') !== FALSE) { $keyVal = explode('-', $key); $current =& $values; $lastElement = array_pop($keyVal); foreach ($keyVal as $v) { if (!array_key_exists($v, $current)) { $current[$v] = array(); } $current =& $current[$v]; } $current[$lastElement] = $dao->{$key}; } else { $values[$key] = $dao->{$key}; } } } } return $values; }
/** * Makes an array of the batch's summary and returns array to parent getBatchSummary() function. * * @param $batchID * @param $params * * @return array */ public static function makeBatchSummary($batchID, $params) { $batchInfo = CRM_Batch_BAO_Batch::retrieve($params, $value); $batchTotals = CRM_Batch_BAO_Batch::batchTotals(array($batchID)); $batchSummary = array('created_by' => CRM_Contact_BAO_Contact::displayName($batchInfo->created_id), 'status' => CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'status_id', $batchInfo->status_id), 'description' => $batchInfo->description, 'payment_instrument' => CRM_Core_PseudoConstant::getLabel('CRM_Batch_BAO_Batch', 'payment_instrument_id', $batchInfo->payment_instrument_id), 'item_count' => $batchInfo->item_count, 'assigned_item_count' => $batchTotals[$batchID]['item_count'], 'total' => CRM_Utils_Money::format($batchInfo->total), 'assigned_total' => CRM_Utils_Money::format($batchTotals[$batchID]['total']), 'opened_date' => CRM_Utils_Date::customFormat($batchInfo->created_date)); return $batchSummary; }
/** * Retrieve soft contributions for contribution record. * * @param int $contributionID * @param bool $all * Include PCP data. * * @return array * Array of soft contribution ids, amounts, and associated contact ids */ public static function getSoftContribution($contributionID, $all = FALSE) { $pcpFields = array('pcp_id', 'pcp_title', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note'); $query = ' SELECT ccs.id, pcp_id, cpcp.title as pcp_title, pcp_display_in_roll, pcp_roll_nickname, pcp_personal_note, ccs.currency as currency, amount, ccs.contact_id as contact_id, c.display_name, ccs.soft_credit_type_id FROM civicrm_contribution_soft ccs INNER JOIN civicrm_contact c on c.id = ccs.contact_id LEFT JOIN civicrm_pcp cpcp ON ccs.pcp_id = cpcp.id WHERE contribution_id = %1; '; $params = array(1 => array($contributionID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); $softContribution = array(); $count = 1; while ($dao->fetch()) { if ($dao->pcp_id) { if ($all) { foreach ($pcpFields as $val) { $softContribution[$val] = $dao->{$val}; } $softContribution['pcp_soft_credit_to_name'] = $dao->display_name; $softContribution['pcp_soft_credit_to_id'] = $dao->contact_id; } } else { $softContribution['soft_credit'][$count] = array('contact_id' => $dao->contact_id, 'soft_credit_id' => $dao->id, 'currency' => $dao->currency, 'amount' => $dao->amount, 'contact_name' => $dao->display_name, 'soft_credit_type' => $dao->soft_credit_type_id, 'soft_credit_type_label' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $dao->soft_credit_type_id)); $count++; } } return $softContribution; }
/** * Alter display of rows. * * Iterate through the rows retrieved via SQL and make changes for display purposes, * such as rendering contacts as links. * * @param array $rows * Rows generated by SQL, with an array for each row. */ public function alterDisplay(&$rows) { $checkList = array(); $entryFound = FALSE; $display_flag = $prev_cid = $cid = 0; $contributionTypes = CRM_Contribute_PseudoConstant::financialType(); $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument(); $contributionPages = CRM_Contribute_PseudoConstant::contributionPage(); foreach ($rows as $rowNum => $row) { if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') { // don't repeat contact details if its same as the previous row if (array_key_exists('civicrm_contact_id', $row)) { if ($cid = $row['civicrm_contact_id']) { if ($rowNum == 0) { $prev_cid = $cid; } else { if ($prev_cid == $cid) { $display_flag = 1; $prev_cid = $cid; } else { $display_flag = 0; $prev_cid = $cid; } } if ($display_flag) { foreach ($row as $colName => $colVal) { // Hide repeats in no-repeat columns, but not if the field's a section header if (in_array($colName, $this->_noRepeats) && !array_key_exists($colName, $this->_sections)) { unset($rows[$rowNum][$colName]); } } } $entryFound = TRUE; } } } if (CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) == 'Contribution') { unset($rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id']); } // convert donor sort name to link if (array_key_exists('civicrm_contact_sort_name', $row) && !empty($rows[$rowNum]['civicrm_contact_sort_name']) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact."); } if ($value = CRM_Utils_Array::value('civicrm_contribution_financial_type_id', $row)) { $rows[$rowNum]['civicrm_contribution_financial_type_id'] = $contributionTypes[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) { $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_page_id', $row)) { $rows[$rowNum]['civicrm_contribution_contribution_page_id'] = $contributionPages[$value]; $entryFound = TRUE; } if ($value = CRM_Utils_Array::value('civicrm_contribution_payment_instrument_id', $row)) { $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $paymentInstruments[$value]; $entryFound = TRUE; } if (array_key_exists('civicrm_batch_batch_id', $row)) { if ($value = $row['civicrm_batch_batch_id']) { $rows[$rowNum]['civicrm_batch_batch_id'] = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $value, 'title'); } $entryFound = TRUE; } // Contribution amount links to viewing contribution if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount_sum', $row)) && CRM_Core_Permission::check('access CiviContribute')) { $url = CRM_Utils_System::url("civicrm/contact/view/contribution", "reset=1&id=" . $row['civicrm_contribution_contribution_id'] . "&cid=" . $row['civicrm_contact_id'] . "&action=view&context=contribution&selectedChild=contribute", $this->_absoluteUrl); $rows[$rowNum]['civicrm_contribution_total_amount_sum_link'] = $url; $rows[$rowNum]['civicrm_contribution_total_amount_sum_hover'] = ts("View Details of this Contribution."); $entryFound = TRUE; } // convert campaign_id to campaign title if (array_key_exists('civicrm_contribution_campaign_id', $row)) { if ($value = $row['civicrm_contribution_campaign_id']) { $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value]; $entryFound = TRUE; } } // soft credits if (array_key_exists('civicrm_contribution_soft_credits', $row) && 'Contribution' == CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) && array_key_exists('civicrm_contribution_contribution_id', $row)) { $query = "\nSELECT civicrm_contact_id, civicrm_contact_sort_name, civicrm_contribution_total_amount_sum, civicrm_contribution_currency\nFROM civireport_contribution_detail_temp2\nWHERE civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}"; $dao = CRM_Core_DAO::executeQuery($query); $string = ''; $separator = $this->_outputMode !== 'csv' ? "<br/>" : ' '; while ($dao->fetch()) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $dao->civicrm_contact_id); $string = $string . ($string ? $separator : '') . "<a href='{$url}'>{$dao->civicrm_contact_sort_name}</a> " . CRM_Utils_Money::format($dao->civicrm_contribution_total_amount_sum, $dao->civicrm_contribution_currency); } $rows[$rowNum]['civicrm_contribution_soft_credits'] = $string; } if (array_key_exists('civicrm_contribution_soft_credit_for', $row) && 'Soft Credit' == CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) && array_key_exists('civicrm_contribution_contribution_id', $row)) { $query = "\nSELECT civicrm_contact_id, civicrm_contact_sort_name\nFROM civireport_contribution_detail_temp1\nWHERE civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}"; $dao = CRM_Core_DAO::executeQuery($query); $string = ''; while ($dao->fetch()) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $dao->civicrm_contact_id); $string = $string . "\n<a href='{$url}'>{$dao->civicrm_contact_sort_name}</a>"; } $rows[$rowNum]['civicrm_contribution_soft_credit_for'] = $string; } //convert soft_credit_type_id into label if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) { $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $row['civicrm_contribution_soft_soft_credit_type_id']); } $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound; //handle gender if (array_key_exists('civicrm_contact_gender_id', $row)) { if ($value = $row['civicrm_contact_gender_id']) { $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'); $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value]; } $entryFound = TRUE; } // display birthday in the configured custom format if (array_key_exists('civicrm_contact_birth_date', $row)) { $birthDate = $row['civicrm_contact_birth_date']; if ($birthDate) { $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d'); } $entryFound = TRUE; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } $lastKey = $rowNum; } }
/** * Given a contact id and a field set, return the values from the db * for this contact * * @param int $cid * @param array $fields * The profile fields of interest. * @param array $values * The values for the above fields. * @param bool $searchable * Searchable or not. * @param array $componentWhere * Component condition. * @param bool $absolute * Return urls in absolute form (useful when sending an email). * @param null $additionalWhereClause */ public static function getValues($cid, &$fields, &$values, $searchable = TRUE, $componentWhere = NULL, $absolute = FALSE, $additionalWhereClause = NULL) { if (empty($cid) && empty($componentWhere)) { return NULL; } // get the contact details (hier) $returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($fields); $params = $cid ? array(array('contact_id', '=', $cid, 0, 0)) : array(); // add conditions specified by components. eg partcipant_id etc if (!empty($componentWhere)) { $params = array_merge($params, $componentWhere); } $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields); $options =& $query->_options; $details = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, FALSE, $additionalWhereClause); if (!$details->fetch()) { return; } $query->convertToPseudoNames($details); $config = CRM_Core_Config::singleton(); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $multipleFields = array('url'); //start of code to set the default values foreach ($fields as $name => $field) { // fix for CRM-3962 if ($name == 'id') { $name = 'contact_id'; } // skip fields that should not be displayed separately if (!empty($field['skipDisplay'])) { continue; } // Create a unique, non-empty index for each field. $index = $field['title']; if ($index === '') { $index = ' '; } while (array_key_exists($index, $values)) { $index .= ' '; } $params[$index] = $values[$index] = ''; $customFieldName = NULL; // hack for CRM-665 if (isset($details->{$name}) || $name == 'group' || $name == 'tag') { // to handle gender / suffix / prefix if (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix'))) { $params[$index] = $details->{$name}; $values[$index] = $details->{$name}; } elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)) { $dname = $name . '_display'; $values[$index] = $details->{$dname}; $name = $name . '_id'; $params[$index] = $details->{$name}; } elseif (in_array($name, array('state_province', 'country', 'county'))) { $values[$index] = $details->{$name}; $idx = $name . '_id'; $params[$index] = $details->{$idx}; } elseif ($name === 'preferred_communication_method') { $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); $compref = array(); $pref = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}); foreach ($pref as $k) { if ($k) { $compref[] = $communicationFields[$k]; } } $params[$index] = $details->{$name}; $values[$index] = implode(',', $compref); } elseif ($name === 'preferred_language') { $params[$index] = $details->{$name}; $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $details->{$name}); } elseif ($name == 'group') { $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', NULL, FALSE, TRUE); $title = $ids = array(); foreach ($groups as $g) { // CRM-8362: User and User Admin visibility groups should be included in display if user has // VIEW permission on that group $groupPerm = CRM_Contact_BAO_Group::checkPermission($g['group_id'], $g['title']); if ($g['visibility'] != 'User and User Admin Only' || CRM_Utils_Array::key(CRM_Core_Permission::VIEW, $groupPerm)) { $title[] = $g['title']; if ($g['visibility'] == 'Public Pages') { $ids[] = $g['group_id']; } } } $values[$index] = implode(', ', $title); $params[$index] = implode(',', $ids); } elseif ($name == 'tag') { $entityTags = CRM_Core_BAO_EntityTag::getTag($cid); $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE)); $title = array(); foreach ($entityTags as $tagId) { $title[] = $allTags[$tagId]; } $values[$index] = implode(', ', $title); $params[$index] = implode(',', $entityTags); } elseif ($name == 'activity_status_id') { $activityStatus = CRM_Core_PseudoConstant::activityStatus(); $values[$index] = $activityStatus[$details->{$name}]; $params[$index] = $details->{$name}; } elseif ($name == 'activity_date_time') { $values[$index] = CRM_Utils_Date::customFormat($details->{$name}); $params[$index] = $details->{$name}; } elseif ($name == 'contact_sub_type') { $contactSubTypeNames = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}); if (!empty($contactSubTypeNames)) { $contactSubTypeLabels = array(); // get all contact subtypes $allContactSubTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); // build contact subtype labels array foreach ($contactSubTypeNames as $cstName) { if ($cstName) { $contactSubTypeLabels[] = $allContactSubTypes[$cstName]['label']; } } $values[$index] = implode(',', $contactSubTypeLabels); } $params[$index] = $details->{$name}; } else { if (substr($name, 0, 7) === 'do_not_' || substr($name, 0, 3) === 'is_') { if ($details->{$name}) { $values[$index] = '[ x ]'; } } else { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $htmlType = $field['html_type']; // field_type is only set when we are retrieving profile values // when sending email, we call the same function to get custom field // values etc, i.e. emulating a profile $fieldType = CRM_Utils_Array::value('field_type', $field); if ($htmlType == 'File') { $entityId = $cid; if (!$cid && $fieldType == 'Activity' && !empty($componentWhere[0][2])) { $entityId = $componentWhere[0][2]; } $fileURL = CRM_Core_BAO_CustomField::getFileURL($entityId, $cfID, NULL, $absolute, $additionalWhereClause); $params[$index] = $values[$index] = $fileURL['file_url']; } else { $customVal = NULL; if (isset($dao) && property_exists($dao, 'data_type') && ($dao->data_type == 'Int' || $dao->data_type == 'Boolean')) { $customVal = (int) $details->{$name}; } elseif (isset($dao) && property_exists($dao, 'data_type') && $dao->data_type == 'Float') { $customVal = (double) $details->{$name}; } elseif (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}))) { $customVal = $details->{$name}; } //CRM-4582 if (CRM_Utils_System::isNull($customVal)) { continue; } $params[$index] = $customVal; $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options); if ($field['data_type'] == 'ContactReference') { $params[$index] = $values[$index]; } if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) { $customFieldName = "{$name}_from"; } } } elseif ($name == 'image_URL') { list($width, $height) = getimagesize(CRM_Utils_String::unstupifyUrl($details->{$name})); list($thumbWidth, $thumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($width, $height); $image_URL = '<img src="' . $details->{$name} . '" height= ' . $thumbHeight . ' width= ' . $thumbWidth . ' />'; $values[$index] = "<a href='#' onclick='contactImagePopUp(\"{$details->{$name}}\", {$width}, {$height});'>{$image_URL}</a>"; } elseif (in_array($name, array('birth_date', 'deceased_date', 'membership_start_date', 'membership_end_date', 'join_date'))) { $values[$index] = CRM_Utils_Date::customFormat($details->{$name}); $params[$index] = CRM_Utils_Date::isoToMysql($details->{$name}); } else { $dao = ''; if ($index == 'Campaign') { $dao = 'CRM_Campaign_DAO_Campaign'; } elseif ($index == 'Contribution Page') { $dao = 'CRM_Contribute_DAO_ContributionPage'; } if ($dao) { $value = CRM_Core_DAO::getFieldValue($dao, $details->{$name}, 'title'); } else { $value = $details->{$name}; } $values[$index] = $value; } } } } elseif (strpos($name, '-') !== FALSE) { list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3); if (!in_array($fieldName, $multipleFields)) { if ($id == 'Primary') { // fix for CRM-1543 // not sure why we'd every use Primary location type id // we need to fix the source if we are using it // $locationTypeName = CRM_Contact_BAO_Contact::getPrimaryLocationType( $cid ); $locationTypeName = 1; } else { $locationTypeName = CRM_Utils_Array::value($id, $locationTypes); } if (!$locationTypeName) { continue; } $detailName = "{$locationTypeName}-{$fieldName}"; $detailName = str_replace(' ', '_', $detailName); if (in_array($fieldName, array('phone', 'im', 'email', 'openid'))) { if ($type) { $detailName .= "-{$type}"; } } if (in_array($fieldName, array('state_province', 'country', 'county'))) { $values[$index] = $details->{$detailName}; $idx = $detailName . '_id'; $params[$index] = $details->{$idx}; } elseif ($fieldName == 'im') { $providerId = $detailName . '-provider_id'; if (isset($imProviders[$details->{$providerId}])) { $values[$index] = $details->{$detailName} . " (" . $imProviders[$details->{$providerId}] . ")"; } else { $values[$index] = $details->{$detailName}; } $params[$index] = $details->{$detailName}; } elseif ($fieldName == 'phone') { $phoneExtField = str_replace('phone', 'phone_ext', $detailName); if (isset($details->{$phoneExtField})) { $values[$index] = $details->{$detailName} . " (" . $details->{$phoneExtField} . ")"; } else { $values[$index] = $details->{$detailName}; } $params[$index] = $details->{$detailName}; } else { $values[$index] = $params[$index] = $details->{$detailName}; } } else { $detailName = "website-{$id}-{$fieldName}"; $url = CRM_Utils_System::fixURL($details->{$detailName}); if ($details->{$detailName}) { $websiteTypeId = "website-{$id}-website_type_id"; $websiteType = $websiteTypes[$details->{$websiteTypeId}]; $values[$index] = "<a href=\"{$url}\">{$details->{$detailName}} ( {$websiteType} )</a>"; } else { $values[$index] = ''; } } } if (CRM_Utils_Array::value('visibility', $field) == 'Public Pages and Listings' && CRM_Core_Permission::check('profile listings and forms')) { if (CRM_Utils_System::isNull($params[$index])) { $params[$index] = $values[$index]; } if (!isset($params[$index])) { continue; } if (!$customFieldName) { $fieldName = $field['name']; } else { $fieldName = $customFieldName; } $url = NULL; if (CRM_Core_BAO_CustomField::getKeyID($field['name'])) { $htmlType = $field['html_type']; if ($htmlType == 'Link') { $url = $params[$index]; } elseif (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Multi-Select State/Province', 'Multi-Select Country'))) { $valSeperator = CRM_Core_DAO::VALUE_SEPARATOR; $selectedOptions = explode($valSeperator, $params[$index]); foreach ($selectedOptions as $key => $multiOption) { if ($multiOption) { $url[] = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($multiOption)); } } } else { $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index])); } } else { $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index])); } if ($url && !empty($values[$index]) && $searchable) { if (is_array($url) && !empty($url)) { $links = array(); $eachMultiValue = explode(', ', $values[$index]); foreach ($eachMultiValue as $key => $valueLabel) { $links[] = '<a href="' . $url[$key] . '">' . $valueLabel . '</a>'; } $values[$index] = implode(', ', $links); } else { $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>'; } } } } }
/** * Function to get the list the export fields * * @param int $selectAll user preference while export * @param array $ids contact ids * @param array $params associated array of fields * @param string $order order by clause * @param array $fields associated array of fields * @param array $moreReturnProperties additional return fields * @param int $exportMode export mode * @param string $componentClause component clause * @param string $componentTable component table * @param bool $mergeSameAddress merge records if they have same address * @param bool $mergeSameHousehold merge records if they belong to the same household * * @static * @access public */ static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND') { $headerRows = $returnProperties = array(); $primary = $paymentFields = $selectedPaymentFields = FALSE; $origFields = $fields; $queryMode = $relationField = NULL; $allCampaigns = array(); $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE); $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS; switch ($exportMode) { case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE; break; case CRM_Export_Form_Select::EVENT_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_EVENT; break; case CRM_Export_Form_Select::MEMBER_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER; break; case CRM_Export_Form_Select::PLEDGE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE; break; case CRM_Export_Form_Select::CASE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_CASE; break; case CRM_Export_Form_Select::GRANT_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_GRANT; break; case CRM_Export_Form_Select::ACTIVITY_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY; break; } if ($fields) { //construct return properties $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im'); foreach ($fields as $key => $value) { $phoneTypeId = $imProviderId = NULL; $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value); if (!$fieldName) { continue; } // get phoneType id and IM service provider id seperately if ($fieldName == 'phone') { $phoneTypeId = CRM_Utils_Array::value(3, $value); } elseif ($fieldName == 'im') { $imProviderId = CRM_Utils_Array::value(3, $value); } if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) { if (!empty($value[2])) { $relationField = CRM_Utils_Array::value(2, $value); if (trim(CRM_Utils_Array::value(3, $value))) { $relLocTypeId = CRM_Utils_Array::value(3, $value); } else { $relLocTypeId = 'Primary'; } if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(4, $value); } elseif ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(4, $value); } } elseif (!empty($value[4])) { $relationField = CRM_Utils_Array::value(4, $value); $relLocTypeId = CRM_Utils_Array::value(5, $value); if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(6, $value); } elseif ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(6, $value); } } } $contactType = CRM_Utils_Array::value(0, $value); $locTypeId = CRM_Utils_Array::value(2, $value); if ($relationField) { if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) { if ($relPhoneTypeId) { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1; } elseif ($relIMProviderId) { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1; } else { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1; } $relPhoneTypeId = $relIMProviderId = NULL; } else { $returnProperties[$relationshipTypes][$relationField] = 1; } } elseif (is_numeric($locTypeId)) { if ($phoneTypeId) { $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1; } elseif ($imProviderId) { $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1; } else { $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1; } } else { //hack to fix component fields if ($fieldName == 'event_id') { $returnProperties['event_title'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT && array_key_exists($fieldName, self::componentPaymentFields())) { $selectedPaymentFields = true; $paymentTableId = 'participant_id'; $returnProperties[$fieldName] = 1; } else { $returnProperties[$fieldName] = 1; } } } } // hack to add default returnproperty based on export mode if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) { $returnProperties['contribution_id'] = 1; } elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { $returnProperties['participant_id'] = 1; if (!empty($returnProperties['participant_role'])) { unset($returnProperties['participant_role']); $returnProperties['participant_role_id'] = 1; } } elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { $returnProperties['membership_id'] = 1; } elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { $returnProperties['pledge_id'] = 1; } elseif ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { $returnProperties['case_id'] = 1; } elseif ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) { $returnProperties['grant_id'] = 1; } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { $returnProperties['activity_id'] = 1; } } else { $primary = TRUE; $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE); foreach ($fields as $key => $var) { if ($key && substr($key, 0, 6) != 'custom') { //for CRM=952 $returnProperties[$key] = 1; } } if ($primary) { $returnProperties['location_type'] = 1; $returnProperties['im_provider'] = 1; $returnProperties['phone_type_id'] = 1; $returnProperties['provider_id'] = 1; $returnProperties['current_employer'] = 1; } $extraReturnProperties = array(); $paymentFields = FALSE; switch ($queryMode) { case CRM_Contact_BAO_Query::MODE_EVENT: $paymentFields = TRUE; $paymentTableId = 'participant_id'; break; case CRM_Contact_BAO_Query::MODE_MEMBER: $paymentFields = TRUE; $paymentTableId = 'membership_id'; break; case CRM_Contact_BAO_Query::MODE_PLEDGE: $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode); $paymentFields = TRUE; $paymentTableId = 'pledge_payment_id'; break; case CRM_Contact_BAO_Query::MODE_CASE: $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode); break; } if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) { $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode); $returnProperties = array_merge($returnProperties, $componentReturnProperties); if (!empty($extraReturnProperties)) { $returnProperties = array_merge($returnProperties, $extraReturnProperties); } // unset non exportable fields for components $nonExpoFields = array('groups', 'tags', 'notes', 'contribution_status_id', 'pledge_status_id', 'pledge_payment_status_id'); foreach ($nonExpoFields as $value) { unset($returnProperties[$value]); } } } if ($mergeSameAddress) { //make sure the addressee fields are selected //while using merge same address feature $returnProperties['addressee'] = 1; $returnProperties['postal_greeting'] = 1; $returnProperties['email_greeting'] = 1; $returnProperties['street_name'] = 1; $returnProperties['household_name'] = 1; $returnProperties['street_address'] = 1; $returnProperties['city'] = 1; $returnProperties['state_province'] = 1; // some columns are required for assistance incase they are not already present $exportParams['merge_same_address']['temp_columns'] = array(); $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'); foreach ($tempColumns as $column) { if (!array_key_exists($column, $returnProperties)) { $returnProperties[$column] = 1; $column = $column == 'id' ? 'civicrm_primary_id' : $column; $exportParams['merge_same_address']['temp_columns'][$column] = 1; } } } if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) { // If an Additional Group is selected, then all contacts in that group are // added to the export set (filtering out duplicates). $query = "\nINSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id"; CRM_Core_DAO::executeQuery($query); } if ($moreReturnProperties) { // fix for CRM-7066 if (!empty($moreReturnProperties['group'])) { unset($moreReturnProperties['group']); $moreReturnProperties['groups'] = 1; } $returnProperties = array_merge($returnProperties, $moreReturnProperties); } $exportParams['postal_mailing_export']['temp_columns'] = array(); if ($exportParams['exportOption'] == 2 && isset($exportParams['postal_mailing_export']) && CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1) { $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'); foreach ($postalColumns as $column) { if (!array_key_exists($column, $returnProperties)) { $returnProperties[$column] = 1; $exportParams['postal_mailing_export']['temp_columns'][$column] = 1; } } } $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, $queryMode, FALSE, TRUE, TRUE, NULL, $queryOperator); list($select, $from, $where, $having) = $query->query(); if ($mergeSameHousehold == 1) { if (!$returnProperties['id']) { $returnProperties['id'] = 1; } //also merge Head of Household $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes); $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes); foreach ($returnProperties as $key => $value) { if (!array_key_exists($key, $contactRelationshipTypes)) { $returnProperties[$relationKeyMOH][$key] = $value; $returnProperties[$relationKeyHOH][$key] = $value; } } unset($returnProperties[$relationKeyMOH]['location_type']); unset($returnProperties[$relationKeyMOH]['im_provider']); unset($returnProperties[$relationKeyHOH]['location_type']); unset($returnProperties[$relationKeyHOH]['im_provider']); } $allRelContactArray = $relationQuery = array(); foreach ($contactRelationshipTypes as $rel => $dnt) { if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) { $allRelContactArray[$rel] = array(); // build Query for each relationship $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, NULL, FALSE, FALSE, $queryMode); list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query(); list($id, $direction) = explode('_', $rel, 2); // identify the relationship direction $contactA = 'contact_id_a'; $contactB = 'contact_id_b'; if ($direction == 'b_a') { $contactA = 'contact_id_b'; $contactB = 'contact_id_a'; } if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) { $relIDs = $ids; } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'); $query = "SELECT contact_id FROM civicrm_activity_contact\n WHERE activity_id IN ( " . implode(',', $ids) . ") AND\n record_type_id = {$sourceID}"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $relIDs[] = $dao->contact_id; } } else { switch ($exportMode) { case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: $component = 'civicrm_contribution'; break; case CRM_Export_Form_Select::EVENT_EXPORT: $component = 'civicrm_participant'; break; case CRM_Export_Form_Select::MEMBER_EXPORT: $component = 'civicrm_membership'; break; case CRM_Export_Form_Select::PLEDGE_EXPORT: $component = 'civicrm_pledge'; break; case CRM_Export_Form_Select::GRANT_EXPORT: $component = 'civicrm_grant'; break; } if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids); } else { $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component); } } $relationshipJoin = $relationshipClause = ''; if (!$selectAll && $componentTable) { $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}"; } elseif (!empty($relIDs)) { $relID = implode(',', $relIDs); $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )"; } $relationFrom = " {$relationFrom}\n INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}\n {$relationshipJoin} "; //check for active relationship status only $today = date('Ymd'); $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )"; $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}"; $relationGroupBy = " GROUP BY crel.{$contactA}"; $relationSelect = "{$relationSelect}, {$contactA} as refContact "; $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationHaving} {$relationGroupBy}"; $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString); while ($allRelContactDAO->fetch()) { //FIX Me: Migrate this to table rather than array // build the array of all related contacts $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone $allRelContactDAO; } $allRelContactDAO->free(); } } // make sure the groups stuff is included only if specifically specified // by the fields param (CRM-1969), else we limit the contacts outputted to only // ones that are part of a group if (!empty($returnProperties['groups'])) { $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )"; $newClause = " ( {$oldClause} AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )"; // total hack for export, CRM-3618 $from = str_replace($oldClause, $newClause, $from); } if (!$selectAll && $componentTable) { $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id "; } elseif ($componentClause) { if (empty($where)) { $where = "WHERE {$componentClause}"; } else { $where .= " AND {$componentClause}"; } } // CRM-13982 - check if is deleted $excludeTrashed = TRUE; foreach ($params as $value) { if ($value[0] == 'contact_is_deleted') { $excludeTrashed = FALSE; } } if (empty($where) && $excludeTrashed) { $where = "WHERE contact_a.is_deleted != 1"; } elseif ($excludeTrashed) { $where .= " AND contact_a.is_deleted != 1"; } $queryString = "{$select} {$from} {$where} {$having}"; $groupBy = ""; if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) || CRM_Utils_Array::value('notes', $returnProperties) || $queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy) { $groupBy = " GROUP BY contact_a.id"; } switch ($exportMode) { case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: $groupBy = 'GROUP BY civicrm_contribution.id'; break; case CRM_Export_Form_Select::EVENT_EXPORT: $groupBy = 'GROUP BY civicrm_participant.id'; break; case CRM_Export_Form_Select::MEMBER_EXPORT: $groupBy = " GROUP BY civicrm_membership.id"; break; } if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) { $groupBy = " GROUP BY civicrm_activity.id "; } $queryString .= $groupBy; if ($order) { list($field, $dir) = explode(' ', $order, 2); $field = trim($field); if (!empty($returnProperties[$field])) { // $queryString .= " ORDER BY $order"; } } $multipleSelectFields = array('preferred_communication_method' => 1); $addPaymentHeader = FALSE; $paymentDetails = array(); if ($paymentFields || $selectedPaymentFields) { // get payment related in for event and members $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids); //get all payment headers. // If we haven't selected specific payment fields, load in all the // payment headers. if (!$selectedPaymentFields) { $paymentHeaders = self::componentPaymentFields(); if (!empty($paymentDetails)) { $addPaymentHeader = TRUE; } } else { $paymentHeaders = array(); } $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL); } // Split campaign into 2 fields for id and title $campaignReturnProperties = array(); foreach ($returnProperties as $fld => $true) { $campaignReturnProperties[$fld] = $true; if (substr($fld, -11) == 'campaign_id') { $exportCampaign = TRUE; $campaignReturnProperties[substr($fld, 0, -3)] = 1; } } $returnProperties = $campaignReturnProperties; //get all campaigns. if (isset($exportCampaign)) { $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE); } $componentDetails = $headerRows = $sqlColumns = array(); $setHeader = TRUE; $rowCount = self::EXPORT_ROW_COUNT; $offset = 0; // we write to temp table often to avoid using too much memory $tempRowCount = 100; $count = -1; // for CRM-3157 purposes $i18n = CRM_Core_I18n::singleton(); while (1) { $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}"; $dao = CRM_Core_DAO::executeQuery($limitQuery); if ($dao->N <= 0) { break; } while ($dao->fetch()) { $count++; $row = array(); //convert the pseudo constants $query->convertToPseudoNames($dao); //first loop through returnproperties so that we return what is required, and in same order. $relationshipField = 0; foreach ($returnProperties as $field => $value) { //we should set header only once if ($setHeader) { $sqlDone = FALSE; // Split campaign into 2 fields for id and title if (substr($field, -8) == 'campaign') { $headerRows[] = ts('Campaign Title'); } elseif (substr($field, -11) == 'campaign_id') { $headerRows[] = ts('Campaign ID'); } elseif (isset($query->_fields[$field]['title'])) { $headerRows[] = $query->_fields[$field]['title']; } elseif ($field == 'phone_type_id') { $headerRows[] = ts('Phone Type'); } elseif ($field == 'provider_id') { $headerRows[] = ts('IM Service Provider'); } elseif (is_array($value) && $field == 'location') { // fix header for location type case foreach ($value as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title']; if (!empty($type[1])) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } elseif (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } $headerRows[] = $hdr; self::sqlColumnDefn($query, $sqlColumns, $hdr); } $sqlDone = TRUE; } } elseif (substr($field, 0, 5) == 'case_') { if ($query->_fields['case'][$field]['title']) { $headerRows[] = $query->_fields['case'][$field]['title']; } elseif ($query->_fields['activity'][$field]['title']) { $headerRows[] = $query->_fields['activity'][$field]['title']; } } elseif (array_key_exists($field, $contactRelationshipTypes)) { $relName = $field; foreach ($value as $relationField => $relationValue) { // below block is same as primary block (duplicate) if (isset($relationQuery[$field]->_fields[$relationField]['title'])) { if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') { $headerName = $field . '-' . $relationField; } else { if ($relationField == 'current_employer') { $headerName = $field . '-' . 'current_employer'; } else { $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name']; } } $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'phone_type_id') { $headerName = $field . '-' . 'Phone Type'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'provider_id') { $headerName = $field . '-' . 'Im Service Provider'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'state_province_id') { $headerName = $field . '-' . 'state_province_id'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif (is_array($relationValue) && $relationField == 'location') { // fix header for location type case foreach ($relationValue as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title']; if (!empty($type[1])) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } elseif (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } $headerName = $field . '-' . $hdr; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } } } } } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) { $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields()); } else { $headerRows[] = $field; } if (!$sqlDone) { self::sqlColumnDefn($query, $sqlColumns, $field); } } // add im_provider to $dao object if ($field == 'im_provider' && property_exists($dao, 'provider_id')) { $dao->im_provider = $dao->provider_id; } //build row values (data) $fieldValue = NULL; if (property_exists($dao, $field)) { $fieldValue = $dao->{$field}; // to get phone type from phone type id if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) { $fieldValue = $phoneTypes[$fieldValue]; } elseif ($field == 'provider_id' || $field == 'im_provider') { $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders); } elseif ($field == 'participant_role_id') { $participantRoles = CRM_Event_PseudoConstant::participantRole(); $sep = CRM_Core_DAO::VALUE_SEPARATOR; $viewRoles = array(); foreach (explode($sep, $dao->{$field}) as $k => $v) { $viewRoles[] = $participantRoles[$v]; } $fieldValue = implode(',', $viewRoles); } elseif ($field == 'master_id') { $masterAddressId = NULL; if (isset($dao->master_id)) { $masterAddressId = $dao->master_id; } // get display name of contact that address is shared. $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $dao->contact_id); } } if ($field == 'id') { $row[$field] = $dao->contact_id; // special case for calculated field } elseif ($field == 'source_contact_id') { $row[$field] = $dao->contact_id; } elseif ($field == 'pledge_balance_amount') { $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid; // special case for calculated field } elseif ($field == 'pledge_next_pay_amount') { $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount; } elseif (in_array(substr($field, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) { $row[$field] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $field, $dao->{$field}); } elseif (is_array($value) && $field == 'location') { // fix header for location type case foreach ($value as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $fldValue = "{$ltype}-" . $type[0]; // CRM-14076 - fix label to work as the query object expects // FIXME: We should not be using labels as keys! $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0]; if (!empty($type[1])) { $fldValue .= "-" . $type[1]; } // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) switch ($fld) { case 'country': case 'world_region': $row[$fldValue] = $i18n->crm_translate($dao->{$daoField}, array('context' => 'country')); break; case 'state_province': $row[$fldValue] = $i18n->crm_translate($dao->{$daoField}, array('context' => 'province')); break; case 'im_provider': $imFieldvalue = $daoField . "-provider_id"; $row[$fldValue] = CRM_Utils_Array::value($dao->{$imFieldvalue}, $imProviders); break; default: $row[$fldValue] = $dao->{$daoField}; break; } } } } elseif (array_key_exists($field, $contactRelationshipTypes)) { $relDAO = CRM_Utils_Array::value($dao->contact_id, $allRelContactArray[$field]); foreach ($value as $relationField => $relationValue) { if (is_object($relDAO) && property_exists($relDAO, $relationField)) { $fieldValue = $relDAO->{$relationField}; if ($relationField == 'phone_type_id') { $fieldValue = $phoneTypes[$relationValue]; } elseif ($relationField == 'provider_id') { $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders); } } elseif (is_object($relDAO) && in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$relationField}_display"; $fieldValue = $relDAO->{$fldValue}; } elseif (is_object($relDAO) && $relationField == 'state_province') { $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id); } elseif (is_object($relDAO) && $relationField == 'country') { $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id); } else { $fieldValue = ''; } $field = $field . '_'; if (is_object($relDAO) && $relationField == 'id') { $row[$field . $relationField] = $relDAO->contact_id; } elseif (is_object($relDAO) && is_array($relationValue) && $relationField == 'location') { foreach ($relationValue as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $fldValue = "{$ltype}-" . $type[0]; if (!empty($type[1])) { $fldValue .= "-" . $type[1]; } // CRM-3157: localise country, region (both have ‘country’ context) // and state_province (‘province’ context) switch (TRUE) { case !is_object($relDAO): $row[$field . '_' . $fldValue] = ''; break; case in_array('country', $type): case in_array('world_region', $type): $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'country')); break; case in_array('state_province', $type): $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'province')); break; default: $row[$field . '_' . $fldValue] = $relDAO->{$fldValue}; break; } } } } elseif (isset($fieldValue) && $fieldValue != '') { //check for custom data if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) { $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options); } else { //normal relationship fields // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) switch ($relationField) { case 'country': case 'world_region': $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country')); break; case 'state_province': $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province')); break; default: $row[$field . $relationField] = $fieldValue; break; } } } else { // if relation field is empty or null $row[$field . $relationField] = ''; } } } elseif (isset($fieldValue) && $fieldValue != '') { //check for custom data if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) { $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options); } elseif (array_key_exists($field, $multipleSelectFields)) { //option group fixes $paramsNew = array($field => $fieldValue); if ($field == 'test_tutoring') { $name = array($field => array('newName' => $field, 'groupName' => 'test')); // for readers group } elseif (substr($field, 0, 4) == 'cmr_') { $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3))); } else { $name = array($field => array('newName' => $field, 'groupName' => $field)); } CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE); $row[$field] = $paramsNew[$field]; } elseif (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$field}_display"; $row[$field] = $dao->{$fldValue}; } else { //normal fields with a touch of CRM-3157 switch ($field) { case 'country': case 'world_region': $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country')); break; case 'state_province': $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province')); break; case 'gender': case 'preferred_communication_method': case 'preferred_mail_format': case 'communication_style': $row[$field] = $i18n->crm_translate($fieldValue); break; default: $row[$field] = $fieldValue; break; } } } elseif (substr($field, -8) == 'campaign') { $campIdFld = "{$field}_id"; $row[$field] = CRM_Utils_Array::value($dao->{$campIdFld}, $allCampaigns, ''); } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) { $paymentData = CRM_Utils_Array::value($dao->{$paymentTableId}, $paymentDetails); $payFieldMapper = array('componentPaymentField_total_amount' => 'total_amount', 'componentPaymentField_contribution_status' => 'contribution_status', 'componentPaymentField_payment_instrument' => 'pay_instru', 'componentPaymentField_transaction_id' => 'trxn_id', 'componentPaymentField_received_date' => 'receive_date'); $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, ''); } else { // if field is empty or null $row[$field] = ''; } } // add payment headers if required if ($addPaymentHeader && $paymentFields) { $headerRows = array_merge($headerRows, $paymentHeaders); foreach (array_keys($paymentHeaders) as $paymentHdr) { self::sqlColumnDefn($query, $sqlColumns, $paymentHdr); } } if ($setHeader) { $exportTempTable = self::createTempTable($sqlColumns); } //build header only once $setHeader = FALSE; // If specific payment fields have been selected for export, payment // data will already be in $row. Otherwise, add payment related // information, if appropriate. if ($addPaymentHeader) { if (!$selectedPaymentFields) { if ($paymentFields) { $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails); if (!is_array($paymentData) || empty($paymentData)) { $paymentData = $nullContributionDetails; } $row = array_merge($row, $paymentData); } elseif (!empty($paymentDetails)) { $row = array_merge($row, $nullContributionDetails); } } } //remove organization name for individuals if it is set for current employer if (!empty($row['contact_type']) && $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)) { $row['organization_name'] = ''; } // add component info // write the row to a file $componentDetails[] = $row; // output every $tempRowCount rows if ($count % $tempRowCount == 0) { self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); $componentDetails = array(); } } $dao->free(); $offset += $rowCount; } if ($exportTempTable) { self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); // do merge same address and merge same household processing if ($mergeSameAddress) { self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams); } // merge the records if they have corresponding households if ($mergeSameHousehold) { self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH); self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH); } // fix the headers for rows with relationship type if (!empty($relName)) { self::manipulateHeaderRows($headerRows, $contactRelationshipTypes); } // if postalMailing option is checked, exclude contacts who are deceased, have // "Do not mail" privacy setting, or have no street address if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) && $exportParams['postal_mailing_export']['postal_mailing_export'] == 1) { self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode); } // call export hook CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode); // now write the CSV file self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode); // delete the export temp table and component table $sql = "DROP TABLE IF EXISTS {$exportTempTable}"; CRM_Core_DAO::executeQuery($sql); CRM_Utils_System::civiExit(); } else { CRM_Core_Error::fatal(ts('No records to export')); } }
/** * Convert the pseudo constants id's to their names * * @param CRM_Core_DAO $dao * @param bool $return * @param bool $usedForAPI * * @return array|NULL */ public function convertToPseudoNames(&$dao, $return = FALSE, $usedForAPI = FALSE) { if (empty($this->_pseudoConstantsSelect)) { return NULL; } $values = array(); foreach ($this->_pseudoConstantsSelect as $key => $value) { if (!empty($this->_pseudoConstantsSelect[$key]['sorting'])) { continue; } if (is_object($dao) && property_exists($dao, $value['idCol'])) { $val = $dao->{$value}['idCol']; if (CRM_Utils_System::isNull($val)) { $dao->{$key} = NULL; } elseif ($baoName = CRM_Utils_Array::value('bao', $value, NULL)) { //preserve id value $idColumn = "{$key}_id"; $dao->{$idColumn} = $val; if ($key == 'state_province_name') { $dao->{$value}['pseudoField'] = $dao->{$key} = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val); } else { $dao->{$value}['pseudoField'] = $dao->{$key} = CRM_Core_PseudoConstant::getLabel($baoName, $value['pseudoField'], $val); } } elseif ($value['pseudoField'] == 'state_province_abbreviation') { $dao->{$key} = CRM_Core_PseudoConstant::stateProvinceAbbreviation($val); } elseif (in_array($value['pseudoField'], array('participant_role_id', 'participant_role'))) { $viewValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $val); if ($value['pseudoField'] == 'participant_role') { $pseudoOptions = CRM_Core_PseudoConstant::get('CRM_Event_DAO_Participant', 'role_id'); foreach ($viewValues as $k => $v) { $viewValues[$k] = $pseudoOptions[$v]; } } $dao->{$key} = $usedForAPI && count($viewValues) > 1 ? $viewValues : implode(', ', $viewValues); } else { $labels = CRM_Core_OptionGroup::values($value['pseudoField']); $dao->{$key} = $labels[$val]; } // return converted values in array format if ($return) { if (strpos($key, '-') !== FALSE) { $keyVal = explode('-', $key); $current =& $values; $lastElement = array_pop($keyVal); foreach ($keyVal as $v) { if (!array_key_exists($v, $current)) { $current[$v] = array(); } $current =& $current[$v]; } $current[$lastElement] = $dao->{$key}; } else { $values[$key] = $dao->{$key}; } } } } return $values; }
function alterDisplay(&$rows) { // custom code to alter rows $entryFound = FALSE; foreach ($rows as $rowNum => $row) { // convert display name to links if (array_key_exists('civicrm_contact_sort_name', $row) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View contact details for this record."); $entryFound = TRUE; } if (array_key_exists('civicrm_grant_grant_type_id', $row)) { if ($value = $row['civicrm_grant_grant_type_id']) { $rows[$rowNum]['civicrm_grant_grant_type_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Grant_DAO_Grant', 'grant_type_id', $value); } $entryFound = TRUE; } if (array_key_exists('civicrm_grant_status_id', $row)) { if ($value = $row['civicrm_grant_status_id']) { $rows[$rowNum]['civicrm_grant_status_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Grant_DAO_Grant', 'status_id', $value); } $entryFound = TRUE; } if (array_key_exists('civicrm_grant_grant_report_received', $row)) { if ($value = $row['civicrm_grant_grant_report_received']) { if ($value == 1) { $value = 'Yes'; } else { $value = 'No'; } $rows[$rowNum]['civicrm_grant_grant_report_received'] = $value; } $entryFound = TRUE; } if (!$entryFound) { break; } } }
/** * Function to build the array for display the profile fields * * @param array $params key value. * @param int $gid profile Id * @param array $groupTitle Profile Group Title. * @param array $values formatted array of key value * * @param array $profileFields * * @return void * @access public * @static */ static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) { if ($gid) { $config = CRM_Core_Config::singleton(); $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); if ($contactID) { if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) { $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW); } } else { $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::ADD); } foreach ($fields as $v) { if (!empty($v['groupTitle'])) { $groupTitle['groupTitle'] = $v['groupTitle']; break; } } $customVal = ''; $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); //start of code to set the default values foreach ($fields as $name => $field) { $skip = FALSE; // skip fields that should not be displayed separately if ($field['skipDisplay']) { continue; } $index = $field['title']; if ($name === 'organization_name') { $values[$index] = $params[$name]; } if ('state_province' == substr($name, 0, 14)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]); } else { $values[$index] = ''; } } elseif ('date' == substr($name, -4)) { $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull); } elseif ('country' == substr($name, 0, 7)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::country($params[$name]); } else { $values[$index] = ''; } } elseif ('county' == substr($name, 0, 6)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::county($params[$name]); } else { $values[$index] = ''; } } elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) { $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]); } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) { $filterCondition = array('greeting_type' => $name); $greeting = CRM_Core_PseudoConstant::greeting($filterCondition); $values[$index] = $greeting[$params[$name]]; } elseif ($name === 'preferred_communication_method') { $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); $compref = array(); $pref = $params[$name]; if (is_array($pref)) { foreach ($pref as $k => $v) { if ($v) { $compref[] = $communicationFields[$k]; } } } $values[$index] = implode(',', $compref); } elseif ($name == 'contact_sub_type') { $values[$index] = implode(', ', $params[$name]); } elseif ($name == 'group') { $groups = CRM_Contact_BAO_GroupContact::getGroupList(); $title = array(); foreach ($params[$name] as $gId => $dontCare) { if ($dontCare) { $title[] = $groups[$gId]; } } $values[$index] = implode(', ', $title); } elseif ($name == 'tag') { $entityTags = $params[$name]; $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE)); $title = array(); if (is_array($entityTags)) { foreach ($entityTags as $tagId => $dontCare) { $title[] = $allTags[$tagId]; } } $values[$index] = implode(', ', $title); } elseif ('participant_role_id' == $name or 'participant_role' == $name) { $roles = CRM_Event_PseudoConstant::participantRole(); $values[$index] = $roles[$params[$name]]; } elseif ('participant_status_id' == $name or 'participant_status' == $name) { $status = CRM_Event_PseudoConstant::participantStatus(); $values[$index] = $status[$params[$name]]; } elseif (substr($name, -11) == 'campaign_id') { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($params[$name]); $values[$index] = CRM_Utils_Array::value($params[$name], $campaigns); } elseif (strpos($name, '-') !== FALSE) { list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2); $detailName = str_replace(' ', '_', $name); if (in_array($fieldName, array('state_province', 'country', 'county'))) { $values[$index] = $params[$detailName]; $idx = $detailName . '_id'; $values[$index] = $params[$idx]; } elseif ($fieldName == 'im') { $providerName = NULL; if ($providerId = $detailName . '-provider_id') { $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders); } if ($providerName) { $values[$index] = $params[$detailName] . " (" . $providerName . ")"; } else { $values[$index] = $params[$detailName]; } } elseif ($fieldName == 'phone') { $phoneExtField = str_replace('phone', 'phone_ext', $detailName); if (isset($params[$phoneExtField])) { $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")"; } else { $values[$index] = $params[$detailName]; } } else { $values[$index] = $params[$detailName]; } } else { if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') { if ($params[$name]) { $values[$index] = '[ x ]'; } } else { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $query = "\nSELECT html_type, data_type\nFROM civicrm_custom_field\nWHERE id = {$cfID}\n"; $dao = CRM_Core_DAO::executeQuery($query); $dao->fetch(); $htmlType = $dao->html_type; if ($htmlType == 'File') { $values[$index] = $params[$index]; } else { if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') { $v = $params[$name]; if (!CRM_Utils_System::isNull($v)) { $customVal = (int) $v; } } elseif ($dao->data_type == 'Float') { $customVal = (double) $params[$name]; } elseif ($dao->data_type == 'Date') { //@todo note the currently we are using default date time formatting. Since you can select/set // different date and time format specific to custom field we should consider fixing this // sometime in the future $customVal = $displayValue = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull); if (!empty($params[$name . '_time'])) { $customVal = $displayValue = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name], $params[$name . '_time']), $config->dateformatDatetime); } $skip = TRUE; } else { $customVal = $params[$name]; } //take the custom field options $returnProperties = array($name => 1); $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields); $options =& $query->_options; if (!$skip) { $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options); } //Hack since we dont have function to check empty. //FIXME in 2.3 using crmIsEmptyArray() $customValue = TRUE; if (is_array($customVal) && is_array($displayValue)) { $customValue = array_diff($customVal, $displayValue); } //use difference of arrays if (empty($customValue) || !$customValue) { $values[$index] = ''; } else { $values[$index] = $displayValue; } } } elseif ($name == 'home_URL' && !empty($params[$name])) { $url = CRM_Utils_System::fixURL($params[$name]); $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>"; } elseif (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) { $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name])); } else { $values[$index] = $params[$name]; } } } $profileFields[$name] = $field; } } }
/** * Function is used to format the individual contact values. * * @param array $params * (reference ) an assoc array of name/value pairs. * @param CRM $contact * Contact object. * * @return CRM_Contact_BAO_Contact */ public static function format(&$params, &$contact) { if (!self::dataExists($params)) { return NULL; } // "null" value for example is passed by dedupe merge in order to empty. // Display name computation shouldn't consider such values. foreach (array('first_name', 'middle_name', 'last_name', 'nick_name', 'formal_title') as $displayField) { if (CRM_Utils_Array::value($displayField, $params) == "null") { $params[$displayField] = ''; } } $sortName = $displayName = ''; $firstName = CRM_Utils_Array::value('first_name', $params, ''); $middleName = CRM_Utils_Array::value('middle_name', $params, ''); $lastName = CRM_Utils_Array::value('last_name', $params, ''); $nickName = CRM_Utils_Array::value('nick_name', $params, ''); $prefix_id = CRM_Utils_Array::value('prefix_id', $params, ''); $suffix_id = CRM_Utils_Array::value('suffix_id', $params, ''); $formalTitle = CRM_Utils_Array::value('formal_title', $params, ''); // get prefix and suffix names $prefix = $suffix = NULL; if ($prefix_id) { $params['individual_prefix'] = $prefix = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'prefix_id', $prefix_id); } if ($suffix_id) { $params['individual_suffix'] = $suffix = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'suffix_id', $suffix_id); } $params['is_deceased'] = CRM_Utils_Array::value('is_deceased', $params, FALSE); $individual = NULL; if ($contact->id) { $individual = new CRM_Contact_BAO_Contact(); $individual->id = $contact->id; if ($individual->find(TRUE)) { //lets allow to update single name field though preserveDBName //but if db having null value and params contain value, CRM-4330. $useDBNames = array(); foreach (array('last', 'middle', 'first', 'nick') as $name) { $dbName = "{$name}_name"; $value = $individual->{$dbName}; // the db has name values if ($value && !empty($params['preserveDBName'])) { $useDBNames[] = $name; } } foreach (array('prefix', 'suffix') as $name) { $dbName = "{$name}_id"; $value = $individual->{$dbName}; if ($value && !empty($params['preserveDBName'])) { $useDBNames[] = $name; } } if ($individual->formal_title && !empty($params['preserveDBName'])) { $useDBNames[] = 'formal_title'; } // CRM-4430 //1. preserve db name if want //2. lets get value from param if exists. //3. if not in params, lets get from db. foreach (array('last', 'middle', 'first', 'nick') as $name) { $phpName = "{$name}Name"; $dbName = "{$name}_name"; $value = $individual->{$dbName}; if (in_array($name, $useDBNames)) { $params[$dbName] = $value; $contact->{$dbName} = $value; ${$phpName} = $value; } elseif (array_key_exists($dbName, $params)) { ${$phpName} = $params[$dbName]; } elseif ($value) { ${$phpName} = $value; } } foreach (array('prefix', 'suffix') as $name) { $dbName = "{$name}_id"; $value = $individual->{$dbName}; if (in_array($name, $useDBNames)) { $params[$dbName] = $value; $contact->{$dbName} = $value; if ($value) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $value); } else { ${$name} = NULL; } } elseif (array_key_exists($dbName, $params)) { // CRM-5278 if (!empty($params[$dbName])) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $params[$dbName]); } } elseif ($value) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $value); } } if (in_array('formal_title', $useDBNames)) { $params['formal_title'] = $individual->formal_title; $contact->formal_title = $individual->formal_title; $formalTitle = $individual->formal_title; } elseif (array_key_exists('formal_title', $params)) { $formalTitle = $params['formal_title']; } elseif ($individual->formal_title) { $formalTitle = $individual->formal_title; } } } //first trim before further processing. foreach (array('lastName', 'firstName', 'middleName') as $fld) { ${$fld} = trim(${$fld}); } if ($lastName || $firstName || $middleName) { // make sure we have values for all the name fields. $formatted = $params; $nameParams = array('first_name' => $firstName, 'middle_name' => $middleName, 'last_name' => $lastName, 'nick_name' => $nickName, 'individual_suffix' => $suffix, 'individual_prefix' => $prefix, 'prefix_id' => $prefix_id, 'suffix_id' => $suffix_id, 'formal_title' => $formalTitle); // make sure we have all the name fields. foreach ($nameParams as $name => $value) { if (empty($formatted[$name]) && $value) { $formatted[$name] = $value; } } $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $catTokens) { foreach ($catTokens as $token => $label) { $tokenFields[] = $token; } } //build the sort name. $format = Civi::settings()->get('sort_name_format'); $sortName = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE, $tokenFields); $sortName = trim($sortName); //build the display name. $format = Civi::settings()->get('display_name_format'); $displayName = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE, $tokenFields); $displayName = trim($displayName); } //start further check for email. if (empty($sortName) || empty($displayName)) { $email = NULL; if (!empty($params['email']) && is_array($params['email'])) { foreach ($params['email'] as $emailBlock) { if (isset($emailBlock['is_primary'])) { $email = $emailBlock['email']; break; } } } $uniqId = CRM_Utils_Array::value('user_unique_id', $params); if (!$email && $contact->id) { $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contact->id); } } //now set the names. $names = array('displayName' => 'display_name', 'sortName' => 'sort_name'); foreach ($names as $value => $name) { if (empty(${$value})) { if ($email) { ${$value} = $email; } elseif ($uniqId) { ${$value} = $uniqId; } elseif (!empty($params[$name])) { ${$value} = $params[$name]; } elseif ($displayName) { ${$value} = $displayName; } } //finally if we could not pass anything lets keep db. if (!empty(${$value})) { $contact->{$name} = ${$value}; } } $format = CRM_Utils_Date::getDateFormat('birth'); if ($date = CRM_Utils_Array::value('birth_date', $params)) { if (in_array($format, array('dd-mm', 'mm/dd'))) { $separator = '/'; if ($format == 'dd-mm') { $separator = '-'; } $date = $date . $separator . '1902'; } elseif (in_array($format, array('yy-mm'))) { $date = $date . '-01'; } elseif (in_array($format, array('M yy'))) { $date = $date . '-01'; } elseif (in_array($format, array('yy'))) { $date = $date . '-01-01'; } $contact->birth_date = CRM_Utils_Date::processDate($date); } elseif ($contact->birth_date) { $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date); } if ($date = CRM_Utils_Array::value('deceased_date', $params)) { if (in_array($format, array('dd-mm', 'mm/dd'))) { $separator = '/'; if ($format == 'dd-mm') { $separator = '-'; } $date = $date . $separator . '1902'; } elseif (in_array($format, array('yy-mm'))) { $date = $date . '-01'; } elseif (in_array($format, array('M yy'))) { $date = $date . '-01'; } elseif (in_array($format, array('yy'))) { $date = $date . '-01-01'; } $contact->deceased_date = CRM_Utils_Date::processDate($date); } elseif ($contact->deceased_date) { $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date); } if ($middle_name = CRM_Utils_Array::value('middle_name', $params)) { $contact->middle_name = $middle_name; } return $contact; }
/** * Get list of payments displayed by Contribute_Page_PaymentInfo. * * @param int $id * @param $component * @param bool $getTrxnInfo * @param bool $usingLineTotal * * @return mixed */ public static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) { if ($component == 'event') { $entity = 'participant'; $entityTable = 'civicrm_participant'; $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id'); if (!$contributionId) { if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) { $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id'); $id = $primaryParticipantId; } if (!$contributionId) { return; } } } $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId); $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL; $isBalance = NULL; if ($baseTrxnId) { $isBalance = TRUE; } else { $baseTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contributionId); $baseTrxnId = $baseTrxnId['financialTrxnId']; $isBalance = FALSE; } if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) { // for additional participants if ($entityTable == 'civicrm_participant') { $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId); $total = 0; foreach ($ids as $val) { $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable); } } else { $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable); } } else { $baseTrxnId = $total['trxn_id']; $total = $total['total_amount']; } $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total); $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later'); $feeRelationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' ")); $financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id'); $feeFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($financialTypeId, $feeRelationTypeId); if ($paymentBalance == 0 && $contributionIsPayLater) { $paymentBalance = $total; } $info['total'] = $total; $info['paid'] = $total - $paymentBalance; $info['balance'] = $paymentBalance; $info['id'] = $id; $info['component'] = $component; $info['payLater'] = $contributionIsPayLater; $rows = array(); if ($getTrxnInfo && $baseTrxnId) { // Need to exclude fee trxn rows so filter out rows where TO FINANCIAL ACCOUNT is expense account $sql = "\nSELECT ft.total_amount, con.financial_type_id, ft.payment_instrument_id, ft.trxn_date, ft.trxn_id, ft.status_id, ft.check_number\nFROM civicrm_contribution con\n LEFT JOIN civicrm_entity_financial_trxn eft ON (eft.entity_id = con.id AND eft.entity_table = 'civicrm_contribution')\n INNER JOIN civicrm_financial_trxn ft ON ft.id = eft.financial_trxn_id AND ft.to_financial_account_id != {$feeFinancialAccount}\nWHERE con.id = {$contributionId}\n"; // conditioned WHERE clause if ($isBalance) { // if balance trxn exists don't include details of it in transaction info $sql .= " AND ft.id != {$baseTrxnId} "; } $resultDAO = CRM_Core_DAO::executeQuery($sql); $statuses = CRM_Contribute_PseudoConstant::contributionStatus(); $financialTypes = CRM_Contribute_PseudoConstant::financialType(); while ($resultDAO->fetch()) { $paidByLabel = CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); $paidByName = CRM_Core_PseudoConstant::getName('CRM_Core_BAO_FinancialTrxn', 'payment_instrument_id', $resultDAO->payment_instrument_id); $val = array('total_amount' => $resultDAO->total_amount, 'financial_type' => $financialTypes[$resultDAO->financial_type_id], 'payment_instrument' => $paidByLabel, 'receive_date' => $resultDAO->trxn_date, 'trxn_id' => $resultDAO->trxn_id, 'status' => $statuses[$resultDAO->status_id]); if ($paidByName == 'Check') { $val['check_number'] = $resultDAO->check_number; } $rows[] = $val; } $info['transaction'] = $rows; } return $info; }
/** * View summary details of a contact. */ public function view() { // Add js for tabs, in-place editing, and jstree for tags CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'templates/CRM/Contact/Page/View/Summary.js', 2, 'html-header')->addStyleFile('civicrm', 'css/contactSummary.css', 2, 'html-header')->addScriptFile('civicrm', 'packages/jquery/plugins/jstree/jquery.jstree.js', 0, 'html-header', FALSE)->addStyleFile('civicrm', 'packages/jquery/plugins/jstree/themes/default/style.css', 0, 'html-header')->addScriptFile('civicrm', 'templates/CRM/common/TabHeader.js', 1, 'html-header')->addSetting(array('summaryPrint' => array('mode' => $this->_print), 'tabSettings' => array('active' => CRM_Utils_Request::retrieve('selectedChild', 'String', $this, FALSE, 'summary')))); $this->assign('summaryPrint', $this->_print); $session = CRM_Core_Session::singleton(); $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $this->_contactId); $session->pushUserContext($url); $params = array(); $defaults = array(); $ids = array(); $params['id'] = $params['contact_id'] = $this->_contactId; $params['noRelationships'] = $params['noNotes'] = $params['noGroups'] = TRUE; $contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults, TRUE); // Let summary page know if outbound mail is disabled so email links can be built conditionally $mailingBackend = Civi::settings()->get('mailing_backend'); $this->assign('mailingOutboundOption', $mailingBackend['outBound_option']); $communicationType = array('phone' => array('type' => 'phoneType', 'id' => 'phone_type', 'daoName' => 'CRM_Core_DAO_Phone', 'fieldName' => 'phone_type_id'), 'im' => array('type' => 'IMProvider', 'id' => 'provider', 'daoName' => 'CRM_Core_DAO_IM', 'fieldName' => 'provider_id'), 'website' => array('type' => 'websiteType', 'id' => 'website_type', 'daoName' => 'CRM_Core_DAO_Website', 'fieldName' => 'website_type_id'), 'address' => array('skip' => TRUE, 'customData' => 1), 'email' => array('skip' => TRUE), 'openid' => array('skip' => TRUE)); foreach ($communicationType as $key => $value) { if (!empty($defaults[$key])) { foreach ($defaults[$key] as &$val) { CRM_Utils_Array::lookupValue($val, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'display_name')), FALSE); if (empty($value['skip'])) { $daoName = $value['daoName']; $pseudoConst = $daoName::buildOptions($value['fieldName'], 'get'); CRM_Utils_Array::lookupValue($val, $value['id'], $pseudoConst, FALSE); } } if (isset($value['customData'])) { foreach ($defaults[$key] as $blockId => $blockVal) { $idValue = $blockVal['id']; if ($key == 'address') { if (!empty($blockVal['master_id'])) { $idValue = $blockVal['master_id']; } } $groupTree = CRM_Core_BAO_CustomGroup::getTree(ucfirst($key), $this, $idValue); // we setting the prefix to dnc_ below so that we don't overwrite smarty's grouptree var. $defaults[$key][$blockId]['custom'] = CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, "dnc_"); } // reset template variable since that won't be of any use, and could be misleading $this->assign("dnc_viewCustomData", NULL); } } } if (!empty($defaults['gender_id'])) { $defaults['gender_display'] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'gender_id', $defaults['gender_id']); } $communicationStyle = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'); if (!empty($communicationStyle)) { if (!empty($defaults['communication_style_id'])) { $defaults['communication_style_display'] = $communicationStyle[CRM_Utils_Array::value('communication_style_id', $defaults)]; } else { // Make sure the field is displayed as long as it is active, even if it is unset for this contact. $defaults['communication_style_display'] = ''; } } // to make contact type label available in the template - $contactType = array_key_exists('contact_sub_type', $defaults) ? $defaults['contact_sub_type'] : $defaults['contact_type']; $defaults['contact_type_label'] = CRM_Contact_BAO_ContactType::contactTypePairs(TRUE, $contactType, ', '); // get contact tags $contactTags = CRM_Core_BAO_EntityTag::getContactTags($this->_contactId); if (!empty($contactTags)) { $defaults['contactTag'] = implode(', ', $contactTags); } $defaults['privacy_values'] = CRM_Core_SelectValues::privacy(); //Show blocks only if they are visible in edit form $this->_editOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_edit_options'); foreach ($this->_editOptions as $blockName => $value) { $varName = '_show' . $blockName; $this->{$varName} = $value; $this->assign(substr($varName, 1), $this->{$varName}); } // get contact name of shared contact names $sharedAddresses = array(); $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']); foreach ($defaults['address'] as $key => $addressValue) { if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) { $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name']); } } $this->assign('sharedAddresses', $sharedAddresses); //get the current employer name if (CRM_Utils_Array::value('contact_type', $defaults) == 'Individual') { if ($contact->employer_id && $contact->organization_name) { $defaults['current_employer'] = $contact->organization_name; $defaults['current_employer_id'] = $contact->employer_id; } //for birthdate format with respect to birth format set $this->assign('birthDateViewFormat', CRM_Utils_Array::value('qfMapping', CRM_Utils_Date::checkBirthDateFormat())); } $defaults['external_identifier'] = $contact->external_identifier; $this->assign($defaults); // FIXME: when we sort out TZ isssues with DATETIME/TIMESTAMP, we can skip next query // also assign the last modifed details $lastModified = CRM_Core_BAO_Log::lastModified($this->_contactId, 'civicrm_contact'); $this->assign_by_ref('lastModified', $lastModified); $allTabs = array(); $weight = 10; $this->_viewOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_view_options', TRUE); // show the tabs only if user has generic access to CiviCRM $accessCiviCRM = CRM_Core_Permission::check('access CiviCRM'); $changeLog = $this->_viewOptions['log']; $this->assign_by_ref('changeLog', $changeLog); $components = CRM_Core_Component::getEnabledComponents(); foreach ($components as $name => $component) { if (!empty($this->_viewOptions[$name]) && CRM_Core_Permission::access($component->name)) { $elem = $component->registerTab(); // FIXME: not very elegant, probably needs better approach // allow explicit id, if not defined, use keyword instead if (array_key_exists('id', $elem)) { $i = $elem['id']; } else { $i = $component->getKeyword(); } $u = $elem['url']; //appending isTest to url for test soft credit CRM-3891. //FIXME: hack ajax url. $q = "reset=1&force=1&cid={$this->_contactId}"; if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) { $q .= "&isTest=1"; } $allTabs[] = array('id' => $i, 'url' => CRM_Utils_System::url("civicrm/contact/view/{$u}", $q), 'title' => $elem['title'], 'weight' => $elem['weight'], 'count' => CRM_Contact_BAO_Contact::getCountComponent($u, $this->_contactId), 'class' => 'livePage'); // make sure to get maximum weight, rest of tabs go after // FIXME: not very elegant again if ($weight < $elem['weight']) { $weight = $elem['weight']; } } } $rest = array('activity' => array('title' => ts('Activities'), 'class' => 'livePage'), 'rel' => array('title' => ts('Relationships'), 'class' => 'livePage'), 'group' => array('title' => ts('Groups'), 'class' => 'ajaxForm'), 'note' => array('title' => ts('Notes'), 'class' => 'livePage'), 'tag' => array('title' => ts('Tags')), 'log' => array('title' => ts('Change Log'))); foreach ($rest as $k => $v) { if ($accessCiviCRM && !empty($this->_viewOptions[$k])) { $allTabs[] = $v + array('id' => $k, 'url' => CRM_Utils_System::url("civicrm/contact/view/{$k}", "reset=1&cid={$this->_contactId}"), 'weight' => $weight, 'count' => CRM_Contact_BAO_Contact::getCountComponent($k, $this->_contactId)); $weight += 10; } } // now add all the custom tabs $entityType = $this->get('contactType'); $activeGroups = CRM_Core_BAO_CustomGroup::getActiveGroups($entityType, 'civicrm/contact/view/cd', $this->_contactId); foreach ($activeGroups as $group) { $id = "custom_{$group['id']}"; $allTabs[] = array('id' => $id, 'url' => CRM_Utils_System::url($group['path'], $group['query'] . "&selectedChild={$id}"), 'title' => $group['title'], 'weight' => $weight, 'count' => CRM_Contact_BAO_Contact::getCountComponent($id, $this->_contactId, $group['table_name']), 'hideCount' => !$group['is_multiple'], 'class' => 'livePage'); $weight += 10; } $context = array('contact_id' => $this->_contactId); // see if any other modules want to add any tabs CRM_Utils_Hook::tabs($allTabs, $this->_contactId); CRM_Utils_Hook::tabset('civicrm/contact/view', $allTabs, $context); $allTabs[] = array('id' => 'summary', 'url' => '#contact-summary', 'title' => ts('Summary'), 'weight' => 0); // now sort the tabs based on weight usort($allTabs, array('CRM_Utils_Sort', 'cmpFunc')); $this->assign('allTabs', $allTabs); // hook for contact summary // ignored but needed to prevent warnings $contentPlacement = CRM_Utils_Hook::SUMMARY_BELOW; CRM_Utils_Hook::summary($this->_contactId, $content, $contentPlacement); if ($content) { $this->assign_by_ref('hookContent', $content); $this->assign('hookContentPlacement', $contentPlacement); } }
/** * Fallback implementation of getlist_output. May be overridden by individual api functions. * * @param array $result * @param array $request * @param string $entity * @param array $fields * * @return array */ function _civicrm_api3_generic_getlist_output($result, $request, $entity, $fields) { $output = array(); if (!empty($result['values'])) { foreach ($result['values'] as $row) { $data = array('id' => $row[$request['id_field']], 'label' => $row[$request['label_field']]); if (!empty($request['description_field'])) { $data['description'] = array(); foreach ((array) $request['description_field'] as $field) { if (!empty($row[$field])) { if (!isset($fields[$field]['pseudoconstant'])) { $data['description'][] = $row[$field]; } else { $data['description'][] = CRM_Core_PseudoConstant::getLabel(_civicrm_api3_get_BAO($entity), $field, $row[$field]); } } } } if (!empty($request['image_field'])) { $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : ''; } $output[] = $data; } } return $output; }
/** * Results formatting for Case entityRef lookups. * * @param array $result * @param array $request * @param string $entity * @param array $fields * * @return array */ function _civicrm_api3_case_contact_getlist_output($result, $request, $entity, $fields) { $output = array(); if (!empty($result['values'])) { foreach ($result['values'] as $row) { $data = array('id' => $row[$request['id_field']], 'label' => $row[$request['label_field']] . ' - ' . $row['case_id.case_type_id.title']); $status = CRM_Core_PseudoConstant::getLabel('CRM_Case_BAO_Case', 'status_id', $row['case_id.status_id']); $date = CRM_Utils_Date::customFormat($row['case_id.start_date']); $data['description'] = array("#{$row['case_id']}: {$status} " . ts('(opened %1)', array(1 => $date)), $row['case_id.subject']); if (!empty($request['image_field'])) { $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : ''; } $output[] = $data; } } return $output; }