/** * Function for building Event combo box */ function event() { $name = trim(CRM_Utils_Type::escape($_GET['s'], 'String')); if (!$name) { $name = '%'; } $whereClause = " title LIKE '{$name}%' AND ( civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0 )"; $includeOld = CRM_Utils_Request::retrieve('includeOld', 'Boolean', CRM_Core_DAO::$_nullObject, FALSE, TRUE); if (!$includeOld) { $whereClause .= " AND ( end_date IS NULL OR end_date >= NOW() )"; } $query = "\n SELECT civicrm_event.title AS title,\n civicrm_event.id AS id,\n civicrm_address.city AS city,\n civicrm_event.start_date\n FROM civicrm_event\n LEFT JOIN civicrm_loc_block ON\n civicrm_event.loc_block_id = civicrm_loc_block.id\n LEFT JOIN civicrm_address ON\n civicrm_loc_block.address_id = civicrm_address.id\n WHERE\n {$whereClause}\n ORDER BY\n civicrm_event.title\n"; $dao = CRM_Core_DAO::executeQuery($query); $results = array(); while ($dao->fetch()) { $fields = array(); foreach (array('title', 'city') as $field) { if (isset($dao->{$field})) { array_push($fields, $dao->{$field}); } } if (isset($dao->start_date)) { array_push($fields, CRM_Utils_Date::customFormat($dao->start_date)); } $results[$dao->id] = implode(' - ', $fields); } CRM_Core_Page_AJAX::autocompleteResults($results); }
/** * Convert the date string "YYYY-MM-DD" to "MM<long> DD, YYYY". * * @param string $dateString date which needs to converted to human readable format * * @return string human readable date format | invalid date message * @access public */ function smarty_modifier_crmDate($dateString, $dateFormat = null) { if ($dateString) { return CRM_Utils_Date::customFormat($dateString, $dateFormat); } return ''; }
/** * Get a standardized array of <select> options for "Event Title" * filter values. * @return Array */ function getEventFilterOptions() { $events = array(); $query = "\n select id, start_date, title from civicrm_event\n where (is_template IS NULL OR is_template = 0) AND is_active\n order by title ASC, start_date\n "; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $events[$dao->id] = "{$dao->title} - " . CRM_Utils_Date::customFormat(substr($dao->start_date, 0, 10)) . " (ID {$dao->id})"; } return $events; }
/** * Evaluate the content of a single token. * * @param \Civi\Token\TokenRow $row * The record for which we want token values. * @param string $entity * @param string $field * The name of the token field. * @param mixed $prefetch * Any data that was returned by the prefetch(). * * @return mixed */ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefetch = NULL) { $actionSearchResult = $row->context['actionSearchResult']; if (in_array($field, array('start_date', 'end_date', 'join_date'))) { $row->tokens($entity, $field, \CRM_Utils_Date::customFormat($actionSearchResult->{$field})); } elseif (isset($actionSearchResult->{$field})) { $row->tokens($entity, $field, $actionSearchResult->{$field}); } else { $row->tokens($entity, $field, ''); } }
/** * Test the ajax function to get financial transactions. * * Test focus is on ensuring changes to how labels are retrieved does not cause regression. */ public function testGetFinancialTransactionsList() { $individualID = $this->individualCreate(); $this->contributionCreate($individualID); $batch = $this->callAPISuccess('Batch', 'create', array('title' => 'test', 'status_id' => 'Open')); CRM_Core_DAO::executeQuery("\n INSERT INTO civicrm_entity_batch (entity_table, entity_id, batch_id)\n values('civicrm_financial_trxn', 1, 1)\n "); $_REQUEST['sEcho'] = 1; $_REQUEST['entityID'] = $batch['id']; $json = CRM_Financial_Page_AJAX::getFinancialTransactionsList(TRUE); $this->assertEquals($json, '{"sEcho": 1, "iTotalRecords": 1, "iTotalDisplayRecords": 1, "aaData": [ ["","<a href=\\"/index.php?q=civicrm/profile/view&reset=1&gid=7&id=3&snippet=4\\" class=\\"crm-summary-link\\"><div' . ' class=\\"icon crm-icon Individual-icon\\"></div></a>","<a href=/index.php?q=civicrm/contact/view&reset=1&cid=3>Anderson, Anthony</a>","$ 100.00","12345","' . CRM_Utils_Date::customFormat(date('Ymd')) . ' 12:00 AM",' . '"Credit Card","Completed","Donation","<span><a href=\\"http://FIX ME/index.php?q=civicrm/contact/view/contribution&reset=1&id=1&cid=3&action=view&context=contribution&' . 'selectedChild=contribute\\" class=\\"action-item crm-hover-button\\" title=\'View Contribution\' >View</a></span>"]] }'); }
/** * build all the data structures needed to build the form * * @return void * @access public */ function preProcess() { parent::preProcess(); $rows = array(); // display name and pledge details of all selected contacts $pledgeIDs = implode(',', $this->_pledgeIds); $query = "\n SELECT plg.amount as amount,\n plg.create_date as create_date,\n ct.display_name as display_name\n FROM civicrm_pledge plg\nINNER JOIN civicrm_contact ct ON ( plg.contact_id = ct.id ) \n WHERE plg.id IN ( {$pledgeIDs} )"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); while ($dao->fetch()) { $rows[] = array('display_name' => $dao->display_name, 'amount' => $dao->amount, 'create_date' => CRM_Utils_Date::customFormat($dao->create_date)); } $this->assign('rows', $rows); }
/** * Build all the data structures needed to build the form. * * @return void */ public function preProcess() { parent::preProcess(); $rows = array(); // display name and participation details of participants $participantIDs = implode(',', $this->_participantIds); $query = "\n SELECT p.fee_amount as amount,\n p.register_date as register_date,\n p.source as source,\n ct.display_name as display_name\n FROM civicrm_participant p\n INNER JOIN civicrm_contact ct ON ( p.contact_id = ct.id )\n WHERE p.id IN ( {$participantIDs} )"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); while ($dao->fetch()) { $rows[] = array('display_name' => $dao->display_name, 'amount' => $dao->amount, 'register_date' => CRM_Utils_Date::customFormat($dao->register_date), 'source' => $dao->source); } $this->assign('rows', $rows); }
/** * build all the data structures needed to build the form * * @return void * @access public */ function preProcess() { parent::preProcess(); $rows = array(); // display name and membership details of all selected contacts $memberIDs = implode(',', $this->_memberIds); $query = "\n SELECT mem.start_date as start_date,\n mem.end_date as end_date,\n mem.source as source, \n ct.display_name as display_name \nFROM civicrm_membership mem\nINNER JOIN civicrm_contact ct ON ( mem.contact_id = ct.id ) \nWHERE mem.id IN ( {$memberIDs} )"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); while ($dao->fetch()) { $rows[] = array('display_name' => $dao->display_name, 'start_date' => CRM_Utils_Date::customFormat($dao->start_date), 'end_date' => CRM_Utils_Date::customFormat($dao->end_date), 'source' => $dao->source); } $this->assign('rows', $rows); }
/** * Build all the data structures needed to build the form. * * @return void */ public function preProcess() { parent::preProcess(); $rows = array(); // display name and email of all contact ids $caseIDs = implode(',', $this->_caseIds); $statusId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'case_status', 'id', 'name'); $query = "\nSELECT ct.display_name as display_name,\n cs.start_date as start_date,\n ov.label as status\n\nFROM civicrm_case cs\nINNER JOIN civicrm_case_contact cc ON ( cs.id = cc.case_id)\nINNER JOIN civicrm_contact ct ON ( cc.contact_id = ct.id)\nLEFT JOIN civicrm_option_value ov ON (cs.status_id = ov.value AND ov.option_group_id = {$statusId} )\nWHERE cs.id IN ( {$caseIDs} )"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); while ($dao->fetch()) { $rows[] = array('display_name' => $dao->display_name, 'start_date' => CRM_Utils_Date::customFormat($dao->start_date), 'status' => $dao->status); } $this->assign('rows', $rows); }
public function generateLabel($participant) { $x = $this->pdf->GetAbsX(); $y = $this->pdf->GetY(); $this->printBackground(TRUE); $this->pdf->SetLineStyle(array('width' => 0.1, 'cap' => 'round', 'join' => 'round', 'dash' => '2,2', 'color' => array(0, 0, 200))); $this->pdf->SetFontSize(8); $this->pdf->MultiCell($this->pdf->width - $this->lMarginLogo, 0, $participant['event_title'], $this->border, "L", 0, 1, $x + $this->lMarginLogo, $y); $this->pdf->SetXY($x, $y + $this->pdf->height - 5); $date = CRM_Utils_Date::customFormat($participant['event_start_date'], "%e %b"); $this->pdf->Cell($this->pdf->width, 0, $date, $this->border, 2, "R"); $this->pdf->SetFontSize(15); $this->pdf->MultiCell($this->pdf->width, 10, $participant['display_name'], $this->border, "C", 0, 1, $x, $y + $this->tMarginName); $this->pdf->SetFontSize(10); $this->pdf->MultiCell($this->pdf->width, 0, $participant['current_employer'], $this->border, "C", 0, 1, $x, $this->pdf->getY()); }
/** * Convert the date string "YYYY-MM-DD" to "MM<long> DD, YYYY". * * @param string $dateString date which needs to converted to human readable format * * @return string human readable date format | invalid date message * @access public */ function smarty_modifier_crmDate($dateString, $dateFormat = null, $onlyTime = false) { if ($dateString) { // this check needs to be type sensitive // CRM-3689, CRM-2441 if ($dateFormat === 0) { $dateFormat = null; } if ($onlyTime) { $config = CRM_Core_Config::singleton(); $dateFormat = $config->dateformatTime; } return CRM_Utils_Date::customFormat($dateString, $dateFormat); } return ''; }
function testGetAllRows() { $mailchimp_sync_log = CRM_CiviMailchimp_BAO_SyncLogTest::createTestLogMessage('This is a test error message'); $details = unserialize($mailchimp_sync_log->details); $details = print_r($details, TRUE); $timestamp = date('c', $mailchimp_sync_log->timestamp); $timestamp = CRM_Utils_Date::customFormat($timestamp); $rows = CRM_CiviMailchimp_Page_SyncLog::getAllRows(); $this->assertCount(1, $rows); $this->assertEquals($mailchimp_sync_log->id, $rows[0]['id']); $this->assertEquals('Error', $rows[0]['type']); $this->assertEquals('CiviCRM to Mailchimp', $rows[0]['direction']); $this->assertEquals($mailchimp_sync_log->message, $rows[0]['message']); $this->assertEquals($details, $rows[0]['details']); $this->assertEquals($timestamp, $rows[0]['timestamp']); }
/** * @param $participant */ public function generateLabel($participant) { $date = CRM_Utils_Date::customFormat($participant['event_start_date'], "%e %b"); $this->pdf->SetFontSize(8); $y = $this->pdf->GetY(); $x = $this->pdf->GetAbsX(); $this->pdf->Cell($this->pdf->width, $this->pdf->lineHeight, $participant['event_title'], 0, 1, "L"); $this->pdf->SetXY($x, $y + 4); $this->pdf->Cell($this->pdf->width, $this->pdf->lineHeight, $date, 0, 2, "R"); $this->pdf->SetFontSize(12); $this->pdf->SetXY($x, $this->pdf->GetY() + 5); $this->pdf->Cell($this->pdf->width, $this->pdf->lineHeight, $participant['display_name'], 0, 2, "C"); $this->pdf->SetFontSize(10); $this->pdf->SetXY($x, $this->pdf->GetY() + 2); $this->pdf->Cell($this->pdf->width, $this->pdf->lineHeight, $participant['current_employer'], 0, 2, "C"); //$this->pdf->MultiCell ($this->pdf->width, $this->pdf->lineHeight, $txt,1,"L"); }
static function getAllRows() { $query = "\n SELECT\n *\n FROM \n civimailchimp_sync_log\n ORDER BY id DESC;\n "; $mailchimp_sync_log = CRM_Core_DAO::executeQuery($query); $rows = array(); while ($mailchimp_sync_log->fetch()) { if ($mailchimp_sync_log->direction === 'civicrm_to_mailchimp') { $direction = 'CiviCRM to Mailchimp'; } elseif ($mailchimp_sync_log->direction === 'mailchimp_to_civicrm') { $direction = 'Mailchimp to CiviCRM'; } $details = unserialize($mailchimp_sync_log->details); $details = print_r($details, TRUE); $timestamp = date('c', $mailchimp_sync_log->timestamp); $timestamp = CRM_Utils_Date::customFormat($timestamp); $rows[] = array('id' => $mailchimp_sync_log->id, 'type' => ucfirst($mailchimp_sync_log->type), 'direction' => $direction, 'message' => $mailchimp_sync_log->message, 'details' => $details, 'timestamp' => $timestamp); } return $rows; }
/** * Heart of the viewing process. The runner gets all the meta data for * the contact and calls the appropriate type of page to view. * * @return void * @access public * */ function preProcess() { CRM_Utils_System::setTitle(ts('CiviPledge')); $startToDate = array(); $yearToDate = array(); $monthToDate = array(); $previousToDate = array(); $prefixes = array('start', 'month', 'year', 'previous'); $status = array('Completed', 'Cancelled', 'Pending', 'In Progress', 'Overdue'); // cumulative (since inception) - prefix = 'start' $startDate = null; $startDateEnd = null; // current year - prefix = 'year' $config =& CRM_Core_Config::singleton(); $yearDate = $config->fiscalYearStart; $year = array('Y' => date('Y')); $this->assign('curYear', $year['Y']); $yearDate = array_merge($year, $yearDate); $yearDate = CRM_Utils_Date::format($yearDate); $yearDate = $yearDate . '000000'; $yearDateEnd = $year['Y'] . '1231235959'; // current month - prefix = 'month' $currentMonth = date("F Y", mktime(0, 0, 0, date("m"), 01, date("Y"))); $this->assign('currentMonthYear', $currentMonth); $monthDate = date('Ym') . '01000000'; $monthDateEnd = CRM_Utils_Date::customFormat(date("Y-m-t", mktime(0, 0, 0, date("m"), 01, date("Y"))), '%Y%m%d') . '235959'; // previous month - prefix = 'previous' $previousDate = CRM_Utils_Date::customFormat(date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))), '%Y%m%d') . '000000'; $previousDateEnd = CRM_Utils_Date::customFormat(date("Y-m-t", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))), '%Y%m%d') . '235959'; $previousMonth = date("F Y", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))); $this->assign('previousMonthYear', $previousMonth); require_once 'CRM/Pledge/BAO/Pledge.php'; foreach ($prefixes as $prefix) { $aName = $prefix . 'ToDate'; $startName = $prefix . 'Date'; $endName = $prefix . 'DateEnd'; foreach ($status as $s) { ${$aName}[str_replace(" ", "", $s)] = CRM_Pledge_BAO_Pledge::getTotalAmountAndCount($s, ${$startName}, ${$endName}); } $this->assign($aName, ${$aName}); } }
/** * Function to get Case Activities * * @param int $caseID case id * @param array $params posted params * @param int $contactID contact id * * @param null $context * @param null $userID * @param null $type * * @return returns case activities * * @static */ static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) { $values = array(); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); // CRM-5081 - formatting the dates to omit seconds. // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue. $select = "SELECT count(ca.id) as ismultiple, ca.id as id,\n ca.activity_type_id as type,\n ca.activity_type_id as activity_type_id,\n cc.sort_name as reporter,\n cc.id as reporter_id,\n acc.sort_name AS assignee,\n acc.id AS assignee_id,\n DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,\n ca.activity_date_time,\n DATE_ADD(NOW(), INTERVAL 1 YEAR)\n ), '%Y%m%d%H%i00') as overdue_date,\n DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,\n ca.status_id as status,\n ca.subject as subject,\n ca.is_deleted as deleted,\n ca.priority_id as priority,\n ca.weight as weight,\n GROUP_CONCAT(ef.file_id) as attachment_ids "; $from = "\n FROM civicrm_case_activity cca\n INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id\n INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}\n INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id\n INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'\n INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id\n AND cov.value = ca.activity_type_id AND cov.is_active = 1\n LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity' AND ef.entity_id = ca.id\n LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'\n LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'\n LEFT JOIN civicrm_activity_contact caa\n ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}\n LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id "; $where = 'WHERE cca.case_id= %1 AND ca.is_current_revision = 1'; if (!empty($params['reporter_id'])) { $where .= " AND cac.contact_id = " . CRM_Utils_Type::escape($params['reporter_id'], 'Integer'); } if (!empty($params['status_id'])) { $where .= " AND ca.status_id = " . CRM_Utils_Type::escape($params['status_id'], 'Integer'); } if (!empty($params['activity_deleted'])) { $where .= " AND ca.is_deleted = 1"; } else { $where .= " AND ca.is_deleted = 0"; } if (!empty($params['activity_type_id'])) { $where .= " AND ca.activity_type_id = " . CRM_Utils_Type::escape($params['activity_type_id'], 'Integer'); } if (!empty($params['activity_date_low'])) { $fromActivityDate = CRM_Utils_Type::escape(CRM_Utils_Date::processDate($params['activity_date_low']), 'Date'); } if (!empty($params['activity_date_high'])) { $toActivityDate = CRM_Utils_Type::escape(CRM_Utils_Date::processDate($params['activity_date_high']), 'Date'); $toActivityDate = $toActivityDate ? $toActivityDate + 235959 : NULL; } if (!empty($fromActivityDate)) { $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'"; } if (!empty($toActivityDate)) { $where .= " AND ca.activity_date_time <= '{$toActivityDate}'"; } // hack to handle to allow initial sorting to be done by query if (CRM_Utils_Array::value('sortname', $params) == 'undefined') { $params['sortname'] = NULL; } if (CRM_Utils_Array::value('sortorder', $params) == 'undefined') { $params['sortorder'] = NULL; } $sortname = CRM_Utils_Array::value('sortname', $params); $sortorder = CRM_Utils_Array::value('sortorder', $params); $groupBy = " GROUP BY ca.id "; if (!$sortname and !$sortorder) { // CRM-5081 - added id to act like creation date $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC"; } else { $sort = "{$sortname} {$sortorder}"; $sort = CRM_Utils_Type::escape($sort, 'String'); $orderBy = " ORDER BY {$sort} "; if ($sortname != 'display_date') { $orderBy .= ', display_date DESC'; } } $page = CRM_Utils_Array::value('page', $params); $rp = CRM_Utils_Array::value('rp', $params); if (!$page) { $page = 1; } if (!$rp) { $rp = 10; } $start = ($page - 1) * $rp; $query = $select . $from . $where . $groupBy . $orderBy; $params = array(1 => array($caseID, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); $params['total'] = $dao->N; //FIXME: need to optimize/cache these queries $limit = " LIMIT {$start}, {$rp}"; $query .= $limit; //EXIT; $dao = CRM_Core_DAO::executeQuery($query, $params); $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE); $activityStatus = CRM_Core_PseudoConstant::activityStatus(); $activityPriority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id'); $url = CRM_Utils_System::url("civicrm/case/activity", "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE); $contextUrl = ''; if ($context == 'fulltext') { $contextUrl = "&context={$context}"; } $editUrl = "{$url}&action=update{$contextUrl}"; $deleteUrl = "{$url}&action=delete{$contextUrl}"; $restoreUrl = "{$url}&action=renew{$contextUrl}"; $viewTitle = ts('View this activity.'); $statusTitle = ts('Edit status'); $emailActivityTypeIDs = array('Email' => CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name'), 'Inbound Email' => CRM_Core_OptionGroup::getValue('activity_type', 'Inbound Email', 'name')); $emailActivityTypeIDs = array('Email' => CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name'), 'Inbound Email' => CRM_Core_OptionGroup::getValue('activity_type', 'Inbound Email', 'name')); $caseDeleted = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted'); // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status) $compStatusValues = array(); $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required'); foreach ($compStatusNames as $name) { $compStatusValues[] = CRM_Core_OptionGroup::getValue('activity_status', $name, 'name'); } $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE); $hasViewContact = CRM_Core_Permission::giveMeAllACLs(); $clientIds = self::retrieveContactIdsByCaseId($caseID); if (!$userID) { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); } while ($dao->fetch()) { $allowView = self::checkPermission($dao->id, 'view', $dao->activity_type_id, $userID); $allowEdit = self::checkPermission($dao->id, 'edit', $dao->activity_type_id, $userID); $allowDelete = self::checkPermission($dao->id, 'delete', $dao->activity_type_id, $userID); //do not have sufficient permission //to access given case activity record. if (!$allowView && !$allowEdit && !$allowDelete) { continue; } $values[$dao->id]['id'] = $dao->id; $values[$dao->id]['type'] = $activityTypes[$dao->type]['label']; $reporterName = $dao->reporter; if ($hasViewContact) { $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id . '">' . $dao->reporter . '</a>'; } $values[$dao->id]['reporter'] = $reporterName; $targetNames = CRM_Activity_BAO_ActivityContact::getNames($dao->id, $targetID); $targetContactUrls = $withContacts = array(); foreach ($targetNames as $targetId => $targetName) { if (!in_array($targetId, $clientIds)) { $withContacts[$targetId] = $targetName; } } foreach ($withContacts as $cid => $name) { if ($hasViewContact) { $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>'; } $targetContactUrls[] = $name; } $values[$dao->id]['with_contacts'] = implode('; ', $targetContactUrls); $values[$dao->id]['display_date'] = CRM_Utils_Date::customFormat($dao->display_date); $values[$dao->id]['status'] = $activityStatus[$dao->status]; //check for view activity. $subject = empty($dao->subject) ? '(' . ts('no subject') . ')' : $dao->subject; if ($allowView) { $url = CRM_Utils_System::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $dao->id)); $subject = '<a class="crm-popup medium-popup" href="' . $url . '" title="' . $viewTitle . '">' . $subject . '</a>'; } $values[$dao->id]['subject'] = $subject; // add activity assignee to activity selector. CRM-4485. if (isset($dao->assignee)) { if ($dao->ismultiple == 1) { if ($dao->reporter_id != $dao->assignee_id) { $values[$dao->id]['reporter'] .= $hasViewContact ? ' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>{$dao->assignee}</a>" : ' / ' . $dao->assignee; } $values[$dao->id]['assignee'] = $dao->assignee; } else { $values[$dao->id]['reporter'] .= ' / ' . ts('(multiple)'); } } // FIXME: Why are we not using CRM_Core_Action for these links? This is too much manual work and likely to get out-of-sync with core markup. $url = ""; $css = 'class="action-item crm-hover-button"'; $additionalUrl = "&id={$dao->id}"; if (!$dao->deleted) { //hide edit link of activity type email.CRM-4530. if (!in_array($dao->type, $emailActivityTypeIDs)) { //hide Edit link if activity type is NOT editable (special case activities).CRM-5871 if ($allowEdit) { $url = '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> '; } } if ($allowDelete) { $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>'; } } elseif (!$caseDeleted) { $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>'; $values[$dao->id]['status'] = $values[$dao->id]['status'] . '<br /> (deleted)'; } //check for operations. if (self::checkPermission($dao->id, 'Move To Case', $dao->activity_type_id)) { $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> '; } if (self::checkPermission($dao->id, 'Copy To Case', $dao->activity_type_id)) { $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> '; } // if there are file attachments we will return how many and, if only one, add a link to it if (!empty($dao->attachment_ids)) { $attachmentIDs = explode(',', $dao->attachment_ids); $values[$dao->id]['no_attachments'] = count($attachmentIDs); if ($values[$dao->id]['no_attachments'] == 1) { // if there is only one it's easy to do a link - otherwise just flag it $attachmentViewUrl = CRM_Utils_System::url("civicrm/file", "reset=1&eid=" . $dao->id . "&id=" . $dao->attachment_ids, FALSE, NULL, FALSE); $url .= " <a href='{$attachmentViewUrl}' ><span class='icon paper-icon'></span></a>"; } } $values[$dao->id]['links'] = $url; $values[$dao->id]['class'] = ""; if (!empty($dao->priority)) { if ($dao->priority == CRM_Core_OptionGroup::getValue('priority', 'Urgent', 'name')) { $values[$dao->id]['class'] = $values[$dao->id]['class'] . "priority-urgent "; } elseif ($dao->priority == CRM_Core_OptionGroup::getValue('priority', 'Low', 'name')) { $values[$dao->id]['class'] = $values[$dao->id]['class'] . "priority-low "; } } if (CRM_Utils_Array::crmInArray($dao->status, $compStatusValues)) { $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-completed"; } else { if (CRM_Utils_Date::overdue($dao->display_date)) { $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-overdue"; } else { $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-scheduled"; } } if ($allowEdit) { $values[$dao->id]['status'] = '<a class="crm-activity-status crm-activity-status-' . $dao->id . ' ' . $values[$dao->id]['class'] . ' crm-activity-change-status crm-editable-enabled" activity_id=' . $dao->id . ' current_status=' . $dao->status . ' case_id=' . $caseID . ' href="#" title=\'' . $statusTitle . '\'>' . $values[$dao->id]['status'] . '</a>'; } } $dao->free(); return $values; }
public function postProcess() { $this->beginPostProcess(); $create = $subSelect1 = $subSelect2 = NULL; list($fromTable, $fromAlias, $fromCol) = $this->groupBy(TRUE); if ($fromTable == 'civicrm_contact') { $contriCol = "contact_id"; } elseif ($fromTable == 'civicrm_contribution_type') { $contriCol = "contribution_type_id"; } elseif ($fromTable == 'civicrm_contribution') { $contriCol = $fromCol; } elseif ($fromTable == 'civicrm_address') { $contriCol = "contact_id"; } elseif ($fromTable == 'civicrm_financial_type') { $contriCol = 'financial_type_id'; $subSelect1 = 'contribution1.contact_id,'; $subSelect2 = 'contribution2.contact_id,'; $create = 'contact_id int unsigned,'; } $subWhere = $this->whereContribution(); $subContributionQuery1 = "\nSELECT {$subSelect1} contribution1.{$contriCol},\n sum( contribution1.total_amount ) AS total_amount_sum,\n count( * ) AS total_amount_count\nFROM civicrm_contribution contribution1\n{$subWhere}\nGROUP BY contribution1.{$contriCol}"; $subWhere = $this->whereContribution('contribution2'); $subContributionQuery2 = "\nSELECT {$subSelect2} contribution2.{$contriCol},\n sum( contribution2.total_amount ) AS total_amount_sum,\n count( * ) AS total_amount_count,\n currency\nFROM civicrm_contribution contribution2\n{$subWhere}\nGROUP BY contribution2.{$contriCol}"; $sql = "\nCREATE TEMPORARY TABLE civicrm_temp_civireport_repeat1 (\n{$create}\n{$contriCol} int unsigned,\ntotal_amount_sum int,\ntotal_amount_count int\n) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"; CRM_Core_DAO::executeQuery($sql); $sql = "INSERT INTO civicrm_temp_civireport_repeat1 {$subContributionQuery1}"; CRM_Core_DAO::executeQuery($sql); $sql = "\nCREATE TEMPORARY TABLE civicrm_temp_civireport_repeat2 (\n{$create}\n{$contriCol} int unsigned,\ntotal_amount_sum int,\ntotal_amount_count int,\ncurrency varchar(3)\n) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"; CRM_Core_DAO::executeQuery($sql); $sql = "INSERT INTO civicrm_temp_civireport_repeat2 {$subContributionQuery2}"; CRM_Core_DAO::executeQuery($sql); $this->select(); $this->from(); $this->where(); $this->groupBy(); $this->limit(); $count = 0; $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_limit}"; $dao = CRM_Core_DAO::executeQuery($sql); $rows = array(); while ($dao->fetch()) { foreach ($this->_columnHeaders as $key => $value) { $rows[$count][$key] = $dao->{$key}; } $count++; } // FIXME: calculate % using query foreach ($rows as $uid => $row) { if ($row['contribution1_total_amount_sum'] && $row['contribution2_total_amount_sum']) { $rows[$uid]['change'] = number_format(($row['contribution2_total_amount_sum'] - $row['contribution1_total_amount_sum']) * 100 / $row['contribution1_total_amount_sum'], 2); } elseif ($row['contribution1_total_amount_sum']) { $rows[$uid]['change'] = ts('Skipped Donation'); } elseif ($row['contribution2_total_amount_sum']) { $rows[$uid]['change'] = ts('New Donor'); } if ($row['contribution1_total_amount_count']) { $rows[$uid]['contribution1_total_amount_sum'] = $row['contribution1_total_amount_sum'] . " ({$row['contribution1_total_amount_count']})"; } if ($row['contribution2_total_amount_count']) { $rows[$uid]['contribution2_total_amount_sum'] = $row['contribution2_total_amount_sum'] . " ({$row['contribution2_total_amount_count']})"; } } $this->_columnHeaders['change'] = array('title' => '% Change', 'type' => CRM_Utils_Type::T_INT); // hack to fix title list($from1, $to1) = $this->getFromTo(CRM_Utils_Array::value("receive_date1_relative", $this->_params), CRM_Utils_Array::value("receive_date1_from", $this->_params), CRM_Utils_Array::value("receive_date1_to", $this->_params)); $from1 = CRM_Utils_Date::customFormat($from1, NULL, array('d')); $to1 = CRM_Utils_Date::customFormat($to1, NULL, array('d')); list($from2, $to2) = $this->getFromTo(CRM_Utils_Array::value("receive_date2_relative", $this->_params), CRM_Utils_Array::value("receive_date2_from", $this->_params), CRM_Utils_Array::value("receive_date2_to", $this->_params)); $from2 = CRM_Utils_Date::customFormat($from2, NULL, array('d')); $to2 = CRM_Utils_Date::customFormat($to2, NULL, array('d')); $this->_columnHeaders['contribution1_total_amount_sum']['title'] = "{$from1} -<br/> {$to1}"; $this->_columnHeaders['contribution2_total_amount_sum']['title'] = "{$from2} -<br/> {$to2}"; unset($this->_columnHeaders['contribution1_total_amount_count'], $this->_columnHeaders['contribution2_total_amount_count']); $this->formatDisplay($rows); // assign variables to templates $this->doTemplateAssignment($rows); $this->endPostProcess($rows); }
/** * Generate where for a single parameter. * * @param array $values * @param CRM_Contact_BAO_Query $query */ public static function whereClauseSingle(&$values, &$query) { list($name, $op, $value, $grouping) = $values; switch ($name) { case 'member_join_date_low': case 'member_join_date_high': $query->dateQueryBuilder($values, 'civicrm_membership', 'member_join_date', 'join_date', 'Member Since'); return; case 'member_start_date_low': case 'member_start_date_high': $query->dateQueryBuilder($values, 'civicrm_membership', 'member_start_date', 'start_date', 'Start Date'); return; case 'member_end_date_low': case 'member_end_date_high': $query->dateQueryBuilder($values, 'civicrm_membership', 'member_end_date', 'end_date', 'End Date'); return; case 'member_join_date': $op = '>='; $date = CRM_Utils_Date::format($value); if ($date) { $query->_where[$grouping][] = "civicrm_membership.join_date {$op} {$date}"; $format = CRM_Utils_Date::customFormat(CRM_Utils_Date::format(array_reverse($value), '-')); $query->_qill[$grouping][] = ts('Member Since %2 %1', array(1 => $format, 2 => $op)); } return; case 'member_source': $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; $value = $strtolower(CRM_Core_DAO::escapeString(trim($value))); $query->_where[$grouping][] = "civicrm_membership.source {$op} '{$value}'"; $query->_qill[$grouping][] = ts('Source %2 %1', array(1 => $value, 2 => $op)); $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1; return; // CRM-17011 These 2 variants appear in some smart groups saved at some time prior to 4.6.6. // CRM-17011 These 2 variants appear in some smart groups saved at some time prior to 4.6.6. case 'member_status_id': case 'member_membership_type_id': if (is_array($value)) { $op = 'IN'; $value = array_keys($value); } case 'membership_type_id': // CRM-17075 we are specifically handling the possibility we are dealing with the entity reference field // for membership_type_id here (although status would be handled if converted). The unhandled pathway at the moment // is from groupContactCache::load and this is a small fix to get the entity reference field to work. // However, it would seem the larger fix would be to NOT invoke the form formValues for // the load function. The where clause and the whereTables are saved so they should suffice to generate the query // to get a contact list. But, better to deal with in 4.8 now... if (is_string($value) && strpos($value, ',') && $op == '=') { $value = array('IN' => explode(',', $value)); } case 'membership_status': case 'membership_status_id': case 'membership_type': case 'member_id': if (strstr($name, 'status') && is_string($value) && !is_numeric($value)) { $value = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', $value); } if (strpos($name, 'status') !== FALSE) { $name = 'status_id'; $qillName = 'Membership Status(s)'; } elseif ($name == 'member_id') { $name = 'id'; $qillName = 'Membership ID'; } else { $name = 'membership_type_id'; $qillName = 'Membership Type(s)'; } $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.{$name}", $op, $value, "Integer"); list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Member_DAO_Membership', $name, $value, $op); $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $qillName, 2 => $op, 3 => $value)); $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1; return; case 'member_test': // We dont want to include all tests for sql OR CRM-7827 if (!$value || $query->getOperator() != 'OR') { $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_test", $op, $value, "Boolean"); if ($value) { $query->_qill[$grouping][] = ts('Membership is a Test'); } } $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1; return; case 'member_auto_renew': $op = "!="; if ($value) { $query->_where[$grouping][] = " civicrm_membership.contribution_recur_id IS NOT NULL"; $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("ccr.contribution_status_id", $op, array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')), "Integer"); $query->_qill[$grouping][] = ts("Membership is Auto-Renew"); } else { $query->_where[$grouping][] = " civicrm_membership.contribution_recur_id IS NULL"; $query->_qill[$grouping][] = ts("Membership is NOT Auto-Renew"); } $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1; return; case 'member_pay_later': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_pay_later", $op, $value, "Integer"); if ($value) { $query->_qill[$grouping][] = ts("Membership is Pay Later"); } else { $query->_qill[$grouping][] = ts("Membership is NOT Pay Later"); } $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1; return; case 'member_is_primary': if ($value) { $query->_where[$grouping][] = " civicrm_membership.owner_membership_id IS NULL"; $query->_qill[$grouping][] = ts("Primary Members Only"); } else { $query->_where[$grouping][] = " civicrm_membership.owner_membership_id IS NOT NULL"; $query->_qill[$grouping][] = ts("Related Members Only"); } $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1; return; case 'member_is_override': $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_override", $op, $value, "Boolean"); $query->_qill[$grouping][] = $value ? ts("Is Membership Status overriden? Yes") : ts("Is Membership Status overriden? No"); $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1; return; case 'member_campaign_id': if (CRM_Utils_Array::value($op, $value)) { $value = $value[$op]; } $campParams = array('op' => $op, 'campaign' => $value, 'grouping' => $grouping, 'tableName' => 'civicrm_membership'); CRM_Campaign_BAO_Query::componentSearchClause($campParams, $query); return; } }
/** * handle the values in import mode * * @param int $onDuplicate the code for what action to take on duplicates * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * @access public */ function import($onDuplicate, &$values) { try { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); //assign join date equal to start date if join date is not provided if (!CRM_Utils_Array::value('join_date', $params) && CRM_Utils_Array::value('membership_start_date', $params)) { $params['join_date'] = $params['membership_start_date']; } $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $formatted = array(); $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params)); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = TRUE; $dateLabels = array('join_date' => ts('Member Since'), 'membership_start_date' => ts('Start Date'), 'membership_end_date' => ts('End Date')); foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'join_date': case 'membership_start_date': case 'membership_end_date': if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) { if (!CRM_Utils_Rule::date($params[$key])) { CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage); } } else { CRM_Contact_Import_Parser_Contact::addToErrorMsg($dateLabels[$key], $errorMessage); } break; case 'membership_type_id': if (!is_numeric($val)) { unset($params['membership_type_id']); $params['membership_type'] = $val; } break; case 'status_id': if (!is_numeric($val)) { unset($params['status_id']); $params['membership_status'] = $val; } break; case 'is_override': $params[$key] = CRM_Utils_String::strtobool($val); break; } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } else { if ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } } //date-Format part ends static $indieFields = NULL; if ($indieFields == NULL) { $tempIndieFields = CRM_Member_DAO_Membership::import(); $indieFields = $tempIndieFields; } $formatValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $formatValues[$key] = $field; } //format params to meet api v2 requirements. //@todo find a way to test removing this formatting $formatError = $this->membership_format_params($formatValues, $formatted, TRUE); if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, NULL, 'Membership'); } else { //fix for CRM-2219 Update Membership // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE if (CRM_Utils_Array::value('is_override', $formatted) && !CRM_Utils_Array::value('status_id', $formatted)) { array_unshift($values, 'Required parameter missing: Status'); return CRM_Import_Parser::ERROR; } if (!empty($formatValues['membership_id'])) { $dao = new CRM_Member_BAO_Membership(); $dao->id = $formatValues['membership_id']; $dates = array('join_date', 'start_date', 'end_date'); foreach ($dates as $v) { if (!CRM_Utils_Array::value($v, $formatted)) { $formatted[$v] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $formatValues['membership_id'], $v); } } $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, CRM_Core_DAO::$_nullObject, $formatValues['membership_id'], 'Membership'); if ($dao->find(TRUE)) { $ids = array('membership' => $formatValues['membership_id'], 'userId' => $session->get('userID')); $newMembership = CRM_Member_BAO_Membership::create($formatted, $ids, TRUE); if (civicrm_error($newMembership)) { array_unshift($values, $newMembership['is_error'] . ' for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } else { $this->_newMemberships[] = $newMembership->id; return CRM_Import_Parser::VALID; } } else { array_unshift($values, 'Matching Membership record not found for Membership ID ' . $formatValues['membership_id'] . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } } } //Format dates $startDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $formatted), '%Y-%m-%d'); $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $formatted), '%Y-%m-%d'); $joinDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $formatted), '%Y-%m-%d'); if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule $formatValues['contact_type'] = $this->_contactType; $formatValues['version'] = 3; require_once 'CRM/Utils/DeprecatedUtils.php'; $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) > 1) { array_unshift($values, 'Multiple matching contact records detected for this row. The membership was not imported'); return CRM_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; //fix for CRM-1924 $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate); self::formattedDates($calcDates, $formatted); //fix for CRM-3570, exclude the statuses those having is_admin = 1 //now user can import is_admin if is override is true. $excludeIsAdmin = FALSE; if (!CRM_Utils_Array::value('is_override', $formatted)) { $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE; } $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted); if (!CRM_Utils_Array::value('status_id', $formatted)) { $formatted['status_id'] = $calcStatus['id']; } elseif (!CRM_Utils_Array::value('is_override', $formatted)) { if (empty($calcStatus)) { array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.'); return CRM_Import_Parser::ERROR; } elseif ($formatted['status_id'] != $calcStatus['id']) { //Status Hold" is either NOT mapped or is FALSE array_unshift($values, 'Status in import row (' . $formatValues['status_id'] . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.'); return CRM_Import_Parser::ERROR; } } $newMembership = civicrm_api3('membership', 'create', $formatted); $this->_newMemberships[] = $newMembership['id']; return CRM_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = ''; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (CRM_Utils_Array::value('external_identifier', $params)) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (CRM_Utils_Array::value('external_identifier', $formatValues)) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $formatValues['external_identifier']; $checkCid->find(TRUE); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, 'Mismatch of External identifier :' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_Import_Parser::ERROR; } } //to calculate dates $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($formatted['membership_type_id'], $joinDate, $startDate, $endDate); self::formattedDates($calcDates, $formatted); //end of date calculation part //fix for CRM-3570, exclude the statuses those having is_admin = 1 //now user can import is_admin if is override is true. $excludeIsAdmin = FALSE; if (!CRM_Utils_Array::value('is_override', $formatted)) { $formatted['exclude_is_admin'] = $excludeIsAdmin = TRUE; } $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin, $formatted['membership_type_id'], $formatted); if (!CRM_Utils_Array::value('status_id', $formatted)) { $formatted['status_id'] = CRM_Utils_Array::value('id', $calcStatus); } elseif (!CRM_Utils_Array::value('is_override', $formatted)) { if (empty($calcStatus)) { array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules. Record was not imported.'); return CRM_Import_Parser::ERROR; } elseif ($formatted['status_id'] != $calcStatus['id']) { //Status Hold" is either NOT mapped or is FALSE array_unshift($values, 'Status in import row (' . CRM_Utils_Array::value('status_id', $formatValues) . ') does not match calculated status based on your configured Membership Status Rules (' . $calcStatus['name'] . '). Record was not imported.'); return CRM_Import_Parser::ERROR; } } $newMembership = civicrm_api3('membership', 'create', $formatted); $this->_newMemberships[] = $newMembership['id']; return CRM_Import_Parser::VALID; } } catch (Exception $e) { array_unshift($values, $e->getMessage()); return CRM_Import_Parser::ERROR; } }
/** * This function update contribution as well as related objects. */ function transitionComponents($params, $processContributionObject = false) { // get minimum required values. $contactId = CRM_Utils_Array::value('contact_id', $params); $componentId = CRM_Utils_Array::value('component_id', $params); $componentName = CRM_Utils_Array::value('componentName', $params); $contributionId = CRM_Utils_Array::value('contribution_id', $params); $contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $params); // if we already processed contribution object pass previous status id. $previousContriStatusId = CRM_Utils_Array::value('previous_contribution_status_id', $params); $updateResult = array(); require_once 'CRM/Contribute/PseudoConstant.php'; $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(null, 'name'); // we process only ( Completed, Cancelled, or Failed ) contributions. if (!$contributionId || !in_array($contributionStatusId, array(array_search('Completed', $contributionStatuses), array_search('Cancelled', $contributionStatuses), array_search('Failed', $contributionStatuses)))) { return $updateResult; } if (!$componentName || !$componentId) { // get the related component details. $componentDetails = self::getComponentDetails($contributionId); } else { $componentDetails['contact_id'] = $contactId; $componentDetails['component'] = $componentName; if ($componentName = 'event') { $componentDetails['participant'] = $componentId; } else { $componentDetails['membership'] = $componentId; } } if (CRM_Utils_Array::value('contact_id', $componentDetails)) { $componentDetails['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id'); } // do check for required ids. if (!CRM_Utils_Array::value('membership', $componentDetails) && !CRM_Utils_Array::value('participant', $componentDetails) && !CRM_Utils_Array::value('pledge_payment', $componentDetails) || !CRM_Utils_Array::value('contact_id', $componentDetails)) { return $updateResult; } //now we are ready w/ required ids, start processing. require_once 'CRM/Core/Payment/BaseIPN.php'; $baseIPN = new CRM_Core_Payment_BaseIPN(); $input = $ids = $objects = array(); $input['component'] = CRM_Utils_Array::value('component', $componentDetails); $ids['contribution'] = $contributionId; $ids['contact'] = CRM_Utils_Array::value('contact_id', $componentDetails); $ids['membership'] = CRM_Utils_Array::value('membership', $componentDetails); $ids['participant'] = CRM_Utils_Array::value('participant', $componentDetails); $ids['event'] = CRM_Utils_Array::value('event', $componentDetails); $ids['pledge_payment'] = CRM_Utils_Array::value('pledge_payment', $componentDetails); $ids['contributionRecur'] = null; $ids['contributionPage'] = null; if (!$baseIPN->validateData($input, $ids, $objects, false)) { CRM_Core_Error::fatal(); } $membership =& $objects['membership']; $participant =& $objects['participant']; $pledgePayment =& $objects['pledge_payment']; $contribution =& $objects['contribution']; if ($pledgePayment) { require_once 'CRM/Pledge/BAO/Payment.php'; $pledgePaymentIDs = array(); foreach ($pledgePayment as $key => $object) { $pledgePaymentIDs[] = $object->id; } $pledgeID = $pledgePayment[0]->pledge_id; } require_once 'CRM/Event/PseudoConstant.php'; require_once 'CRM/Event/BAO/Participant.php'; require_once 'CRM/Pledge/BAO/Pledge.php'; require_once 'CRM/Member/PseudoConstant.php'; require_once 'CRM/Member/BAO/Membership.php'; $membershipStatuses = CRM_Member_PseudoConstant::membershipStatus(); if ($participant) { $participantStatuses = CRM_Event_PseudoConstant::participantStatus(); $oldStatus = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participant->id, 'status_id'); } // we might want to process contribution object. $processContribution = false; if ($contributionStatusId == array_search('Cancelled', $contributionStatuses)) { if ($membership) { $membership->status_id = array_search('Cancelled', $membershipStatuses); $membership->save(); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = true; } } if ($participant) { $updatedStatusId = array_search('Cancelled', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = true; } } if ($pledgePayment) { CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = true; } } } else { if ($contributionStatusId == array_search('Failed', $contributionStatuses)) { if ($membership) { $membership->status_id = array_search('Expired', $membershipStatuses); $membership->save(); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = true; } } if ($participant) { $updatedStatusId = array_search('Cancelled', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = true; } } if ($pledgePayment) { CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = true; } } } else { if ($contributionStatusId == array_search('Completed', $contributionStatuses)) { // only pending contribution related object processed. if ($previousContriStatusId && $previousContriStatusId != array_search('Pending', $contributionStatuses)) { // this is case when we already processed contribution object. return $updateResult; } else { if (!$previousContriStatusId && $contribution->contribution_status_id != array_search('Pending', $contributionStatuses)) { // this is case when we will going to process contribution object. return $updateResult; } } if ($membership) { $format = '%Y%m%d'; require_once 'CRM/Member/BAO/MembershipType.php'; //CRM-4523 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id); if ($currentMembership) { CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday = null); $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday = null); $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); } else { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id); } //get the status for membership. require_once 'CRM/Member/BAO/MembershipStatus.php'; $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', true); $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, array_search('Current', $membershipStatuses)), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), 'reminder_date' => CRM_Utils_Date::customFormat($dates['reminder_date'], $format)); $membership->copyValues($formatedParams); $membership->save(); //updating the membership log $membershipLog = array(); $membershipLog = $formatedParams; $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date']; $membershipLog['start_date'] = $logStartDate; $membershipLog['membership_id'] = $membership->id; $membershipLog['modified_id'] = $membership->contact_id; $membershipLog['modified_date'] = date('Ymd'); require_once 'CRM/Member/BAO/MembershipLog.php'; CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); //update related Memberships. CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams); $updateResult['membership_end_date'] = CRM_Utils_Date::customFormat($dates['end_date'], '%B %E%f, %Y'); $updateResult['updatedComponents']['CiviMember'] = $membership->status_id; if ($processContributionObject) { $processContribution = true; } } if ($participant) { $updatedStatusId = array_search('Registered', $participantStatuses); CRM_Event_BAO_Participant::updateParticipantStatus($participant->id, $oldStatus, $updatedStatusId, true); $updateResult['updatedComponents']['CiviEvent'] = $updatedStatusId; if ($processContributionObject) { $processContribution = true; } } if ($pledgePayment) { CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeID, $pledgePaymentIDs, $contributionStatusId); $updateResult['updatedComponents']['CiviPledge'] = $contributionStatusId; if ($processContributionObject) { $processContribution = true; } } } } } // process contribution object. if ($processContribution) { require_once 'CRM/Contribute/BAO/Contribution.php'; $contributionParams = array(); $fields = array('contact_id', 'total_amount', 'receive_date', 'is_test', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'contribution_type_id', 'contribution_status_id', 'non_deductible_amount', 'receipt_date', 'check_number'); foreach ($fields as $field) { if (!CRM_Utils_Array::value($field, $params)) { continue; } $contributionParams[$field] = $params[$field]; } $ids = array('contribution' => $contributionId); require_once 'CRM/Contribute/BAO/Contribution.php'; $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids); } return $updateResult; }
/** * Send email receipt. * * @param CRM_Core_Form $form * Form object. * @param array $formValues * @param object $membership * Object. * * @return bool * true if mail was sent successfully */ public static function emailReceipt(&$form, &$formValues, &$membership) { // retrieve 'from email id' for acknowledgement $receiptFrom = $formValues['from_email_address']; if (!empty($formValues['payment_instrument_id'])) { $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument(); $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']]; } // retrieve custom data $customFields = $customValues = array(); if (property_exists($form, '_groupTree') && !empty($form->_groupTree)) { foreach ($form->_groupTree as $groupID => $group) { if ($groupID == 'info') { continue; } foreach ($group['fields'] as $k => $field) { $field['title'] = $field['label']; $customFields["custom_{$k}"] = $field; } } } $members = array(array('member_id', '=', $membership->id, 0, 0)); // check whether its a test drive if ($form->_mode == 'test') { $members[] = array('member_test', '=', 1, 0, 0); } CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members); if ($form->_mode) { if (!empty($form->_params['billing_first_name'])) { $name = $form->_params['billing_first_name']; } if (!empty($form->_params['billing_middle_name'])) { $name .= " {$form->_params['billing_middle_name']}"; } if (!empty($form->_params['billing_last_name'])) { $name .= " {$form->_params['billing_last_name']}"; } $form->assign('billingName', $name); // assign the address formatted up for display $addressParts = array("street_address-{$form->_bltID}", "city-{$form->_bltID}", "postal_code-{$form->_bltID}", "state_province-{$form->_bltID}", "country-{$form->_bltID}"); $addressFields = array(); foreach ($addressParts as $part) { list($n, $id) = explode('-', $part); if (isset($form->_params['billing_' . $part])) { $addressFields[$n] = $form->_params['billing_' . $part]; } } $form->assign('address', CRM_Utils_Address::format($addressFields)); $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']); $date = CRM_Utils_Date::mysqlToIso($date); $form->assign('credit_card_exp_date', $date); $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number'])); $form->assign('credit_card_type', $form->_params['credit_card_type']); $form->assign('contributeMode', 'direct'); $form->assign('isAmountzero', 0); $form->assign('is_pay_later', 0); $form->assign('isPrimary', 1); } $form->assign('module', 'Membership'); $form->assign('contactID', $formValues['contact_id']); $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues))); if (!empty($formValues['contribution_id'])) { $form->assign('contributionID', $formValues['contribution_id']); } elseif (isset($form->_onlinePendingContributionId)) { $form->assign('contributionID', $form->_onlinePendingContributionId); } if (!empty($formValues['contribution_status_id'])) { $form->assign('contributionStatusID', $formValues['contribution_status_id']); $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name')); } if (!empty($formValues['is_renew'])) { $form->assign('receiptType', 'membership renewal'); } else { $form->assign('receiptType', 'membership signup'); } $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues))); $form->assign('formValues', $formValues); if (empty($lineItem)) { $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y')); if (!CRM_Utils_System::isNull($membership->end_date)) { $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y')); } $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id)); } $form->assign('customValues', $customValues); $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry'); if (empty($form->_contributorDisplayName) || empty($form->_contributorEmail) || $isBatchProcess) { // in this case the form is being called statically from the batch editing screen // having one class in the form layer call another statically is not greate // & we should aim to move this function to the BAO layer in future. // however, we can assume that the contact_id passed in by the batch // function will be the recipient list($form->_contributorDisplayName, $form->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']); if (empty($form->_receiptContactId) || $isBatchProcess) { $form->_receiptContactId = $formValues['contact_id']; } } $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $eventTaxAmt = $template->get_template_vars('totalTaxAmount'); $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $isEmailPdf = TRUE; } else { $isEmailPdf = FALSE; } list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $form->_receiptContactId, 'from' => $receiptFrom, 'toName' => $form->_contributorDisplayName, 'toEmail' => $form->_contributorEmail, 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf, 'contributionId' => $formValues['contribution_id'], 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW))); return TRUE; }
function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) { $contribution =& $objects['contribution']; $memberships =& $objects['membership']; if (is_numeric($memberships)) { $memberships = array($objects['membership']); } $participant =& $objects['participant']; $event =& $objects['event']; $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now); $recurContrib =& $objects['contributionRecur']; $values = array(); if ($input['component'] == 'contribute') { if ($contribution->contribution_page_id) { CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values); $source = ts('Online Contribution') . ': ' . $values['title']; } elseif ($recurContrib->id) { $contribution->contribution_page_id = NULL; $values['amount'] = $recurContrib->amount; $values['contribution_type_id'] = $objects['contributionType']->id; $values['title'] = $source = ts('Offline Recurring Contribution'); $values['is_email_receipt'] = $recurContrib->is_email_receipt; $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $values['receipt_from_name'] = $domainValues[0]; $values['receipt_from_email'] = $domainValues[1]; } $contribution->source = $source; if (CRM_Utils_Array::value('is_email_receipt', $values)) { $contribution->receipt_date = self::$_now; } if (!empty($memberships)) { foreach ($memberships as $membershipTypeIdKey => $membership) { if ($membership) { $format = '%Y%m%d'; $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id); // CRM-8141 update the membership type with the value recorded in log when membership created/renewed // this picks up membership type changes during renewals $sql = "\nSELECT membership_type_id\nFROM civicrm_membership_log\nWHERE membership_id={$membership->id}\nORDER BY id DESC\nLIMIT 1;"; $dao = new CRM_Core_DAO(); $dao->query($sql); if ($dao->fetch()) { if (!empty($dao->membership_type_id)) { $membership->membership_type_id = $dao->membership_type_id; $membership->save(); } // else fall back to using current membership type } // else fall back to using current membership type $dao->free(); if ($currentMembership) { /* * Fixed FOR CRM-4433 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status * when Contribution mode is notify and membership is for renewal ) */ CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday); $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday); $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); } else { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id); } //get the status for membership. $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE); $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format), 'reminder_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('reminder_date', $dates), $format)); //we might be renewing membership, //so make status override false. $formatedParams['is_override'] = FALSE; $membership->copyValues($formatedParams); $membership->save(); //updating the membership log $membershipLog = array(); $membershipLog = $formatedParams; $logStartDate = $formatedParams['start_date']; if (CRM_Utils_Array::value('log_start_date', $dates)) { $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate); } $membershipLog['start_date'] = $logStartDate; $membershipLog['membership_id'] = $membership->id; $membershipLog['modified_id'] = $membership->contact_id; $membershipLog['modified_date'] = date('Ymd'); $membershipLog['membership_type_id'] = $membership->membership_type_id; CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); //update related Memberships. CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams); //update the membership type key of membership relatedObjects array //if it has changed after membership update if ($membershipTypeIdKey != $membership->membership_type_id) { $memberships[$membership->membership_type_id] = $membership; $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership; unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]); unset($memberships[$membershipTypeIdKey]); } } } } } else { // event $eventParams = array('id' => $objects['event']->id); $values['event'] = array(); CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); $eventParams = array('id' => $objects['event']->id); $values['event'] = array(); CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); //get location details $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event'); $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent'); list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $values['custom_pre_id'] = $custom_pre_id; $values['custom_post_id'] = $custom_post_ids; $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title']; if ($values['event']['is_email_confirm']) { $contribution->receipt_date = self::$_now; $values['is_email_receipt'] = 1; } $participant->status_id = 1; $participant->save(); } if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) { $input['net_amount'] = $input['amount'] - $input['fee_amount']; } $addLineItems = FALSE; if (empty($contribution->id)) { $addLineItems = TRUE; } $contribution->contribution_status_id = 1; $contribution->is_test = $input['is_test']; $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0); $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0); $contribution->trxn_id = $input['trxn_id']; $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date); $contribution->cancel_date = 'null'; if (CRM_Utils_Array::value('check_number', $input)) { $contribution->check_number = $input['check_number']; } if (CRM_Utils_Array::value('payment_instrument_id', $input)) { $contribution->payment_instrument_id = $input['payment_instrument_id']; } $contribution->save(); //add lineitems for recurring payments if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) { $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id); } // next create the transaction record $paymentProcessor = ''; if (isset($objects['paymentProcessor'])) { if (is_array($objects['paymentProcessor'])) { $paymentProcessor = $objects['paymentProcessor']['payment_processor_type']; } else { $paymentProcessor = $objects['paymentProcessor']->payment_processor_type; } } if ($contribution->trxn_id) { $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id); $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams); } self::updateRecurLinkedPledge($contribution); // create an activity record if ($input['component'] == 'contribute') { //CRM-4027 $targetContactID = NULL; if (CRM_Utils_Array::value('related_contact', $ids)) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $ids['related_contact']; } CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); // event } else { CRM_Activity_BAO_Activity::addActivity($participant); } CRM_Core_Error::debug_log_message("Contribution record updated successfully"); $transaction->commit(); // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) { self::sendMail($input, $ids, $objects, $values, $recur, FALSE); } CRM_Core_Error::debug_log_message("Success: Database updated and mail sent"); }
/** * @param $row */ function alterRow(&$row) { $row['activity_date'] = CRM_Utils_Date::customFormat($row['activity_date'], '%B %E%f, %Y %l:%M %P'); }
/** * 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; $eventType = CRM_Core_OptionGroup::values('event_type'); $financialTypes = CRM_Contribute_PseudoConstant::financialType(); $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument(); foreach ($rows as $rowNum => $row) { // make count columns point to detail report // convert display name to links if (array_key_exists('civicrm_participant_event_id', $row)) { $eventId = $row['civicrm_participant_event_id']; if ($eventId) { $rows[$rowNum]['civicrm_participant_event_id'] = CRM_Event_PseudoConstant::event($eventId, FALSE); $url = CRM_Report_Utils_Report::getNextUrl('event/income', 'reset=1&force=1&id_op=in&id_value=' . $eventId, $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $rows[$rowNum]['civicrm_participant_event_id_link'] = $url; $rows[$rowNum]['civicrm_participant_event_id_hover'] = ts("View Event Income Details for this Event"); } $entryFound = TRUE; } // handle event type id $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_event_event_type_id', $rowNum, $eventType); // handle participant status id if (array_key_exists('civicrm_participant_status_id', $row)) { $statusId = $row['civicrm_participant_status_id']; if ($statusId) { $rows[$rowNum]['civicrm_participant_status_id'] = CRM_Event_PseudoConstant::participantStatus($statusId, FALSE, 'label'); } $entryFound = TRUE; } // handle participant role id if (array_key_exists('civicrm_participant_role_id', $row)) { $roleId = $row['civicrm_participant_role_id']; if ($roleId) { $roles = explode(CRM_Core_DAO::VALUE_SEPARATOR, $roleId); $roleId = array(); foreach ($roles as $role) { $roleId[$role] = CRM_Event_PseudoConstant::participantRole($role, FALSE); } $rows[$rowNum]['civicrm_participant_role_id'] = implode(', ', $roleId); } $entryFound = TRUE; } // Handel value seperator in Fee Level if (array_key_exists('civicrm_participant_participant_fee_level', $row)) { $feeLevel = $row['civicrm_participant_participant_fee_level']; if ($feeLevel) { CRM_Event_BAO_Participant::fixEventLevel($feeLevel); $rows[$rowNum]['civicrm_participant_participant_fee_level'] = $feeLevel; } $entryFound = TRUE; } // Convert display name to link $displayName = CRM_Utils_Array::value('civicrm_contact_sort_name_linked', $row); $cid = CRM_Utils_Array::value('civicrm_contact_id', $row); $id = CRM_Utils_Array::value('civicrm_participant_participant_record', $row); if ($displayName && $cid && $id) { $url = CRM_Report_Utils_Report::getNextUrl('contact/detail', "reset=1&force=1&id_op=eq&id_value={$cid}", $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $viewUrl = CRM_Utils_System::url("civicrm/contact/view/participant", "reset=1&id={$id}&cid={$cid}&action=view&context=participant"); $contactTitle = ts('View Contact Details'); $participantTitle = ts('View Participant Record'); $rows[$rowNum]['civicrm_contact_sort_name_linked'] = "<a title='{$contactTitle}' href={$url}>{$displayName}</a>"; if ($this->_outputMode !== 'csv') { $rows[$rowNum]['civicrm_contact_sort_name_linked'] .= "<span style='float: right;'><a title='{$participantTitle}' href={$viewUrl}>" . ts('View') . "</a></span>"; } $entryFound = TRUE; } // Handle country id if (array_key_exists('civicrm_address_country_id', $row)) { $countryId = $row['civicrm_address_country_id']; if ($countryId) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($countryId, TRUE); } $entryFound = TRUE; } // Handle state/province id if (array_key_exists('civicrm_address_state_province_id', $row)) { $provinceId = $row['civicrm_address_state_province_id']; if ($provinceId) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($provinceId, TRUE); } $entryFound = TRUE; } // Handle employer id if (array_key_exists('civicrm_contact_employer_id', $row)) { $employerId = $row['civicrm_contact_employer_id']; if ($employerId) { $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId); $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_employer_id_link'] = $url; $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for this Contact.'); } } // Convert campaign_id to campaign title $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_participant_campaign_id', $rowNum, $this->activeCampaigns); // handle contribution status $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_contribution_status_id', $rowNum, $contributionStatus); // handle payment instrument $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_payment_instrument_id', $rowNum, $paymentInstruments); // handle financial type $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_financial_type_id', $rowNum, $financialTypes); $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'event/participantListing', 'View Event Income Details') ? TRUE : $entryFound; // 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; } } }
/** * Process a PCP contribution. * * @param int $pcpId * @param $component * @param $entity * * @return array */ public static function handlePcp($pcpId, $component, $entity) { self::getPcpEntityTable($component); if (!$pcpId) { return FALSE; } $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name'); $pcpStatus = CRM_Core_OptionGroup::values("pcp_status"); $params = array('id' => $pcpId); CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo); $params = array('id' => $pcpInfo['pcp_block_id']); CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $params, $pcpBlock); $params = array('id' => $pcpInfo['page_id']); $now = time(); if ($component == 'event') { // figure out where to redirect if an exception occurs below based on target entity $urlBase = 'civicrm/event/register'; // ignore startDate for events - PCP's can be active long before event start date $startDate = 0; $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $entity)); } elseif ($component == 'contribute') { $urlBase = 'civicrm/contribute/transact'; //start and end date of the contribution page $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('start_date', $entity)); $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $entity)); } // define redirect url back to contrib page or event if needed $url = CRM_Utils_System::url($urlBase, "reset=1&id={$pcpBlock['entity_id']}", FALSE, NULL, FALSE, TRUE); if ($pcpBlock['target_entity_id'] != $entity['id']) { $statusMessage = ts('This page is not related to the Personal Campaign Page you have just visited. However you can still make a contribution here.'); CRM_Core_Error::statusBounce($statusMessage, $url); } elseif ($pcpInfo['status_id'] != $approvedId) { $statusMessage = ts('The Personal Campaign Page you have just visited is currently %1. However you can still support the campaign here.', array(1 => $pcpStatus[$pcpInfo['status_id']])); CRM_Core_Error::statusBounce($statusMessage, $url); } elseif (empty($pcpBlock['is_active'])) { $statusMessage = ts('Personal Campaign Pages are currently not enabled for this contribution page. However you can still support the campaign here.'); CRM_Core_Error::statusBounce($statusMessage, $url); } elseif (empty($pcpInfo['is_active'])) { $statusMessage = ts('The Personal Campaign Page you have just visited is currently inactive. However you can still support the campaign here.'); CRM_Core_Error::statusBounce($statusMessage, $url); } elseif ($startDate && $startDate > $now || $endDate && $endDate < $now) { $customStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $entity)); $customEndDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $entity)); if ($startDate && $endDate) { $statusMessage = ts('The Personal Campaign Page you have just visited is only active from %1 to %2. However you can still support the campaign here.', array(1 => $customStartDate, 2 => $customEndDate)); CRM_Core_Error::statusBounce($statusMessage, $url); } elseif ($startDate) { $statusMessage = ts('The Personal Campaign Page you have just visited will be active beginning on %1. However you can still support the campaign here.', array(1 => $customStartDate)); CRM_Core_Error::statusBounce($statusMessage, $url); } elseif ($endDate) { if ($component == 'event') { // Target_entity is an event and the event is over, redirect to event info instead of event registration page. $url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$pcpBlock['entity_id']}", FALSE, NULL, FALSE, TRUE); $statusMessage = ts('The event linked to the Personal Campaign Page you have just visited is over (as of %1).', array(1 => $customEndDate)); CRM_Core_Error::statusBounce($statusMessage, $url); } else { $statusMessage = ts('The Personal Campaign Page you have just visited is no longer active (as of %1). However you can still support the campaign here.', array(1 => $customEndDate)); CRM_Core_Error::statusBounce($statusMessage, $url); } } } return array('pcpId' => $pcpId, 'pcpBlock' => $pcpBlock, 'pcpInfo' => $pcpInfo); }
/** * @param int $contactID * @param int $membershipTypeID * @param bool $is_test * @param $changeToday * @param int $modifiedID * @param $customFieldsFormatted * @param $numRenewTerms * @param int $membershipID * @param $pending * @param int $contributionRecurID * @param $membershipSource * @param $isPayLater * @param int $campaignId * @param array $formDates * * @throws CRM_Core_Exception * @return array */ public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array()) { $renewalMode = $updateStatusId = FALSE; $allStatus = CRM_Member_PseudoConstant::membershipStatus(); $format = '%Y%m%d'; $statusFormat = '%Y-%m-%d'; $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipTypeID); $dates = array(); // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType // is the same as the parent org of an existing membership of the contact $currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID, $is_test, $membershipID, TRUE); if ($currentMembership) { $activityType = 'Membership Renewal'; $renewalMode = TRUE; // Do NOT do anything. //1. membership with status : PENDING/CANCELLED (CRM-2395) //2. Paylater/IPN renew. CRM-4556. if ($pending || in_array($currentMembership['status_id'], array(array_search('Pending', $allStatus), array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE))))) { $membership = new CRM_Member_DAO_Membership(); $membership->id = $currentMembership['id']; $membership->find(TRUE); // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed $format = '%Y%m%d'; // note that we are logging the requested new membership_type_id that may be different than current membership_type_id // it will be used when payment is received to update the membership_type_id to what was paid for $logParams = array('membership_id' => $membership->id, 'status_id' => $membership->status_id, 'start_date' => CRM_Utils_Date::customFormat($membership->start_date, $format), 'end_date' => CRM_Utils_Date::customFormat($membership->end_date, $format), 'modified_date' => CRM_Utils_Date::customFormat(date('Ymd'), $format), 'membership_type_id' => $membershipTypeID, 'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL); $session = CRM_Core_Session::singleton(); // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id if ($session->get('userID')) { $logParams['modified_id'] = $session->get('userID'); } else { $logParams['modified_id'] = $membership->contact_id; } CRM_Member_BAO_MembershipLog::add($logParams); if ($contributionRecurID) { CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $membership->id, 'contribution_recur_id', $contributionRecurID); } return array($membership, $renewalMode, $dates); } // Check and fix the membership if it is STALE self::fixMembershipStatusBeforeRenew($currentMembership, $changeToday); // Now Renew the membership if (!$currentMembership['is_current_member']) { // membership is not CURRENT // CRM-7297 Membership Upsell - calculate dates based on new membership type $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'], $changeToday, $membershipTypeID, $numRenewTerms); $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); foreach (array('start_date', 'end_date') as $dateType) { $currentMembership[$dateType] = CRM_Utils_Array::value($dateType, $formDates); if (empty($currentMembership[$dateType])) { $currentMembership[$dateType] = CRM_Utils_Array::value($dateType, $dates); } } $currentMembership['is_test'] = $is_test; if (!empty($membershipSource)) { $currentMembership['source'] = $membershipSource; } else { $currentMembership['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $currentMembership['id'], 'source'); } if (!empty($currentMembership['id'])) { $ids['membership'] = $currentMembership['id']; } $memParams = $currentMembership; $memParams['membership_type_id'] = $membershipTypeID; //set the log start date. $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); } else { // CURRENT Membership $membership = new CRM_Member_DAO_Membership(); $membership->id = $currentMembership['id']; $membership->find(TRUE); // CRM-7297 Membership Upsell - calculate dates based on new membership type $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, $membershipTypeID, $numRenewTerms); // Insert renewed dates for CURRENT membership $memParams = array(); $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date); $memParams['start_date'] = CRM_Utils_Date::isoToMysql($membership->start_date); $memParams['end_date'] = CRM_Utils_Array::value('end_date', $formDates); if (empty($memParams['end_date'])) { $memParams['end_date'] = CRM_Utils_Array::value('end_date', $dates); } $memParams['membership_type_id'] = $membershipTypeID; //set the log start date. $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); if (empty($membership->source)) { if (!empty($membershipSource)) { $memParams['source'] = $membershipSource; } else { $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $currentMembership['id'], 'source'); } } if (!empty($currentMembership['id'])) { $ids['membership'] = $currentMembership['id']; } } //CRM-4555 if ($pending) { $updateStatusId = array_search('Pending', $allStatus); } } else { // NEW Membership $activityType = 'Membership Signup'; $memParams = array('contact_id' => $contactID, 'membership_type_id' => $membershipTypeID); if (!$pending) { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms); foreach (array('join_date', 'start_date', 'end_date') as $dateType) { $memParams[$dateType] = CRM_Utils_Array::value($dateType, $formDates); if (empty($memParams[$dateType])) { $memParams[$dateType] = CRM_Utils_Array::value($dateType, $dates); } } $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'], $statusFormat), CRM_Utils_Date::customFormat($dates['end_date'], $statusFormat), CRM_Utils_Date::customFormat($dates['join_date'], $statusFormat), 'today', TRUE, $membershipTypeID, $memParams); $updateStatusId = CRM_Utils_Array::value('id', $status); } else { // if IPN/Pay-Later set status to: PENDING $updateStatusId = array_search('Pending', $allStatus); } if (!empty($membershipSource)) { $memParams['source'] = $membershipSource; } $memParams['is_test'] = $is_test; $memParams['is_pay_later'] = $isPayLater; } // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but // perhaps shouldn't be? if ($contributionRecurID) { $memParams['contribution_recur_id'] = $contributionRecurID; } //CRM-4555 //if we decided status here and want to skip status //calculation in create( ); then need to pass 'skipStatusCal'. if ($updateStatusId) { $memParams['status_id'] = $updateStatusId; $memParams['skipStatusCal'] = TRUE; } //since we are renewing, //make status override false. $memParams['is_override'] = FALSE; //CRM-4027, create log w/ individual contact. if ($modifiedID) { $ids['userId'] = $modifiedID; $memParams['is_for_organization'] = TRUE; } else { $ids['userId'] = $contactID; } //inherit campaign from contrib page. if (isset($campaignId)) { $memParams['campaign_id'] = $campaignId; } $memParams['custom'] = $customFieldsFormatted; $membership = self::create($memParams, $ids, FALSE, $activityType); // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072 $membership->find(TRUE); return array($membership, $renewalMode, $dates); }
function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE) { $contribution =& $objects['contribution']; $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id; $memberships =& $objects['membership']; if (is_numeric($memberships)) { $memberships = array($objects['membership']); } $participant =& $objects['participant']; $event =& $objects['event']; $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now); $recurContrib =& $objects['contributionRecur']; $values = array(); if (isset($input['is_email_receipt'])) { $values['is_email_receipt'] = $input['is_email_receipt']; } $source = NULL; if ($input['component'] == 'contribute') { if ($contribution->contribution_page_id) { CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values); $source = ts('Online Contribution') . ': ' . $values['title']; } elseif ($recurContrib && $recurContrib->id) { $contribution->contribution_page_id = NULL; $values['amount'] = $recurContrib->amount; $values['financial_type_id'] = $objects['contributionType']->id; $values['title'] = $source = ts('Offline Recurring Contribution'); $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $values['receipt_from_name'] = $domainValues[0]; $values['receipt_from_email'] = $domainValues[1]; } if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) { //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden. $values['is_email_receipt'] = $recurContrib->is_email_receipt; } $contribution->source = $source; if (CRM_Utils_Array::value('is_email_receipt', $values)) { $contribution->receipt_date = self::$_now; } if (!empty($memberships)) { $membershipsUpdate = array(); foreach ($memberships as $membershipTypeIdKey => $membership) { if ($membership) { $format = '%Y%m%d'; $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id); // CRM-8141 update the membership type with the value recorded in log when membership created/renewed // this picks up membership type changes during renewals $sql = "\nSELECT membership_type_id\nFROM civicrm_membership_log\nWHERE membership_id={$membership->id}\nORDER BY id DESC\nLIMIT 1;"; $dao = new CRM_Core_DAO(); $dao->query($sql); if ($dao->fetch()) { if (!empty($dao->membership_type_id)) { $membership->membership_type_id = $dao->membership_type_id; $membership->save(); } // else fall back to using current membership type } // else fall back to using current membership type $dao->free(); $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID); if ($currentMembership) { /* * Fixed FOR CRM-4433 * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status * when Contribution mode is notify and membership is for renewal ) */ CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday); // @todo - we should pass membership_type_id instead of null here but not // adding as not sure of testing $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, NULL, $num_terms); $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format); } else { $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms); } //get the status for membership. $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership); $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format)); //we might be renewing membership, //so make status override false. $formatedParams['is_override'] = FALSE; $membership->copyValues($formatedParams); $membership->save(); //updating the membership log $membershipLog = array(); $membershipLog = $formatedParams; $logStartDate = $formatedParams['start_date']; if (CRM_Utils_Array::value('log_start_date', $dates)) { $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format); $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate); } $membershipLog['start_date'] = $logStartDate; $membershipLog['membership_id'] = $membership->id; $membershipLog['modified_id'] = $membership->contact_id; $membershipLog['modified_date'] = date('Ymd'); $membershipLog['membership_type_id'] = $membership->membership_type_id; CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray); //update related Memberships. CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams); //update the membership type key of membership relatedObjects array //if it has changed after membership update if ($membershipTypeIdKey != $membership->membership_type_id) { $membershipsUpdate[$membership->membership_type_id] = $membership; $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership; unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]); unset($memberships[$membershipTypeIdKey]); } } } //update the memberships object with updated membershipTypeId data //if membershipTypeId has changed after membership update if (!empty($membershipsUpdate)) { $memberships = $memberships + $membershipsUpdate; } } } else { // event $eventParams = array('id' => $objects['event']->id); $values['event'] = array(); CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); //get location details $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event'); $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent'); list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $values['custom_pre_id'] = $custom_pre_id; $values['custom_post_id'] = $custom_post_ids; //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case //and cases involving status updation through ipn $values['totalAmount'] = $input['amount']; $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title']; if ($values['event']['is_email_confirm']) { $contribution->receipt_date = self::$_now; $values['is_email_receipt'] = 1; } if (!CRM_Utils_Array::value('skipComponentSync', $input)) { $participant->status_id = 1; } $participant->save(); } if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) { $input['net_amount'] = $input['amount'] - $input['fee_amount']; } // This complete transaction function is being overloaded to create new contributions too. // here we record if it is a new contribution. // @todo separate the 2 more appropriately. $isNewContribution = FALSE; if (empty($contribution->id)) { $isNewContribution = TRUE; if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) { $contribution->total_amount = $input['amount']; // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner) // so we have to handle net_amount in this (naughty) code. if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) { $contribution->fee_amount = $input['fee_amount']; } $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount; } if (!empty($input['campaign_id'])) { $contribution->campaign_id = $input['campaign_id']; } } $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1)); // @todo this section should call the api in order to have hooks called & // because all this 'messiness' setting variables could be avoided // by letting the api resolve pseudoconstants & copy set values and format dates. $contribution->contribution_status_id = $contributionStatuses['Completed']; $contribution->is_test = $input['is_test']; // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out. if (isset($input['net_amount'])) { $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0); } if (isset($input['net_amount'])) { $contribution->net_amount = $input['net_amount']; } $contribution->trxn_id = $input['trxn_id']; $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date); $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date); $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date); $contribution->cancel_date = 'null'; if (CRM_Utils_Array::value('check_number', $input)) { $contribution->check_number = $input['check_number']; } if (CRM_Utils_Array::value('payment_instrument_id', $input)) { $contribution->payment_instrument_id = $input['payment_instrument_id']; } if (!empty($contribution->id)) { $contributionId['id'] = $contribution->id; $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray); } $contribution->save(); //add line items for recurring payments if (!empty($contribution->contribution_recur_id)) { if ($isNewContribution) { $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution); } else { // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear $input['line_item'] = array(); } if (!empty($memberships) && $primaryContributionID != $contribution->id) { foreach ($memberships as $membership) { try { $membershipPayment = array('membership_id' => $membership->id, 'contribution_id' => $contribution->id); if (!civicrm_api3('membership_payment', 'getcount', $membershipPayment)) { civicrm_api3('membership_payment', 'create', $membershipPayment); } } catch (CiviCRM_API3_Exception $e) { echo $e->getMessage(); // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated } } } } //copy initial contribution custom fields for recurring contributions if ($recurContrib && $recurContrib->id) { $this->copyCustomValues($recurContrib->id, $contribution->id); } // next create the transaction record $paymentProcessor = $paymentProcessorId = ''; if (isset($objects['paymentProcessor'])) { if (is_array($objects['paymentProcessor'])) { $paymentProcessor = $objects['paymentProcessor']['payment_processor_type']; $paymentProcessorId = $objects['paymentProcessor']['id']; } else { $paymentProcessor = $objects['paymentProcessor']->payment_processor_type; $paymentProcessorId = $objects['paymentProcessor']->id; } } //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above // which raised the question as to whether this check preceded line 511 & if so whether something could be broken // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code // it would be good if someone added some comments or refactored this if ($contribution->id) { $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) { $input['payment_processor'] = $paymentProcessorId; } $input['contribution_status_id'] = array_search('Completed', $contributionStatuses); $input['total_amount'] = $input['amount']; $input['contribution'] = $contribution; $input['financial_type_id'] = $contribution->financial_type_id; if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) { $input['contribution_mode'] = 'participant'; $input['participant_id'] = $contribution->_relatedObjects['participant']->id; $input['skipLineItem'] = 1; } //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second // and subsequent payments. In this case the line items are created at $this->addRecurLineItems // and since the contribution is saved prior to this line there is always a contribution-id, // however there is never a prevContribution (which appears to mean original contribution not previous // contribution - or preUpdateContributionObject most accurately) // so, this is always called & only appears to succeed when prevContribution exists - which appears // to mean "are we updating an exisitng pending contribution" //I was able to make the unit test complete as fataling here doesn't prevent // the contribution being created - but activities would not be created or emails sent CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL); } self::updateRecurLinkedPledge($contribution); // create an activity record if ($input['component'] == 'contribute') { //CRM-4027 $targetContactID = NULL; if (CRM_Utils_Array::value('related_contact', $ids)) { $targetContactID = $contribution->contact_id; $contribution->contact_id = $ids['related_contact']; } CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID); // event } else { CRM_Activity_BAO_Activity::addActivity($participant); } CRM_Core_Error::debug_log_message("Contribution record updated successfully"); $transaction->commit(); // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) { self::sendMail($input, $ids, $objects, $values, $recur, FALSE); CRM_Core_Error::debug_log_message("Receipt sent"); } CRM_Core_Error::debug_log_message("Success: Database updated"); }
function preProcess() { parent::preProcess(); $reportDate = CRM_Utils_Date::customFormat(date('Y-m-d H:i')); $this->assign('reportTitle', "{$this->_orgName} - Call List <br /> {$reportDate}"); }
/** * Check if event is valid. * * @todo - combine this with CRM_Event_BAO_Event::validRegistrationRequest * (probably extract relevant values here & call that with them & handle bounces & redirects here -as * those belong in the form layer) * * @param string $redirect */ public function checkValidEvent($redirect = NULL) { // is the event active (enabled)? if (!$this->_values['event']['is_active']) { // form is inactive, die a fatal death CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).')); } // is online registration is enabled? if (!$this->_values['event']['is_online_registration']) { CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $redirect); } // is this an event template ? if (!empty($this->_values['event']['is_template'])) { CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $redirect); } $now = date('YmdHis'); $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])); if ($startDate && $startDate >= $now) { CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])))), $redirect); } $regEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date', $this->_values['event'])); $eventEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('event_end_date', $this->_values['event'])); if ($regEndDate && $regEndDate < $now || empty($regEndDate) && !empty($eventEndDate) && $eventEndDate < $now) { $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_end_date', $this->_values['event'])); if (empty($regEndDate)) { $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('event_end_date', $this->_values['event'])); } CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => $endDate)), $redirect); } }
/** * Get rows for the event browser * * @param int $mailing_id ID of the mailing * @param int $job_id optional ID of the job * @param int $offset Offset * @param int $rowCount Number of rows * @param array $sort sort array * @return array Result set * @access public * @static */ function &getRows($mailing_id, $job_id = null, $offset = null, $rowCount = null, $sort = null) { $dao =& new CRM_Core_Dao(); $queue = CRM_Mailing_Event_BAO_Queue::getTableName(); $mailing = CRM_Mailing_BAO_Mailing::getTableName(); $job = CRM_Mailing_BAO_Job::getTableName(); $contact = CRM_Contact_BAO_Contact::getTableName(); $email = CRM_Core_BAO_Email::getTableName(); $query = "\n SELECT {$contact}.display_name as display_name,\n {$contact}.id as contact_id,\n {$email}.email as email,\n {$job}.start_date as date\n FROM {$contact}\n INNER JOIN {$queue}\n ON {$queue}.contact_id = {$contact}.id\n INNER JOIN {$email}\n ON {$queue}.email_id = {$email}.id\n INNER JOIN {$job}\n ON {$queue}.job_id = {$job}.id\n INNER JOIN {$mailing}\n ON {$job}.mailing_id = {$mailing}.id\n WHERE {$mailing}.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer'); if (!empty($job_id)) { $query .= " AND {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer'); } $query .= " ORDER BY {$contact}.sort_name, {$job}.start_date "; if ($offset) { $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer'); } $dao->query($query); $results = array(); while ($dao->fetch()) { $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$dao->contact_id}"); $results[] = array('name' => "<a href=\"{$url}\">{$dao->display_name}</a>", 'email' => $dao->email, 'date' => CRM_Utils_Date::customFormat($dao->date)); } return $results; }