/**
  * @param $rows
  */
 function alterDisplay(&$rows)
 {
     // cache for id → is_deleted mapping
     $isDeleted = array();
     $newRows = array();
     foreach ($rows as $key => &$row) {
         if (!isset($isDeleted[$row['log_civicrm_entity_altered_contact_id']])) {
             $isDeleted[$row['log_civicrm_entity_altered_contact_id']] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $row['log_civicrm_entity_altered_contact_id'], 'is_deleted') !== '0';
         }
         if (!empty($row['log_civicrm_entity_altered_contact']) && !$isDeleted[$row['log_civicrm_entity_altered_contact_id']]) {
             $row['log_civicrm_entity_altered_contact_link'] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $row['log_civicrm_entity_altered_contact_id']);
             $row['log_civicrm_entity_altered_contact_hover'] = ts("Go to contact summary");
             $entity = $this->getEntityValue($row['log_civicrm_entity_id'], $row['log_civicrm_entity_log_type'], $row['log_civicrm_entity_log_date']);
             if ($entity) {
                 $row['log_civicrm_entity_altered_contact'] = $row['log_civicrm_entity_altered_contact'] . " [{$entity}]";
             }
         }
         $row['altered_by_contact_display_name_link'] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $row['log_civicrm_entity_log_user_id']);
         $row['altered_by_contact_display_name_hover'] = ts("Go to contact summary");
         if ($row['log_civicrm_entity_is_deleted'] and 'Update' == CRM_Utils_Array::value('log_civicrm_entity_log_action', $row)) {
             $row['log_civicrm_entity_log_action'] = ts('Delete (to trash)');
         }
         if ('Contact' == CRM_Utils_Array::value('log_type', $this->_logTables[$row['log_civicrm_entity_log_type']]) && CRM_Utils_Array::value('log_civicrm_entity_log_action', $row) == 'Insert') {
             $row['log_civicrm_entity_log_action'] = ts('Update');
         }
         if ($newAction = $this->getEntityAction($row['log_civicrm_entity_id'], $row['log_civicrm_entity_log_conn_id'], $row['log_civicrm_entity_log_type'], CRM_Utils_Array::value('log_civicrm_entity_log_action', $row))) {
             $row['log_civicrm_entity_log_action'] = $newAction;
         }
         $row['log_civicrm_entity_log_type'] = $this->getLogType($row['log_civicrm_entity_log_type']);
         $date = CRM_Utils_Date::isoToMysql($row['log_civicrm_entity_log_date']);
         if ('Update' == CRM_Utils_Array::value('log_civicrm_entity_log_action', $row)) {
             $q = "reset=1&log_conn_id={$row['log_civicrm_entity_log_conn_id']}&log_date=" . $date;
             if ($this->cid) {
                 $q .= '&cid=' . $this->cid;
             }
             $q .= !empty($row['log_civicrm_entity_altered_contact']) ? '&alteredName=' . $row['log_civicrm_entity_altered_contact'] : '';
             $q .= !empty($row['altered_by_contact_display_name']) ? '&alteredBy=' . $row['altered_by_contact_display_name'] : '';
             $q .= !empty($row['log_civicrm_entity_log_user_id']) ? '&alteredById=' . $row['log_civicrm_entity_log_user_id'] : '';
             $url1 = CRM_Report_Utils_Report::getNextUrl('logging/contact/detail', "{$q}&snippet=4&section=2&layout=overlay", FALSE, TRUE);
             $url2 = CRM_Report_Utils_Report::getNextUrl('logging/contact/detail', "{$q}&section=2", FALSE, TRUE);
             $row['log_civicrm_entity_log_action'] = "<a href='{$url1}' class='crm-summary-link'><div class='icon details-icon'></div></a>&nbsp;<a title='View details for this update' href='{$url2}'>" . ts('Update') . '</a>';
         }
         $key = $date . '_' . $row['log_civicrm_entity_log_type'] . '_' . $row['log_civicrm_entity_log_conn_id'] . '_' . $row['log_civicrm_entity_log_user_id'] . '_' . $row['log_civicrm_entity_altered_contact_id'];
         $newRows[$key] = $row;
         unset($row['log_civicrm_entity_log_user_id']);
         unset($row['log_civicrm_entity_log_conn_id']);
     }
     krsort($newRows);
     $rows = $newRows;
 }
Example #2
0
 /**
  * create() method (create and update modes)
  */
 function testCreateGet()
 {
     $permissionIndividual1Id = Contact::createIndividual();
     $permissionIndividual2Id = Contact::createIndividual();
     $stages = array_keys(CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, " AND grouping = 'Vacancy'"));
     $params = array('position' => 'Senior Support Specialist', 'location' => 'Headquaters', 'salary' => '$110-$130k/yr', 'description' => 'Answer phone calls and emails from irate customers.', 'benefits' => 'Have a place to park', 'requirements' => 'Pro-actively looks to build cross discipline experience and increase knowledge.', 'stages' => $stages, 'application_profile' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'application_profile', 'id', 'name'), 'evaluation_profile' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', 'evaluation_profile', 'id', 'name'), 'status_id' => '4', 'start_date' => '20140425151100', 'end_date' => '20140426231100', 'permission' => array('manage Applicants', 'administer Vacancy'), 'permission_contact_id' => array($permissionIndividual1Id, $permissionIndividual2Id));
     $vacancy = CRM_HRRecruitment_BAO_HRVacancy::create($params);
     $getValues = array();
     $getParams = array('id' => $vacancy->id);
     CRM_HRRecruitment_BAO_HRVacancy::retrieve($getParams, $getValues);
     //stage array index always starts with 1 so in order to make changes in
     //$getValues['stages'] in order to just match the value
     $getValues['stages'] = array_values($getValues['stages']);
     $getValues['permission'] = array_values($getValues['permission']);
     $getValues['permission_contact_id'] = array_values($getValues['permission_contact_id']);
     //process date back to mysql format
     $getValues['start_date'] = CRM_Utils_Date::isoToMysql($getValues['start_date']);
     $getValues['end_date'] = CRM_Utils_Date::isoToMysql($getValues['end_date']);
     foreach ($params as $column => $value) {
         $this->assertEquals($params[$column], $getValues[$column], "Check for Job {$column}.");
     }
 }
 /**
  * Process the PDf and email with activity and attachment.
  * on click of Print Invoices
  *
  * @param array $contribIDs
  *   Contribution Id.
  * @param array $params
  *   Associated array of submitted values.
  * @param array $contactIds
  *   Contact Id.
  * @param CRM_Core_Form $form
  *   Form object.
  */
 public static function printPDF($contribIDs, &$params, $contactIds, &$form)
 {
     // get all the details needed to generate a invoice
     $messageInvoice = array();
     $invoiceTemplate = CRM_Core_Smarty::singleton();
     $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
     // gives the status id when contribution status is 'Refunded'
     $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
     // getting data from admin page
     $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     foreach ($invoiceElements['details'] as $contribID => $detail) {
         $input = $ids = $objects = array();
         if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
             continue;
         }
         $input['component'] = $detail['component'];
         $ids['contact'] = $detail['contact'];
         $ids['contribution'] = $contribID;
         $ids['contributionRecur'] = NULL;
         $ids['contributionPage'] = NULL;
         $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
         $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
         $ids['event'] = CRM_Utils_Array::value('event', $detail);
         if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
             CRM_Core_Error::fatal();
         }
         $contribution =& $objects['contribution'];
         $input['amount'] = $contribution->total_amount;
         $input['invoice_id'] = $contribution->invoice_id;
         $input['receive_date'] = $contribution->receive_date;
         $input['contribution_status_id'] = $contribution->contribution_status_id;
         $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
         $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
         $addressParams = array('contact_id' => $contribution->contact_id);
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
         // to get billing address if present
         $billingAddress = array();
         foreach ($addressDetails as $key => $address) {
             if (isset($address['is_billing']) && $address['is_billing'] == 1 && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
                 $billingAddress[$address['contact_id']] = $address;
                 break;
             } elseif ($address['is_billing'] == 0 && $address['is_primary'] == 1 || isset($address['is_billing']) && $address['is_billing'] == 1 && $address['contact_id'] == $contribution->contact_id) {
                 $billingAddress[$address['contact_id']] = $address;
             }
         }
         if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
             $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
         } else {
             $stateProvinceAbbreviation = '';
         }
         if ($contribution->contribution_status_id == $refundedStatusId) {
             $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
         }
         $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
         //to obtain due date for PDF invoice
         $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
         $invoiceDate = date("F j, Y");
         $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
         if ($input['component'] == 'contribute') {
             $eid = $contribID;
             $etable = 'contribution';
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
         } else {
             $eid = $contribution->_relatedObjects['participant']->id;
             $etable = 'participant';
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable);
         }
         //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
         $amountDue = $input['amount'] - $input['amount'];
         // retreiving the subtotal and sum of same tax_rate
         $dataArray = array();
         $subTotal = 0;
         foreach ($lineItem as $entity_id => $taxRate) {
             if (isset($dataArray[(string) $taxRate['tax_rate']])) {
                 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
             } else {
                 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
             }
             $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
         }
         // to email the invoice
         $mailDetails = array();
         $values = array();
         if ($contribution->_component == 'event') {
             $daoName = 'CRM_Event_DAO_Event';
             $pageId = $contribution->_relatedObjects['event']->id;
             $mailElements = array('title', 'confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm');
             CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
             $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
             $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
         } elseif ($contribution->_component == 'contribute') {
             $daoName = 'CRM_Contribute_DAO_ContributionPage';
             $pageId = $contribution->contribution_page_id;
             $mailElements = array('title', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt');
             CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
             $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
             $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
         }
         $source = $contribution->source;
         $config = CRM_Core_Config::singleton();
         if (!isset($params['forPage'])) {
             $config->doNotAttachPDFReceipt = 1;
         }
         // get organization address
         $domain = CRM_Core_BAO_Domain::getDomain();
         $locParams = array('contact_id' => $domain->id);
         $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
         if (isset($locationDefaults['address'][1]['state_province_id'])) {
             $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
         } else {
             $stateProvinceAbbreviationDomain = '';
         }
         if (isset($locationDefaults['address'][1]['country_id'])) {
             $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
         } else {
             $countryDomain = '';
         }
         // parameters to be assign for template
         $tplParams = array('title' => $title, 'component' => $input['component'], 'id' => $contribution->id, 'source' => $source, 'invoice_id' => $invoiceId, 'resourceBase' => $config->userFrameworkResourceURL, 'defaultCurrency' => $config->defaultCurrency, 'amount' => $contribution->total_amount, 'amountDue' => $amountDue, 'invoice_date' => $invoiceDate, 'dueDate' => $dueDate, 'notes' => CRM_Utils_Array::value('notes', $prefixValue), 'display_name' => $contribution->_relatedObjects['contact']->display_name, 'lineItem' => $lineItem, 'dataArray' => $dataArray, 'refundedStatusId' => $refundedStatusId, 'contribution_status_id' => $contribution->contribution_status_id, 'subTotal' => $subTotal, 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'stateProvinceAbbreviation' => $stateProvinceAbbreviation, 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'is_pay_later' => $contribution->is_pay_later, 'organization_name' => $contribution->_relatedObjects['contact']->organization_name, 'domain_organization' => $domain->name, 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_state' => $stateProvinceAbbreviationDomain, 'domain_country' => $countryDomain, 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])), 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])));
         if (isset($creditNoteId)) {
             $tplParams['creditnote_id'] = $creditNoteId;
         }
         $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_invoice_receipt', 'contactId' => $contribution->contact_id, 'tplParams' => $tplParams, 'PDFFilename' => 'Invoice.pdf');
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         //CRM-16319 - we dont store in userID in case the user is doing multiple
         //transactions etc
         if (empty($contactID)) {
             $contactID = $session->get('transaction.userID');
         }
         $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
         $emails = array();
         $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name');
         foreach ($contactEmails as $emailId => $item) {
             $email = $item['email'];
             if ($email) {
                 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
             }
         }
         $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
         // from email address
         if (isset($params['from_email_address'])) {
             $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
         }
         // condition to check for download PDF Invoice or email Invoice
         if ($invoiceElements['createPdf']) {
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if (isset($params['forPage'])) {
                 return $html;
             } else {
                 $mail = array('subject' => $subject, 'body' => $message, 'html' => $html);
                 if ($mail['html']) {
                     $messageInvoice[] = $mail['html'];
                 } else {
                     $messageInvoice[] = nl2br($mail['body']);
                 }
             }
         } elseif ($contribution->_component == 'contribute') {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
             $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
             $sendTemplateParams['from'] = $fromEmailAddress;
             $sendTemplateParams['toEmail'] = $email;
             $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
             $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contribution->contact_id, $fileName, $params);
         } elseif ($contribution->_component == 'event') {
             $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
             $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
             $sendTemplateParams['from'] = $fromEmailAddress;
             $sendTemplateParams['toEmail'] = $email;
             $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
             $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
             list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contribution->contact_id, $fileName, $params);
         }
         CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
         if ($contribution->contribution_status_id == $refundedStatusId) {
             CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
         }
         $invoiceTemplate->clearTemplateVars();
     }
     if ($invoiceElements['createPdf']) {
         if (isset($params['forPage'])) {
             return $html;
         } else {
             CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array('margin_top' => 10, 'margin_left' => 65, 'metric' => 'px'));
             // functions call for adding activity with attachment
             $fileName = self::putFile($html);
             self::addActivities($subject, $contactIds, $fileName, $params);
             CRM_Utils_System::civiExit();
         }
     } else {
         if ($invoiceElements['suppressedEmails']) {
             $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails']));
             $msgTitle = ts('Email Error');
             $msgType = 'error';
         } else {
             $status = ts('Your mail has been sent.');
             $msgTitle = ts('Sent');
             $msgType = 'success';
         }
         CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
     }
 }
Example #4
0
 /**
  * @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");
 }
Example #6
0
 /**
  * Update membership status to deceased.
  * function return the status message for updated membership.
  *
  * @param array $deceasedParams
  *   having contact id and deceased value.
  *
  * @return null|string
  *   $updateMembershipMsg string  status message for updated membership.
  */
 public function updateMembershipStatus($deceasedParams)
 {
     $updateMembershipMsg = NULL;
     $contactId = CRM_Utils_Array::value('contact_id', $deceasedParams);
     $deceasedDate = CRM_Utils_Array::value('deceased_date', $deceasedParams);
     // process to set membership status to deceased for both active/inactive membership
     if ($contactId && $this->_contactType == 'Individual' && !empty($deceasedParams['is_deceased'])) {
         $session = CRM_Core_Session::singleton();
         $userId = $session->get('userID');
         if (!$userId) {
             $userId = $contactId;
         }
         // get deceased status id
         $allStatus = CRM_Member_PseudoConstant::membershipStatus();
         $deceasedStatusId = array_search('Deceased', $allStatus);
         if (!$deceasedStatusId) {
             return $updateMembershipMsg;
         }
         $today = time();
         if ($deceasedDate && strtotime($deceasedDate) > $today) {
             return $updateMembershipMsg;
         }
         // get non deceased membership
         $dao = new CRM_Member_DAO_Membership();
         $dao->contact_id = $contactId;
         $dao->whereAdd("status_id != {$deceasedStatusId}");
         $dao->find();
         $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
         $allStatus = CRM_Member_PseudoConstant::membershipStatus();
         $memCount = 0;
         while ($dao->fetch()) {
             // update status to deceased (for both active/inactive membership )
             CRM_Core_DAO::setFieldValue('CRM_Member_DAO_Membership', $dao->id, 'status_id', $deceasedStatusId);
             // add membership log
             $membershipLog = array('membership_id' => $dao->id, 'status_id' => $deceasedStatusId, 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date), 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date), 'modified_id' => $userId, 'modified_date' => date('Ymd'), 'membership_type_id' => $dao->membership_type_id, 'max_related' => $dao->max_related);
             CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
             //create activity when membership status is changed
             $activityParam = array('subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}", 'source_contact_id' => $userId, 'target_contact_id' => $dao->contact_id, 'source_record_id' => $dao->id, 'activity_type_id' => array_search('Change Membership Status', $activityTypes), 'status_id' => 2, 'version' => 3, 'priority_id' => 2, 'activity_date_time' => date('Y-m-d H:i:s'), 'is_auto' => 0, 'is_current_revision' => 1, 'is_deleted' => 0);
             $activityResult = civicrm_api('activity', 'create', $activityParam);
             $memCount++;
         }
         // set status msg
         if ($memCount) {
             $updateMembershipMsg = ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.", array(1 => $memCount));
         }
     }
     return $updateMembershipMsg;
 }
Example #7
0
 function recur(&$input, &$ids, &$objects, $first)
 {
     if (!isset($input['txnType'])) {
         CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
         echo "Failure: Invalid parameters<p>";
         return false;
     }
     if ($input['txnType'] == 'subscr_payment' && $input['paymentStatus'] != 'Completed') {
         CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
         echo "Failure: Invalid parameters<p>";
         return false;
     }
     $recur =& $objects['contributionRecur'];
     // make sure the invoice ids match
     // make sure the invoice is valid and matches what we have in the contribution record
     if ($recur->invoice_id != $input['invoice']) {
         CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
         echo "Failure: Invoice values dont match between database and IPN request<p>";
         return false;
     }
     $now = date('YmdHis');
     // fix dates that already exist
     $dates = array('create', 'start', 'end', 'cancel', 'modified');
     foreach ($dates as $date) {
         $name = "{$date}_date";
         if ($recur->{$name}) {
             $recur->{$name} = CRM_Utils_Date::isoToMysql($recur->{$name});
         }
     }
     $sendNotification = false;
     $subscriptionPaymentStatus = null;
     require_once 'CRM/Core/Payment.php';
     //set transaction type
     $txnType = $_POST['txn_type'];
     switch ($txnType) {
         case 'subscr_signup':
             $recur->create_date = $now;
             //some times subscr_signup response come after the
             //subscr_payment and set to pending mode.
             $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $recur->id, 'contribution_status_id');
             if ($statusID != 5) {
                 $recur->contribution_status_id = 2;
             }
             $recur->processor_id = $_POST['subscr_id'];
             $recur->trxn_id = $recur->processor_id;
             $sendNotification = true;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
             break;
         case 'subscr_eot':
             $recur->contribution_status_id = 1;
             $recur->end_date = $now;
             $sendNotification = true;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
             break;
         case 'subscr_cancel':
             $recur->contribution_status_id = 3;
             $recur->cancel_date = $now;
             break;
         case 'subscr_failed':
             $recur->contribution_status_id = 4;
             $recur->cancel_date = $now;
             break;
         case 'subscr_modify':
             CRM_Core_Error::debug_log_message("We do not handle modifications to subscriptions right now");
             echo "Failure: We do not handle modifications to subscriptions right now<p>";
             return false;
         case 'subscr_payment':
             if ($first) {
                 $recur->start_date = $now;
             } else {
                 $recur->modified_date = $now;
             }
             // make sure the contribution status is not done
             // since order of ipn's is unknown
             if ($recur->contribution_status_id != 1) {
                 $recur->contribution_status_id = 5;
             }
             break;
     }
     $recur->save();
     if ($sendNotification) {
         //send recurring Notification email for user
         require_once 'CRM/Contribute/BAO/ContributionPage.php';
         CRM_Contribute_BAO_ContributionPage::recurringNofify($subscriptionPaymentStatus, $ids['contact'], $ids['contributionPage'], $recur);
     }
     if ($txnType != 'subscr_payment') {
         return;
     }
     if (!$first) {
         // create a contribution and then get it processed
         $contribution =& new CRM_Contribute_DAO_Contribution();
         $contribution->contact_id = $ids['contact'];
         $contribution->contribution_type_id = $objects['contributionType']->id;
         $contribution->contribution_page_id = $ids['contributionPage'];
         $contribution->contribution_recur_id = $ids['contributionRecur'];
         $contribution->receive_date = $now;
         $contribution->currency = $objects['contribution']->currency;
         $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
         $contribution->amount_level = $objects['contribution']->amount_level;
         $objects['contribution'] =& $contribution;
     }
     $this->single($input, $ids, $objects, true, $first);
 }
Example #8
0
 /**
  * Send mail and create activity
  * when participant status changed.
  *
  * @param int $participantId
  *   Participant id.
  * @param array $participantValues
  *   Participant detail values. status id for participants.
  * @param array $eventDetails
  *   Required event details.
  * @param array $contactDetails
  *   Required contact details.
  * @param array $domainValues
  *   Required domain values.
  * @param string $mailType
  *   (eg 'approval', 'confirm', 'expired' ).
  *
  * @return bool
  */
 public static function sendTransitionParticipantMail($participantId, $participantValues, $eventDetails, $contactDetails, &$domainValues, $mailType)
 {
     //send emails.
     $mailSent = FALSE;
     //don't send confirmation mail to additional
     //since only primary able to confirm registration.
     if (!empty($participantValues['registered_by_id']) && $mailType == 'Confirm') {
         return $mailSent;
     }
     $toEmail = CRM_Utils_Array::value('email', $contactDetails);
     if ($toEmail) {
         $contactId = $participantValues['contact_id'];
         $participantName = $contactDetails['display_name'];
         //calculate the checksum value.
         $checksumValue = NULL;
         if ($mailType == 'Confirm' && !$participantValues['registered_by_id']) {
             $checksumLife = 'inf';
             $endDate = CRM_Utils_Array::value('end_date', $eventDetails);
             if ($endDate) {
                 $checksumLife = (CRM_Utils_Date::unixTime($endDate) - time()) / (60 * 60);
             }
             $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactId, NULL, $checksumLife);
         }
         //take a receipt from as event else domain.
         $receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
         if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
             $receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
         }
         list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'participant_' . strtolower($mailType), 'contactId' => $contactId, 'tplParams' => array('contact' => $contactDetails, 'domain' => $domainValues, 'participant' => $participantValues, 'event' => $eventDetails, 'paidEvent' => CRM_Utils_Array::value('is_monetary', $eventDetails), 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $eventDetails), 'isAdditional' => $participantValues['registered_by_id'], 'isExpired' => $mailType == 'Expired', 'isConfirm' => $mailType == 'Confirm', 'checksumValue' => $checksumValue), 'from' => $receiptFrom, 'toName' => $participantName, 'toEmail' => $toEmail, 'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails), 'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails)));
         // 3. create activity record.
         if ($mailSent) {
             $now = date('YmdHis');
             $activityType = 'Event Registration';
             $activityParams = array('subject' => $subject, 'source_contact_id' => $contactId, 'source_record_id' => $participantId, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($now), 'due_date_time' => CRM_Utils_Date::isoToMysql($participantValues['register_date']), 'is_test' => $participantValues['is_test'], 'status_id' => 2);
             if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
                 CRM_Core_Error::fatal('Failed creating Activity for expiration mail');
             }
         }
     }
     return $mailSent;
 }
 /**
  * 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;
 }
Example #10
0
 /**
  * @param $entityObj
  * @param $trxnObj
  * @param $activityType
  * @param $component
  * @param int $contributionId
  *
  * @throws CRM_Core_Exception
  */
 public static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId)
 {
     if ($component == 'event') {
         $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
         $paymentAmount = CRM_Utils_Money::format($trxnObj->total_amount, $trxnObj->currency);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Event', $entityObj->event_id, 'title');
         $subject = "{$paymentAmount} - Offline {$activityType} for {$eventTitle}";
         $targetCid = $entityObj->contact_id;
         // source record id would be the contribution id
         $srcRecId = $contributionId;
     }
     // activity params
     $activityParams = array('source_contact_id' => $targetCid, 'source_record_id' => $srcRecId, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'subject' => $subject, 'activity_date_time' => $date, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'), 'skipRecentView' => TRUE);
     // create activity with target contacts
     $session = CRM_Core_Session::singleton();
     $id = $session->get('userID');
     if ($id) {
         $activityParams['source_contact_id'] = $id;
         $activityParams['target_contact_id'][] = $targetCid;
     }
     CRM_Activity_BAO_Activity::create($activityParams);
 }
 function completeRecur($input, $ids, $objects)
 {
     if ($ids['contributionRecur']) {
         $recur =& $objects['contributionRecur'];
         $contributionCount = CRM_Core_DAO::singleValueQuery("\nSELECT count(*)\nFROM   civicrm_contribution\nWHERE  contribution_recur_id = {$ids['contributionRecur']}\n");
         $autoRenewMembership = FALSE;
         if ($recur->id && isset($ids['membership']) && $ids['membership']) {
             $autoRenewMembership = TRUE;
         }
         if ($recur->installments && $contributionCount >= $recur->installments) {
             $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
             $recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
             $recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
             $recur->cancel_date = CRM_Utils_Date::isoToMysql($recur->cancel_date);
             $recur->end_date = date('YmdHis');
             $recur->modified_date = date('YmdHis');
             $recur->contribution_status_id = array_search('Completed', $contributionStatus);
             $recur->trnx_id = $dataRoot['google-order-number']['VALUE'];
             $recur->save();
             //send recurring Notification email for user
             CRM_Contribute_BAO_ContributionPage::recurringNotify(CRM_Core_Payment::RECURRING_PAYMENT_END, $ids['contact'], $ids['contributionPage'], $recur, $autoRenewMembership);
         } elseif ($contributionCount == 1) {
             CRM_Contribute_BAO_ContributionPage::recurringNotify(CRM_Core_Payment::RECURRING_PAYMENT_START, $ids['contact'], $ids['contributionPage'], $recur, $autoRenewMembership);
         }
     }
 }
Example #12
0
 /**
  * Add the financial items and financial trxn.
  *
  * @param object $lineItem
  *   Line item object.
  * @param object $contribution
  *   Contribution object.
  * @param bool $taxTrxnID
  *
  * @return void
  */
 public static function add($lineItem, $contribution, $taxTrxnID = FALSE, $trxnId = NULL)
 {
     $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
     $itemStatus = NULL;
     if ($contribution->contribution_status_id == array_search('Completed', $contributionStatuses) || $contribution->contribution_status_id == array_search('Pending refund', $contributionStatuses)) {
         $itemStatus = array_search('Paid', $financialItemStatus);
     } elseif ($contribution->contribution_status_id == array_search('Pending', $contributionStatuses) || $contribution->contribution_status_id == array_search('In Progress', $contributionStatuses)) {
         $itemStatus = array_search('Unpaid', $financialItemStatus);
     } elseif ($contribution->contribution_status_id == array_search('Partially paid', $contributionStatuses)) {
         $itemStatus = array_search('Partially paid', $financialItemStatus);
     }
     $params = array('transaction_date' => CRM_Utils_Date::isoToMysql($contribution->receive_date), 'contact_id' => $contribution->contact_id, 'amount' => $lineItem->line_total, 'currency' => $contribution->currency, 'entity_table' => 'civicrm_line_item', 'entity_id' => $lineItem->id, 'description' => ($lineItem->qty != 1 ? $lineItem->qty . ' of ' : '') . ' ' . $lineItem->label, 'status_id' => $itemStatus);
     if ($taxTrxnID) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
         $params['amount'] = $lineItem->tax_amount;
         $params['description'] = $taxTerm;
         $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Sales Tax Account is' "));
     } else {
         $accountRel = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Income Account is' "));
     }
     if ($lineItem->financial_type_id) {
         $searchParams = array('entity_table' => 'civicrm_financial_type', 'entity_id' => $lineItem->financial_type_id, 'account_relationship' => $accountRel);
         $result = array();
         CRM_Financial_BAO_FinancialTypeAccount::retrieve($searchParams, $result);
         $params['financial_account_id'] = CRM_Utils_Array::value('financial_account_id', $result);
     }
     if (empty($trxnId)) {
         $trxn = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($contribution->id, 'ASC', TRUE);
         $trxnId['id'] = $trxn['financialTrxnId'];
     }
     return self::create($params, NULL, $trxnId);
 }
Example #13
0
 /**
  * Send the mailing.
  *
  * @param object $mailer
  *   A Mail object to send the messages.
  *
  * @param array $testParams
  *
  * @return void
  */
 public function deliver(&$mailer, $testParams = NULL)
 {
     $mailing = new CRM_Mailing_BAO_Mailing();
     $mailing->id = $this->mailing_id;
     $mailing->find(TRUE);
     $mailing->free();
     $eq = new CRM_Mailing_Event_BAO_Queue();
     $eqTable = CRM_Mailing_Event_BAO_Queue::getTableName();
     $emailTable = CRM_Core_BAO_Email::getTableName();
     $phoneTable = CRM_Core_DAO_Phone::getTableName();
     $contactTable = CRM_Contact_BAO_Contact::getTableName();
     $edTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
     $ebTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
     $query = "  SELECT      {$eqTable}.id,\n                                {$emailTable}.email as email,\n                                {$eqTable}.contact_id,\n                                {$eqTable}.hash,\n                                NULL as phone\n                    FROM        {$eqTable}\n                    INNER JOIN  {$emailTable}\n                            ON  {$eqTable}.email_id = {$emailTable}.id\n                    INNER JOIN  {$contactTable}\n                            ON  {$contactTable}.id = {$emailTable}.contact_id\n                    LEFT JOIN   {$edTable}\n                            ON  {$eqTable}.id = {$edTable}.event_queue_id\n                    LEFT JOIN   {$ebTable}\n                            ON  {$eqTable}.id = {$ebTable}.event_queue_id\n                    WHERE       {$eqTable}.job_id = " . $this->id . "\n                        AND     {$edTable}.id IS null\n                        AND     {$ebTable}.id IS null\n                        AND    {$contactTable}.is_opt_out = 0";
     if ($mailing->sms_provider_id) {
         $query = "\n                    SELECT      {$eqTable}.id,\n                                {$phoneTable}.phone as phone,\n                                {$eqTable}.contact_id,\n                                {$eqTable}.hash,\n                                NULL as email\n                    FROM        {$eqTable}\n                    INNER JOIN  {$phoneTable}\n                            ON  {$eqTable}.phone_id = {$phoneTable}.id\n                    INNER JOIN  {$contactTable}\n                            ON  {$contactTable}.id = {$phoneTable}.contact_id\n                    LEFT JOIN   {$edTable}\n                            ON  {$eqTable}.id = {$edTable}.event_queue_id\n                    LEFT JOIN   {$ebTable}\n                            ON  {$eqTable}.id = {$ebTable}.event_queue_id\n                    WHERE       {$eqTable}.job_id = " . $this->id . "\n                        AND     {$edTable}.id IS null\n                        AND     {$ebTable}.id IS null\n                        AND    ( {$contactTable}.is_opt_out = 0\n                        OR       {$contactTable}.do_not_sms = 0 )";
     }
     $eq->query($query);
     $config = NULL;
     if ($config == NULL) {
         $config = CRM_Core_Config::singleton();
     }
     $job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
     $fields = array();
     if (!empty($testParams)) {
         $mailing->subject = ts('[CiviMail Draft]') . ' ' . $mailing->subject;
     }
     CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
     // get and format attachments
     $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
     if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
         CRM_Core_Smarty::registerStringResource();
     }
     // CRM-12376
     // This handles the edge case scenario where all the mails
     // have been delivered in prior jobs
     $isDelivered = TRUE;
     // make sure that there's no more than $config->mailerBatchLimit mails processed in a run
     while ($eq->fetch()) {
         // if ( ( $mailsProcessed % 100 ) == 0 ) {
         // CRM_Utils_System::xMemory( "$mailsProcessed: " );
         // }
         if ($config->mailerBatchLimit > 0 && self::$mailsProcessed >= $config->mailerBatchLimit) {
             if (!empty($fields)) {
                 $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
             }
             $eq->free();
             return FALSE;
         }
         self::$mailsProcessed++;
         $fields[] = array('id' => $eq->id, 'hash' => $eq->hash, 'contact_id' => $eq->contact_id, 'email' => $eq->email, 'phone' => $eq->phone);
         if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
             $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
             if (!$isDelivered) {
                 $eq->free();
                 return $isDelivered;
             }
             $fields = array();
         }
     }
     $eq->free();
     if (!empty($fields)) {
         $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
     }
     return $isDelivered;
 }
Example #14
0
 function getEntityValue($id, $entity, $logDate)
 {
     if (CRM_Utils_Array::value('bracket_info', $this->_logTables[$entity])) {
         if (CRM_Utils_Array::value('entity_column', $this->_logTables[$entity]['bracket_info'])) {
             $logTable = CRM_Utils_Array::value('table_name', $this->_logTables[$entity]) ? $this->_logTables[$entity]['table_name'] : $entity;
             $sql = "\nSELECT {$this->_logTables[$entity]['bracket_info']['entity_column']}\n  FROM `{$this->loggingDB}`.{$logTable}\n WHERE  log_date <= %1 AND id = %2 ORDER BY log_date DESC LIMIT 1";
             $entityID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array(CRM_Utils_Date::isoToMysql($logDate), 'Timestamp'), 2 => array($id, 'Integer')));
         } else {
             $entityID = $id;
         }
         // since case_type_id is a varchar field with separator
         if ($entity == 'log_civicrm_case') {
             $entityID = explode(CRM_Case_BAO_Case::VALUE_SEPARATOR, $entityID);
             $entityID = CRM_Utils_Array::value(1, $entityID);
         }
         if ($entityID && $logDate && array_key_exists('table', $this->_logTables[$entity]['bracket_info'])) {
             $sql = "\nSELECT {$this->_logTables[$entity]['bracket_info']['column']}\nFROM  `{$this->loggingDB}`.{$this->_logTables[$entity]['bracket_info']['table']}\nWHERE  log_date <= %1 AND id = %2 ORDER BY log_date DESC LIMIT 1";
             return CRM_Core_DAO::singleValueQuery($sql, array(1 => array(CRM_Utils_Date::isoToMysql($logDate), 'Timestamp'), 2 => array($entityID, 'Integer')));
         } else {
             if (array_key_exists('options', $this->_logTables[$entity]['bracket_info']) && $entityID) {
                 return CRM_Utils_Array::value($entityID, $this->_logTables[$entity]['bracket_info']['options']);
             }
         }
     }
     return NULL;
 }
Example #15
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     // get all the details needed to generate a receipt
     $contribIDs = implode(',', $this->_contributionIds);
     $details = CRM_Contribute_Form_Task_Status::getDetails($contribIDs);
     $baseIPN = new CRM_Core_Payment_BaseIPN();
     $message = array();
     $template = CRM_Core_Smarty::singleton();
     $params = $this->controller->exportValues($this->_name);
     $createPdf = FALSE;
     if ($params['output'] == "pdf_receipt") {
         $createPdf = TRUE;
     }
     $excludeContactIds = array();
     if (!$createPdf) {
         $returnProperties = array('email' => 1, 'do_not_email' => 1, 'is_deceased' => 1, 'on_hold' => 1);
         list($contactDetails) = CRM_Utils_Token::getTokenDetails($this->_contactIds, $returnProperties, FALSE, FALSE);
         $suppressedEmails = 0;
         foreach ($contactDetails as $id => $values) {
             if (empty($values['email']) || !empty($values['do_not_email']) || CRM_Utils_Array::value('is_deceased', $values) || !empty($values['on_hold'])) {
                 $suppressedEmails++;
                 $excludeContactIds[] = $values['contact_id'];
             }
         }
     }
     foreach ($details as $contribID => $detail) {
         $input = $ids = $objects = array();
         if (in_array($detail['contact'], $excludeContactIds)) {
             continue;
         }
         $input['component'] = $detail['component'];
         $ids['contact'] = $detail['contact'];
         $ids['contribution'] = $contribID;
         $ids['contributionRecur'] = NULL;
         $ids['contributionPage'] = NULL;
         $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
         $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
         $ids['event'] = CRM_Utils_Array::value('event', $detail);
         if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
             CRM_Core_Error::fatal();
         }
         $contribution =& $objects['contribution'];
         // CRM_Core_Error::debug('o',$objects);
         // set some fake input values so we can reuse IPN code
         $input['amount'] = $contribution->total_amount;
         $input['is_test'] = $contribution->is_test;
         $input['fee_amount'] = $contribution->fee_amount;
         $input['net_amount'] = $contribution->net_amount;
         $input['trxn_id'] = $contribution->trxn_id;
         $input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : NULL;
         // CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date
         $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
         // CRM_Core_Error::debug('input',$input);
         $values = array();
         $mail = $baseIPN->sendMail($input, $ids, $objects, $values, FALSE, $createPdf);
         if ($mail['html']) {
             $message[] = $mail['html'];
         } else {
             $message[] = nl2br($mail['body']);
         }
         // reset template values before processing next transactions
         $template->clearTemplateVars();
     }
     if ($createPdf) {
         CRM_Utils_PDF_Utils::html2pdf($message, 'civicrmContributionReceipt.pdf', FALSE, $params['pdf_format_id']);
         CRM_Utils_System::civiExit();
     } else {
         if ($suppressedEmails) {
             $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $suppressedEmails));
             $msgTitle = ts('Email Error');
             $msgType = 'error';
         } else {
             $status = ts('Your mail has been sent.');
             $msgTitle = ts('Sent');
             $msgType = 'success';
         }
         CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
     }
 }
Example #16
0
 /**
  * Updates contacts affected by the option value passed.
  *
  * @param int $optionValueId
  *   The option value id.
  * @param int $action
  *   The action describing whether prefix/suffix was UPDATED or DELETED.
  *
  * @return bool
  */
 public static function updateRecords(&$optionValueId, $action)
 {
     //finding group name
     $optionValue = new CRM_Core_DAO_OptionValue();
     $optionValue->id = $optionValueId;
     $optionValue->find(TRUE);
     $optionGroup = new CRM_Core_DAO_OptionGroup();
     $optionGroup->id = $optionValue->option_group_id;
     $optionGroup->find(TRUE);
     // group name
     $gName = $optionGroup->name;
     // value
     $value = $optionValue->value;
     // get the proper group name & affected field name
     // todo: this may no longer be needed for individuals - check inputs
     $individuals = array('gender' => 'gender_id', 'individual_prefix' => 'prefix_id', 'individual_suffix' => 'suffix_id', 'communication_style' => 'communication_style_id');
     $contributions = array('payment_instrument' => 'payment_instrument_id');
     $activities = array('activity_type' => 'activity_type_id');
     $participant = array('participant_role' => 'role_id');
     $eventType = array('event_type' => 'event_type_id');
     $aclRole = array('acl_role' => 'acl_role_id');
     $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
     $fieldName = '';
     foreach ($all as $name => $id) {
         if ($gName == $name) {
             $fieldName = $id;
         }
     }
     if ($fieldName == '') {
         return TRUE;
     }
     if (array_key_exists($gName, $individuals)) {
         $contactDAO = new CRM_Contact_DAO_Contact();
         $contactDAO->{$fieldName} = $value;
         $contactDAO->find();
         while ($contactDAO->fetch()) {
             if ($action == CRM_Core_Action::DELETE) {
                 $contact = new CRM_Contact_DAO_Contact();
                 $contact->id = $contactDAO->id;
                 $contact->find(TRUE);
                 // make sure dates doesn't get reset
                 $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
                 $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
                 $contact->{$fieldName} = 'NULL';
                 $contact->save();
             }
         }
         return TRUE;
     }
     if (array_key_exists($gName, $contributions)) {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->{$fieldName} = $value;
         $contribution->find();
         while ($contribution->fetch()) {
             if ($action == CRM_Core_Action::DELETE) {
                 $contribution->{$fieldName} = 'NULL';
                 $contribution->save();
             }
         }
         return TRUE;
     }
     if (array_key_exists($gName, $activities)) {
         $activity = new CRM_Activity_DAO_Activity();
         $activity->{$fieldName} = $value;
         $activity->find();
         while ($activity->fetch()) {
             $activity->delete();
         }
         return TRUE;
     }
     //delete participant role, type and event type option value
     if (array_key_exists($gName, $participant)) {
         $participantValue = new CRM_Event_DAO_Participant();
         $participantValue->{$fieldName} = $value;
         if ($participantValue->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
     //delete event type option value
     if (array_key_exists($gName, $eventType)) {
         $event = new CRM_Event_DAO_Event();
         $event->{$fieldName} = $value;
         if ($event->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
     //delete acl_role option value
     if (array_key_exists($gName, $aclRole)) {
         $entityRole = new CRM_ACL_DAO_EntityRole();
         $entityRole->{$fieldName} = $value;
         $aclDAO = new CRM_ACL_DAO_ACL();
         $aclDAO->entity_id = $value;
         if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) {
             return FALSE;
         }
         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");
 }
Example #18
0
 public static function updatePledgeStatus($params)
 {
     $returnMessages = array();
     $sendReminders = CRM_Utils_Array::value('send_reminders', $params, FALSE);
     $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     //unset statues that we never use for pledges
     foreach (array('Completed', 'Cancelled', 'Failed') as $statusKey) {
         if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) {
             unset($allStatus[$key]);
         }
     }
     $statusIds = implode(',', array_keys($allStatus));
     $updateCnt = 0;
     $query = "\nSELECT  pledge.contact_id              as contact_id,\n        pledge.id                      as pledge_id,\n        pledge.amount                  as amount,\n        payment.scheduled_date         as scheduled_date,\n        pledge.create_date             as create_date,\n        payment.id                     as payment_id,\n        pledge.currency                as currency,\n        pledge.contribution_page_id    as contribution_page_id,\n        payment.reminder_count         as reminder_count,\n        pledge.max_reminders           as max_reminders,\n        payment.reminder_date          as reminder_date,\n        pledge.initial_reminder_day    as initial_reminder_day,\n        pledge.additional_reminder_day as additional_reminder_day,\n        pledge.status_id               as pledge_status,\n        payment.status_id              as payment_status,\n        pledge.is_test                 as is_test,\n        pledge.campaign_id             as campaign_id,\n        SUM(payment.scheduled_amount)  as amount_due,\n        ( SELECT sum(civicrm_pledge_payment.actual_amount)\n        FROM civicrm_pledge_payment\n        WHERE civicrm_pledge_payment.status_id = 1\n        AND  civicrm_pledge_payment.pledge_id = pledge.id\n        ) as amount_paid\n        FROM      civicrm_pledge pledge, civicrm_pledge_payment payment\n        WHERE     pledge.id = payment.pledge_id\n        AND     payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )\n        GROUP By  payment.id\n        ";
     $dao = CRM_Core_DAO::executeQuery($query);
     $now = date('Ymd');
     $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
     while ($dao->fetch()) {
         $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id);
         $pledgeDetails[$dao->payment_id] = array('scheduled_date' => $dao->scheduled_date, 'amount_due' => $dao->amount_due, 'amount' => $dao->amount, 'amount_paid' => $dao->amount_paid, 'create_date' => $dao->create_date, 'contact_id' => $dao->contact_id, 'pledge_id' => $dao->pledge_id, 'checksumValue' => $checksumValue, 'contribution_page_id' => $dao->contribution_page_id, 'reminder_count' => $dao->reminder_count, 'max_reminders' => $dao->max_reminders, 'reminder_date' => $dao->reminder_date, 'initial_reminder_day' => $dao->initial_reminder_day, 'additional_reminder_day' => $dao->additional_reminder_day, 'pledge_status' => $dao->pledge_status, 'payment_status' => $dao->payment_status, 'is_test' => $dao->is_test, 'currency' => $dao->currency, 'campaign_id' => $dao->campaign_id);
         $contactIds[$dao->contact_id] = $dao->contact_id;
         $pledgeStatus[$dao->pledge_id] = $dao->pledge_status;
         if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'), $now) && $dao->payment_status != array_search('Overdue', $allStatus)) {
             $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
         }
     }
     // process the updating script...
     foreach ($pledgePayments as $pledgeId => $paymentIds) {
         // 1. update the pledge /pledge payment status. returns new status when an update happens
         $returnMessages[] = "Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
         $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds, array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE);
         if ($newStatus != $pledgeStatus[$pledgeId]) {
             $returnMessages[] = "- status updated to: {$allStatus[$newStatus]}";
             $updateCnt += 1;
         }
     }
     if ($sendReminders) {
         // retrieve domain tokens
         $domain = CRM_Core_BAO_Domain::getDomain();
         $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens());
         $domainValues = array();
         foreach ($tokens['domain'] as $token) {
             $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
         }
         //get the domain email address, since we don't carry w/ object.
         $domainValue = CRM_Core_BAO_Domain::getNameAndEmail();
         $domainValues['email'] = $domainValue[1];
         // retrieve contact tokens
         // this function does NOT return Deceased contacts since we don't want to send them email
         list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, $tokens, 'CRM_UpdatePledgeRecord');
         // assign domain values to template
         $template = CRM_Core_Smarty::singleton();
         $template->assign('domain', $domainValues);
         //set receipt from
         $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
         foreach ($pledgeDetails as $paymentId => $details) {
             if (array_key_exists($details['contact_id'], $contactDetails)) {
                 $contactId = $details['contact_id'];
                 $pledgerName = $contactDetails[$contactId]['display_name'];
             } else {
                 continue;
             }
             if (empty($details['reminder_date'])) {
                 $nextReminderDate = new DateTime($details['scheduled_date']);
                 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
                 $nextReminderDate = $nextReminderDate->format("Ymd");
             } else {
                 $nextReminderDate = new DateTime($details['reminder_date']);
                 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
                 $nextReminderDate = $nextReminderDate->format("Ymd");
             }
             if ($details['reminder_count'] < $details['max_reminders'] && $nextReminderDate <= $now) {
                 $toEmail = $doNotEmail = $onHold = NULL;
                 if (!empty($contactDetails[$contactId]['email'])) {
                     $toEmail = $contactDetails[$contactId]['email'];
                 }
                 if (!empty($contactDetails[$contactId]['do_not_email'])) {
                     $doNotEmail = $contactDetails[$contactId]['do_not_email'];
                 }
                 if (!empty($contactDetails[$contactId]['on_hold'])) {
                     $onHold = $contactDetails[$contactId]['on_hold'];
                 }
                 // 2. send acknowledgement mail
                 if ($toEmail && !($doNotEmail || $onHold)) {
                     //assign value to template
                     $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0);
                     $template->assign('contact', $contactDetails[$contactId]);
                     $template->assign('next_payment', $details['scheduled_date']);
                     $template->assign('amount_due', $details['amount_due']);
                     $template->assign('checksumValue', $details['checksumValue']);
                     $template->assign('contribution_page_id', $details['contribution_page_id']);
                     $template->assign('pledge_id', $details['pledge_id']);
                     $template->assign('scheduled_payment_date', $details['scheduled_date']);
                     $template->assign('amount', $details['amount']);
                     $template->assign('create_date', $details['create_date']);
                     $template->assign('currency', $details['currency']);
                     list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_pledge', 'valueName' => 'pledge_reminder', 'contactId' => $contactId, 'from' => $receiptFrom, 'toName' => $pledgerName, 'toEmail' => $toEmail));
                     // 3. update pledge payment details
                     if ($mailSent) {
                         CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId);
                         $activityType = 'Pledge Reminder';
                         $activityParams = array('subject' => $subject, 'source_contact_id' => $contactId, 'source_record_id' => $paymentId, 'assignee_contact_id' => $contactId, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($now), 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']), 'is_test' => $details['is_test'], 'status_id' => 2, 'campaign_id' => $details['campaign_id']);
                         if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
                             $returnMessages[] = "Failed creating Activity for acknowledgment";
                             return array('is_error' => 1, 'message' => $returnMessages);
                         }
                         $returnMessages[] = "Payment reminder sent to: {$pledgerName} - {$toEmail}";
                     }
                 }
             }
         }
         // end foreach on $pledgeDetails
     }
     // end if ( $sendReminders )
     $returnMessages[] = "{$updateCnt} records updated.";
     return array('is_error' => 0, 'messages' => implode("\n\r", $returnMessages));
 }
 /**
  *  to calculate join, start and end dates
  *
  *  @param Array $calcDates array of dates returned by getDatesForMembershipType()
  *
  *  @return Array formatted containing date values
  *
  *  @access public
  */
 function formattedDates($calcDates, &$formatted)
 {
     $dates = array('join_date', 'start_date', 'end_date');
     foreach ($dates as $d) {
         if (isset($formatted[$d]) && !CRM_Utils_System::isNull($formatted[$d])) {
             $formatted[$d] = CRM_Utils_Date::isoToMysql($formatted[$d]);
         } elseif (isset($calcDates[$d])) {
             $formatted[$d] = CRM_Utils_Date::isoToMysql($calcDates[$d]);
         }
     }
 }
    /**
     * Cancel Recurring contribution.
     *
     * @param int $recurId
     *   Recur contribution id.
     * @param array $objects
     *   An array of objects that is to be cancelled like.
     *                          contribution, membership, event. At least contribution object is a must.
     *
     * @param array $activityParams
     *
     * @return bool
     */
    public static function cancelRecurContribution($recurId, $objects, $activityParams = array())
    {
        if (!$recurId) {
            return FALSE;
        }
        $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
        $canceledId = array_search('Cancelled', $contributionStatus);
        $recur = new CRM_Contribute_DAO_ContributionRecur();
        $recur->id = $recurId;
        $recur->whereAdd("contribution_status_id != {$canceledId}");
        if ($recur->find(TRUE)) {
            $transaction = new CRM_Core_Transaction();
            $recur->contribution_status_id = $canceledId;
            $recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
            $recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
            $recur->modified_date = CRM_Utils_Date::isoToMysql($recur->modified_date);
            $recur->cancel_date = date('YmdHis');
            $recur->save();
            $dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
            if ($dao && $dao->recur_id) {
                $details = CRM_Utils_Array::value('details', $activityParams);
                if ($dao->auto_renew && $dao->membership_id) {
                    // its auto-renewal membership mode
                    $membershipTypes = CRM_Member_PseudoConstant::membershipType();
                    $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
                    $membershipType = CRM_Utils_Array::value($membershipType, $membershipTypes);
                    $details .= '
<br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
                } else {
                    $details .= '
<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(1 => $dao->amount, 2 => $dao->frequency_interval, 3 => $dao->frequency_unit));
                }
                $activityParams = array('source_contact_id' => $dao->contact_id, 'source_record_id' => CRM_Utils_Array::value('source_record_id', $activityParams), 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Cancel Recurring Contribution', 'name'), 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')), 'details' => $details, 'activity_date_time' => date('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'));
                $session = CRM_Core_Session::singleton();
                $cid = $session->get('userID');
                if ($cid) {
                    $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
                    $activityParams['source_contact_id'] = $cid;
                }
                CRM_Activity_BAO_Activity::create($activityParams);
            }
            // if there are associated objects, cancel them as well
            if ($objects == CRM_Core_DAO::$_nullObject) {
                $transaction->commit();
                return TRUE;
            } else {
                $baseIPN = new CRM_Core_Payment_BaseIPN();
                return $baseIPN->cancelled($objects, $transaction);
            }
        } else {
            // if already cancelled, return true
            $recur->whereAdd();
            $recur->whereAdd("contribution_status_id = {$canceledId}");
            if ($recur->find(TRUE)) {
                return TRUE;
            }
        }
        return FALSE;
    }
Example #21
0
 /**
  * Function to add/copy relationships, when new client is added for a case
  *
  * @param int $caseId case id
  * @param int $contactId contact id / new client id
  *
  * @return void
  */
 static function addCaseRelationships($caseId, $contactId)
 {
     // get the case role / relationships for the case
     $caseRelationships = new CRM_Contact_DAO_Relationship();
     $caseRelationships->case_id = $caseId;
     $caseRelationships->find();
     $relationshipTypes = array();
     // make sure we don't add duplicate relationships of same relationship type.
     while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id, $relationshipTypes)) {
         $values = array();
         CRM_Core_DAO::storeValues($caseRelationships, $values);
         // add relationship for new client.
         $newRelationship = new CRM_Contact_DAO_Relationship();
         $newRelationship->copyValues($values);
         $newRelationship->id = NULL;
         $newRelationship->case_id = $caseId;
         $newRelationship->contact_id_a = $contactId;
         $newRelationship->end_date = CRM_Utils_Date::isoToMysql($caseRelationships->end_date);
         $newRelationship->start_date = CRM_Utils_Date::isoToMysql($caseRelationships->start_date);
         // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
         if (!$newRelationship->find(TRUE)) {
             $newRelationship->save();
         }
         $newRelationship->free();
         // store relationship type of newly created relationship
         $relationshipTypes[] = $caseRelationships->relationship_type_id;
     }
 }
Example #22
0
 /**
  * Convert all date fields within the params to mysql date ready for the
  * BAO layer. In this case fields are checked against the $_datefields defined for the form
  * and if time is defined it is incorporated
  *
  * @param array $params
  *   Input params from the form.
  *
  * @todo it would probably be better to work on $this->_params than a passed array
  * @todo standardise the format which dates are passed to the BAO layer in & remove date
  * handling from BAO
  */
 public function convertDateFieldsToMySQL(&$params)
 {
     foreach ($this->_dateFields as $fieldName => $specs) {
         if (!empty($params[$fieldName])) {
             $params[$fieldName] = CRM_Utils_Date::isoToMysql(CRM_Utils_Date::processDate($params[$fieldName], CRM_Utils_Array::value("{$fieldName}_time", $params), TRUE));
         } else {
             if (isset($specs['default'])) {
                 $params[$fieldName] = date('YmdHis', strtotime($specs['default']));
             }
         }
     }
 }
Example #23
0
 function executePrintmode($rows)
 {
     //only get these last contribution related variables in print mode if selected on previous form
     if (array_key_exists('civicrm_contribution_cont_receive_date', $rows[0])) {
         $receiveDate = ', date_received   DATE';
     }
     if (array_key_exists('civicrm_contribution_cont_total_amount', $rows[0])) {
         $contAmount = ' , total_amount FLOAT';
     }
     //  Separate out fields and build a temporary table
     $tempTable = "WalkList_" . uniqid();
     $sql = "CREATE TEMPORARY TABLE {$tempTable}" . " ( id              INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,\n                  street_name     VARCHAR(255),\n                  s_street_number VARCHAR(32),\n                  i_street_number INT,\n                  odd             TINYINT,\n                  apt_number      VARCHAR(32),\n                  city            VARCHAR(64),\n                  state           VARCHAR(32),\n                  zip             VARCHAR(32),\n                  name            VARCHAR(255),\n                  phone           VARCHAR(255),\n                  age             INT,\n                  sex             VARCHAR(16),\n                  lang            CHAR(2),\n                  party           CHAR(1),\n                  vh              CHAR(1),\n                  contact_type    VARCHAR(128),\n                  other_name      VARCHAR(128),\n                  contact_id      INT\n                  {$receiveDate} {$contAmount}\n                  )\n                 ENGINE=HEAP\n                 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
     CRM_Core_DAO::executeQuery($sql);
     $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
     foreach ($rows as $key => $value) {
         $dob = $value['civicrm_contact_birth_date'];
         $age = empty($dob) ? 0 : $this->dob2age($dob);
         if (!empty($value['civicrm_contact_gender_id'])) {
             $sex = $gender[CRM_Utils_Array::value('civicrm_contact_gender_id', $value)];
         }
         $sex = empty($sex) ? '' : $sex;
         $lang = strtoupper(substr($value[$this->_demoTable . '_' . $this->_demoLangCol], 0, 2));
         $party = substr($value["{$this->_voterInfoTable}_{$this->_partyCol}"], 0, 1);
         $vh = substr($value["{$this->_voterInfoTable}_{$this->_vhCol}"], 0, 1);
         $contactType = $value[$this->_coreInfoTable . '_' . $this->_coreTypeCol];
         $on = $value[$this->_coreInfoTable . '_' . $this->_coreOtherCol];
         $otherName = empty($on) ? 0 : "'{$on}'";
         $type = '';
         if (!empty($contactType)) {
             $type = $this->hexOne2str($contactType);
         }
         $contact_id = (int) $value['civicrm_contact_id'];
         $state = '';
         if (!empty($value['civicrm_address_state_province_id'])) {
             $state = CRM_Core_PseudoConstant::stateProvince($value['civicrm_address_state_province_id']);
         }
         $sStreetNumber = $value['civicrm_address_street_number'];
         $iStreetNumber = $value['civicrm_address_street_number'] ? (int) $value['civicrm_address_street_number'] : 0;
         $odd = $value['civicrm_address_street_number'] ? (int) $value['civicrm_address_street_number'] % 2 : 0;
         $apt_number = $value['civicrm_address_street_number'] ? $value['civicrm_address_street_number'] : '';
         $phone_number = $value['civicrm_phone_phone'] ? $value['civicrm_phone_phone'] : '';
         $query = "INSERT INTO {$tempTable} SET\n                       street_name     = %1,\n                       s_street_number = %2,\n                       i_street_number = %3,\n                       odd             = %4,\n                       apt_number      = %5,\n                       city            = %6,\n                       state           = %7,\n                       zip             = %8,\n                       name            = %9,\n                       phone           = %10,\n                       age             = %11,\n                       sex             = %12,\n                       lang            = %13,\n                       party           = %14,\n                       vh              = %15,\n                       contact_type    = %16,\n                       other_name      = %17,\n                       contact_id      = %18";
         $params = array(1 => array($value['civicrm_address_street_name'] ? $value['civicrm_address_street_name'] : '', 'String'), 2 => array((string) $sStreetNumber, 'String'), 3 => array($iStreetNumber, 'Integer'), 4 => array($odd, 'Integer'), 5 => array((string) $apt_number, 'String'), 6 => array($value['civicrm_address_city'] ? $value['civicrm_address_city'] : '', 'String'), 7 => array((string) $state, 'String'), 8 => array($value['civicrm_address_postal_code'] ? $value['civicrm_address_postal_code'] : '', 'String'), 9 => array($value['civicrm_contact_display_name'] ? $value['civicrm_contact_display_name'] : '', 'String'), 10 => array((string) $phone_number, 'String'), 11 => array($age, 'Integer'), 12 => array((string) $sex, 'String'), 13 => array((string) $lang, 'String'), 14 => array((string) $party, 'String'), 15 => array((string) $vh, 'String'), 16 => array((string) $type, 'String'), 17 => array((string) $otherName, 'String'), 18 => array((string) $contact_id, 'Integer'));
         if (!empty($contAmount)) {
             $query .= ", total_amount = %19";
             $total_amount = $value['civicrm_contribution_cont_total_amount'] ? $value['civicrm_contribution_cont_total_amount'] : 0;
             $params[19] = array($total_amount, 'Money');
         }
         if (!empty($receiveDate)) {
             $query .= ",date_received  = %20";
             $date_received = $value['civicrm_contribution_cont_receive_date'] ? CRM_Utils_Date::isoToMysql($value['civicrm_contribution_cont_receive_date']) : NULL;
             $params[20] = array($date_received, 'Timestamp');
         }
         CRM_Core_DAO::executeQuery($query, $params);
     }
     //  With the data normalized and in a table, we can
     //  retrieve it in the order we need to present it
     $query = "SELECT * FROM {$tempTable} ORDER BY state, city, zip,\n                  street_name, odd, i_street_number, apt_number";
     $dao = CRM_Core_DAO::executeQuery($query);
     //  Initialize output state
     $first = TRUE;
     $state = '';
     $city = '';
     $zip = '';
     $street_name = '';
     $odd = '';
     $pageRow = 0;
     $reportDate = date('F j, Y');
     $pdfRows = array();
     $groupRows = array();
     $groupCounts = 0;
     $pdfHeaders = array('s_street_number' => array('title' => 'STREET#'), 'apt_number' => array('title' => 'APT'), 'name' => array('title' => 'Name'), 'phone' => array('title' => 'PHONE'), 'age' => array('title' => 'AGE'), 'sex' => array('title' => 'SEX'), 'lang' => array('title' => 'Lang'), 'party' => array('title' => 'Party'), 'vh' => array('title' => 'VH'), 'contact_type' => array('title' => 'Constituent Type'), 'note' => array('title' => 'NOTES'), 'rcode' => array('title' => 'RESPONSE CODES'), 'status' => array('title' => 'STATUS'), 'contact_id' => array('title' => 'ID', 'class' => 'width=7%'));
     if (variable_get('civicrm_engage_groupbreak_street', "1") != 1) {
         $pdfHeaders['street_name']['title'] = 'Street';
     }
     if ($receiveDate) {
         $pdfHeaders['date_received'] = array('title' => 'Last donation Date');
     }
     if ($contAmount) {
         $pdfHeaders['total_amount'] = array('title' => 'Last donation');
     }
     $groupInfo = array('date' => $reportDate, 'descr' => empty($this->_groupDescr) ? '' : "<br>Group {$this->_groupDescr}");
     while ($dao->fetch()) {
         if (strtolower($state) != strtolower($dao->state) || variable_get('civicrm_engage_groupbreak_city', "1") == 1 && strtolower($city) != strtolower($dao->city) || variable_get('civicrm_engage_groupbreak_zip', "1") == 1 && strtolower($zip) != strtolower($dao->zip) || variable_get('civicrm_engage_groupbreak_street', "1") == 1 && strtolower($street_name) != strtolower($dao->street_name) || variable_get('civicrm_engage_groupbreak_odd_even', "1") == 1 && $odd != $dao->odd || $pageRow > variable_get('civicrm_engage_lines_per_group', "6") - 1) {
             $state = $dao->state;
             $city = $dao->city;
             $zip = $dao->zip;
             $street_name = $dao->street_name;
             $odd = $dao->odd;
             $pageRow = 0;
             $groupRow['city_zip'] = '';
             $groupRow['org'] = $this->_orgName;
             if (variable_get('civicrm_engage_groupbreak_street', "1") == 1) {
                 $groupRow['street_name'] = $street_name;
             }
             if (variable_get('civicrm_engage_groupbreak_city', "1") == 1) {
                 $groupRow['city_zip'] .= $city . ', ';
             }
             $groupRow['city_zip'] .= $state;
             //don't give zip or odd-even if not grouped on
             if (variable_get('civicrm_engage_groupbreak_zip', "1") == 1) {
                 $groupRow['city_zip'] .= ' ' . $zip;
             }
             if (variable_get('civicrm_engage_groupbreak_odd_even', "1") == 1) {
                 $groupRow['odd'] = $odd ? 'Odd' : 'Even';
             }
             $groupCounts++;
             $groupRows[$groupCounts] = $groupRow;
         }
         // if admin settings have been defined to specify not to canvas people for a period change date to specified text
         if (variable_get('civicrm_engage_no_canvas_period', "0") > 0 && $dao->date_received > 0 && (strtotime("now") - strtotime($dao->date_received)) / 60 / 60 / 24 / 30 < variable_get('civicrm_engage_no_canvas_period', "0")) {
             $dao->date_received = variable_get('civicrm_engage_no_canvass_text', "Do Not Canvass");
         }
         $pdfRow = array();
         foreach ($pdfHeaders as $k => $v) {
             if (property_exists($dao, $k)) {
                 if ($k == 'name' && $dao->other_name) {
                     $pdfRow[$k] = $dao->{$k} . "<br />" . $dao->other_name;
                     continue;
                 }
                 $pdfRow[$k] = $dao->{$k};
             } else {
                 $pdfRow[$k] = "";
             }
         }
         $pdfRows[$groupCounts][] = $pdfRow;
         $pageRow++;
     }
     if (variable_get('civicrm_engage_group_per_page', "1")) {
         $this->assign('newgroupdiv', 'class="page"');
     }
     $this->assign('pageTotal', $groupCounts);
     $this->assign('pdfHeaders', $pdfHeaders);
     $this->assign('groupInfo', $groupInfo);
     $this->assign('pdfRows', $pdfRows);
     $this->assign('groupRows', $groupRows);
 }
 public function doDirectPayment(&$params)
 {
     if (!defined('CURLOPT_SSLCERT')) {
         CRM_Core_Error::fatal(ts('eWAY - Gateway requires curl with SSL support'));
     }
     /*
      * OPTIONAL: If TEST Card Number force an Override of URL and CustomerID.
      * During testing CiviCRM once used the LIVE URL.
      * This code can be uncommented to override the LIVE URL that if CiviCRM does that again.
      * if ( ( $gateway_URL == "https://www.eway.com.au/gateway_cvn/xmlpayment.asp")
      *   && ( $params['credit_card_number'] == "4444333322221111" ) ) {
      *   $ewayCustomerID = "87654321";
      *   $gateway_URL    = "https://www.eway.com.au/gateway/rebill/test/Upload_test.aspx";
      * }
      */
     // Was the recurring payment check box checked?
     if (isset($params['is_recur']) && $params['is_recur'] == 1) {
         // Create the customer via the API.
         try {
             $result = $this->createToken($this->_paymentProcessor, $params);
         } catch (Exception $e) {
             return self::errorExit(9010, $e->getMessage());
         }
         // We've created the customer successfully.
         $managed_customer_id = $result;
         try {
             $initialPayment = civicrm_api3('ewayrecurring', 'payment', array('invoice_id' => $params['invoiceID'], 'amount_in_cents' => round((double) $params['amount'] * 100), 'managed_customer_id' => $managed_customer_id, 'description' => $params['description'] . ts('first payment'), 'payment_processor_id' => $this->_paymentProcessor['id']));
             // Here we compensate for the fact core accepts 0 as a valid frequency
             // interval and set it.
             $extra = array();
             if (empty($params['frequency_interval'])) {
                 $params['frequency_interval'] = 1;
                 $extra['frequency_interval'] = 1;
             }
             $params['trxn_id'] = $initialPayment['values'][$managed_customer_id]['trxn_id'];
             $params['contribution_status_id'] = 1;
             $params['payment_status_id'] = 1;
             // If there's only one installment, then the recurring contribution is now complete
             if (isset($params['installments']) && $params['installments'] == 1) {
                 $status = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
             } else {
                 $status = CRM_Core_OptionGroup::getValue('contribution_status', 'In Progress', 'name');
             }
             // Save the eWay customer token in the recurring contribution's processor_id field.
             civicrm_api3('contribution_recur', 'create', array_merge(array('id' => $params['contributionRecurID'], 'processor_id' => $managed_customer_id, 'contribution_status_id' => $status, 'next_sched_contribution_date' => CRM_Utils_Date::isoToMysql(date('Y-m-d 00:00:00', strtotime('+' . $params['frequency_interval'] . ' ' . $params['frequency_unit'])))), $extra));
             // Send recurring Notification email for user.
             $recur = new CRM_Contribute_BAO_ContributionRecur();
             $recur->id = $params['contributionRecurID'];
             $recur->find(TRUE);
             // If none found then effectively FALSE.
             $autoRenewMembership = civicrm_api3('membership', 'getcount', array('contribution_recur_id' => $recur->id));
             if (!empty($params['selectMembership']) || !empty($params['membership_type_id']) && !empty($params['auto_renew'])) {
                 $autoRenewMembership = TRUE;
             }
             CRM_Contribute_BAO_ContributionPage::recurringNotify(CRM_Core_Payment::RECURRING_PAYMENT_START, $params['contactID'], CRM_Utils_Array::value('contributionPageID', $params), $recur, $autoRenewMembership);
         } catch (CiviCRM_API3_Exception $e) {
             return self::errorExit(9014, 'Initial payment not processed' . $e->getMessage());
         }
     } else {
         try {
             $result = $this->processSinglePayment($params);
             $params = array_merge($params, $result);
         } catch (CRM_Core_Exception $e) {
             return self::errorExit(9001, $e->getMessage());
         }
     }
     return $params;
 }
 /**
  * Get entity value.
  *
  * @param int $id
  * @param $entity
  * @param $logDate
  *
  * @return mixed|null|string
  */
 public function getEntityValue($id, $entity, $logDate)
 {
     if (!empty($this->_logTables[$entity]['bracket_info'])) {
         if (!empty($this->_logTables[$entity]['bracket_info']['entity_column'])) {
             $logTable = !empty($this->_logTables[$entity]['table_name']) ? $this->_logTables[$entity]['table_name'] : $entity;
             $sql = "\nSELECT {$this->_logTables[$entity]['bracket_info']['entity_column']}\n  FROM `{$this->loggingDB}`.{$logTable}\n WHERE  log_date <= %1 AND id = %2 ORDER BY log_date DESC LIMIT 1";
             $entityID = CRM_Core_DAO::singleValueQuery($sql, array(1 => array(CRM_Utils_Date::isoToMysql($logDate), 'Timestamp'), 2 => array($id, 'Integer')));
         } else {
             $entityID = $id;
         }
         if ($entityID && $logDate && array_key_exists('table', $this->_logTables[$entity]['bracket_info'])) {
             $sql = "\nSELECT {$this->_logTables[$entity]['bracket_info']['column']}\nFROM  `{$this->loggingDB}`.{$this->_logTables[$entity]['bracket_info']['table']}\nWHERE  log_date <= %1 AND id = %2 ORDER BY log_date DESC LIMIT 1";
             return CRM_Core_DAO::singleValueQuery($sql, array(1 => array(CRM_Utils_Date::isoToMysql($logDate), 'Timestamp'), 2 => array($entityID, 'Integer')));
         } else {
             if (array_key_exists('options', $this->_logTables[$entity]['bracket_info']) && $entityID) {
                 return CRM_Utils_Array::value($entityID, $this->_logTables[$entity]['bracket_info']['options']);
             }
         }
     }
     return NULL;
 }
Example #26
0
 /**
  * Add activity for Membership/Event/Contribution.
  *
  * @param object $activity
  *   (reference) particular component object.
  * @param string $activityType
  *   For Membership Signup or Renewal.
  * @param int $targetContactID
  *
  * @return bool|NULL
  */
 public static function addActivity(&$activity, $activityType = 'Membership Signup', $targetContactID = NULL)
 {
     if ($activity->__table == 'civicrm_membership') {
         $membershipType = CRM_Member_PseudoConstant::membershipType($activity->membership_type_id);
         if (!$membershipType) {
             $membershipType = ts('Membership');
         }
         $subject = "{$membershipType}";
         if (!empty($activity->source) && $activity->source != 'null') {
             $subject .= " - {$activity->source}";
         }
         if ($activity->owner_membership_id) {
             $query = "\nSELECT  display_name\n  FROM  civicrm_contact, civicrm_membership\n WHERE  civicrm_contact.id    = civicrm_membership.contact_id\n   AND  civicrm_membership.id = {$activity->owner_membership_id}\n";
             $displayName = CRM_Core_DAO::singleValueQuery($query);
             $subject .= " (by {$displayName})";
         }
         $subject .= " - Status: " . CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $activity->status_id, 'label');
         // CRM-72097 changed from start date to today
         $date = date('YmdHis');
         $component = 'Membership';
     } elseif ($activity->__table == 'civicrm_participant') {
         $event = CRM_Event_BAO_Event::getEvents(1, $activity->event_id, TRUE, FALSE);
         $roles = CRM_Event_PseudoConstant::participantRole();
         $status = CRM_Event_PseudoConstant::participantStatus();
         $subject = $event[$activity->event_id];
         if (!empty($roles[$activity->role_id])) {
             $subject .= ' - ' . $roles[$activity->role_id];
         }
         if (!empty($status[$activity->status_id])) {
             $subject .= ' - ' . $status[$activity->status_id];
         }
         $date = date('YmdHis');
         if ($activityType != 'Email') {
             $activityType = 'Event Registration';
         }
         $component = 'Event';
     } elseif ($activity->__table == 'civicrm_contribution') {
         // create activity record only for Completed Contributions
         if ($activity->contribution_status_id != 1) {
             return NULL;
         }
         $subject = NULL;
         $subject .= CRM_Utils_Money::format($activity->total_amount, $activity->currency);
         if (!empty($activity->source) && $activity->source != 'null') {
             $subject .= " - {$activity->source}";
         }
         $date = CRM_Utils_Date::isoToMysql($activity->receive_date);
         $activityType = $component = 'Contribution';
     }
     $activityParams = array('source_contact_id' => $activity->contact_id, 'source_record_id' => $activity->id, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'subject' => $subject, 'activity_date_time' => $date, 'is_test' => $activity->is_test, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'), 'skipRecentView' => TRUE, 'campaign_id' => $activity->campaign_id);
     // create activity with target contacts
     $session = CRM_Core_Session::singleton();
     $id = $session->get('userID');
     if ($id) {
         $activityParams['source_contact_id'] = $id;
         $activityParams['target_contact_id'][] = $activity->contact_id;
     }
     // CRM-14945
     if (property_exists($activity, 'details')) {
         $activityParams['details'] = $activity->details;
     }
     //CRM-4027
     if ($targetContactID) {
         $activityParams['target_contact_id'][] = $targetContactID;
     }
     if (is_a(self::create($activityParams), 'CRM_Core_Error')) {
         CRM_Core_Error::fatal("Failed creating Activity for {$component} of id {$activity->id}");
         return FALSE;
     }
 }
 /**
  * Process recurring contributions
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param boolean $first
  * @return void|boolean
  */
 function recur(&$input, &$ids, &$objects, $first)
 {
     if (!isset($input['txnType'])) {
         CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
         echo "Failure: Invalid parameters<p>";
         return FALSE;
     }
     if ($input['txnType'] == 'recurring_payment' && $input['paymentStatus'] != 'Completed') {
         CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
         echo "Failure: Invalid parameters<p>";
         return FALSE;
     }
     $recur =& $objects['contributionRecur'];
     // make sure the invoice ids match
     // make sure the invoice is valid and matches what we have in
     // the contribution record
     if ($recur->invoice_id != $input['invoice']) {
         CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
         echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
         return FALSE;
     }
     $now = date('YmdHis');
     // fix dates that already exist
     $dates = array('create', 'start', 'end', 'cancel', 'modified');
     foreach ($dates as $date) {
         $name = "{$date}_date";
         if ($recur->{$name}) {
             $recur->{$name} = CRM_Utils_Date::isoToMysql($recur->{$name});
         }
     }
     $sendNotification = FALSE;
     $subscriptionPaymentStatus = NULL;
     //List of Transaction Type
     /*
      recurring_payment_profile_created          RP Profile Created
      recurring_payment           RP Sucessful Payment
      recurring_payment_failed                               RP Failed Payment
      recurring_payment_profile_cancel           RP Profile Cancelled
      recurring_payment_expired         RP Profile Expired
      recurring_payment_skipped        RP Profile Skipped
      recurring_payment_outstanding_payment      RP Sucessful Outstanding Payment
      recurring_payment_outstanding_payment_failed          RP Failed Outstanding Payment
      recurring_payment_suspended        RP Profile Suspended
      recurring_payment_suspended_due_to_max_failed_payment  RP Profile Suspended due to Max Failed Payment
     */
     //set transaction type
     $txnType = $this->retrieve('txn_type', 'String');
     //Changes for paypal pro recurring payment
     $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
     $contributionStatuses = $contributionStatuses['values'];
     switch ($txnType) {
         case 'recurring_payment_profile_created':
             if (in_array($recur->contribution_status_id, array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses))) && !empty($recur->processor_id)) {
                 echo "already handled";
                 return;
             }
             $recur->create_date = $now;
             $recur->contribution_status_id = 2;
             $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
             $recur->trxn_id = $recur->processor_id;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
             $sendNotification = TRUE;
             break;
         case 'recurring_payment':
             if ($first) {
                 $recur->start_date = $now;
             } else {
                 $recur->modified_date = $now;
             }
             //contribution installment is completed
             if ($this->retrieve('profile_status', 'String') == 'Expired') {
                 if (!empty($recur->end_date)) {
                     echo "already handled";
                     return;
                 }
                 $recur->contribution_status_id = 1;
                 $recur->end_date = $now;
                 $sendNotification = TRUE;
                 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
             }
             // make sure the contribution status is not done
             // since order of ipn's is unknown
             if ($recur->contribution_status_id != 1) {
                 $recur->contribution_status_id = 5;
             }
             break;
     }
     $recur->save();
     if ($sendNotification) {
         $autoRenewMembership = FALSE;
         if ($recur->id && isset($ids['membership']) && $ids['membership']) {
             $autoRenewMembership = TRUE;
         }
         //send recurring Notification email for user
         CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus, $ids['contact'], $ids['contributionPage'], $recur, $autoRenewMembership);
     }
     if ($txnType != 'recurring_payment') {
         return;
     }
     if (!$first) {
         //check if this contribution transaction is already processed
         //if not create a contribution and then get it processed
         $contribution = new CRM_Contribute_BAO_Contribution();
         $contribution->trxn_id = $input['trxn_id'];
         if ($contribution->trxn_id && $contribution->find()) {
             CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
             echo "Success: Contribution has already been handled<p>";
             return TRUE;
         }
         $contribution->contact_id = $recur->contact_id;
         $contribution->financial_type_id = $objects['contributionType']->id;
         $contribution->contribution_page_id = $ids['contributionPage'];
         $contribution->contribution_recur_id = $ids['contributionRecur'];
         $contribution->currency = $objects['contribution']->currency;
         $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
         $contribution->amount_level = $objects['contribution']->amount_level;
         $contribution->campaign_id = $objects['contribution']->campaign_id;
         $objects['contribution'] =& $contribution;
     }
     // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
     $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
     $this->single($input, $ids, $objects, TRUE, $first);
 }
Example #28
0
 /**
  * Function to set the task status of various tasks
  *
  * @param array  $params        associated array
  *
  * @static
  * @return returns task status object
  */
 static function create(&$params)
 {
     if (!$params['target_entity_id'] || !$params['responsible_entity_id'] || !$params['task_id'] || !$params['status_id']) {
         return null;
     }
     if (!$params['target_entity_table']) {
         $params['target_entity_table'] = 'civicrm_contact';
     }
     if (!$params['responsible_entity_table']) {
         $params['responsible_entity_table'] = 'civicrm_contact';
     }
     require_once 'CRM/Project/DAO/TaskStatus.php';
     $dao =& new CRM_Project_DAO_TaskStatus();
     $dao->target_entity_id = $params['target_entity_id'];
     $dao->responsible_entity_id = $params['responsible_entity_id'];
     $dao->target_entity_table = $params['target_entity_table'];
     $dao->responsible_entity_table = $params['responsible_entity_table'];
     $dao->task_id = $params['task_id'];
     if ($dao->find(true)) {
         $dao->create_date = CRM_Utils_Date::isoToMysql($dao->create_date);
     } else {
         $dao->create_date = date('YmdHis');
     }
     $dao->modified_date = date('YmdHis');
     $dao->status_id = $params['status_id'];
     return $dao->save();
 }
Example #29
0
 /**
  * Process the form after the input has been submitted and validated.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     // get all the details needed to generate a receipt
     $message = array();
     $template = CRM_Core_Smarty::singleton();
     $params = $this->controller->exportValues($this->_name);
     $elements = self::getElements($this->_contributionIds, $params, $this->_contactIds);
     foreach ($elements['details'] as $contribID => $detail) {
         $input = $ids = $objects = array();
         if (in_array($detail['contact'], $elements['excludeContactIds'])) {
             continue;
         }
         $input['component'] = $detail['component'];
         $ids['contact'] = $detail['contact'];
         $ids['contribution'] = $contribID;
         $ids['contributionRecur'] = NULL;
         $ids['contributionPage'] = NULL;
         $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
         $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
         $ids['event'] = CRM_Utils_Array::value('event', $detail);
         if (!$elements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
             CRM_Core_Error::fatal();
         }
         $contribution =& $objects['contribution'];
         // set some fake input values so we can reuse IPN code
         $input['amount'] = $contribution->total_amount;
         $input['is_test'] = $contribution->is_test;
         $input['fee_amount'] = $contribution->fee_amount;
         $input['net_amount'] = $contribution->net_amount;
         $input['trxn_id'] = $contribution->trxn_id;
         $input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : NULL;
         // CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date
         $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
         $values = array();
         $mail = $elements['baseIPN']->sendMail($input, $ids, $objects, $values, FALSE, $elements['createPdf']);
         if ($mail['html']) {
             $message[] = $mail['html'];
         } else {
             $message[] = nl2br($mail['body']);
         }
         // reset template values before processing next transactions
         $template->clearTemplateVars();
         if (!empty($params['receipt_update'])) {
             $objects['contribution']->receipt_date = date('Y-m-d H-i-s');
             $objects['contribution']->save();
         }
     }
     if ($elements['createPdf']) {
         CRM_Utils_PDF_Utils::html2pdf($message, 'civicrmContributionReceipt.pdf', FALSE, $elements['params']['pdf_format_id']);
         CRM_Utils_System::civiExit();
     } else {
         if ($elements['suppressedEmails']) {
             $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $elements['suppressedEmails']));
             $msgTitle = ts('Email Error');
             $msgType = 'error';
         } else {
             $status = ts('Your mail has been sent.');
             $msgTitle = ts('Sent');
             $msgType = 'success';
         }
         CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
     }
 }
Example #30
0
 function recur(&$input, &$ids, &$objects, $first)
 {
     if (!isset($input['txnType'])) {
         CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
         echo "Failure: Invalid parameters<p>";
         return false;
     }
     if ($input['txnType'] == 'recurring_payment' && $input['paymentStatus'] != 'Completed') {
         CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
         echo "Failure: Invalid parameters<p>";
         return false;
     }
     $recur =& $objects['contributionRecur'];
     // make sure the invoice ids match
     // make sure the invoice is valid and matches what we have in
     // the contribution record
     if ($recur->invoice_id != $input['invoice']) {
         CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
         echo "Failure: Invoice values dont match between database and IPN request<p>";
         return false;
     }
     $now = date('YmdHis');
     // fix dates that already exist
     $dates = array('create', 'start', 'end', 'cancel', 'modified');
     foreach ($dates as $date) {
         $name = "{$date}_date";
         if ($recur->{$name}) {
             $recur->{$name} = CRM_Utils_Date::isoToMysql($recur->{$name});
         }
     }
     $sendNotification = false;
     $subscriptionPaymentStatus = null;
     //List of Transaction Type
     /*
      recurring_payment_profile_created    			RP Profile Created
      recurring_payment 					RP Sucessful Payment
      recurring_payment_failed                               RP Failed Payment
      recurring_payment_profile_cancel     			RP Profile Cancelled
      recurring_payment_expired 				RP Profile Expired
      recurring_payment_skipped				RP Profile Skipped
      recurring_payment_outstanding_payment			RP Sucessful Outstanding Payment
      recurring_payment_outstanding_payment_failed	        RP Failed Outstanding Payment
      recurring_payment_suspended				RP Profile Suspended
      recurring_payment_suspended_due_to_max_failed_payment	RP Profile Suspended due to Max Failed Payment
     */
     //set transaction type
     $txnType = $_POST['txn_type'];
     require_once 'CRM/Core/Payment.php';
     //Changes for paypal pro recurring payment
     switch ($txnType) {
         case 'recurring_payment_profile_created':
             $recur->create_date = $now;
             $recur->contribution_status_id = 2;
             $recur->processor_id = $_POST['recurring_payment_id'];
             $recur->trxn_id = $recur->processor_id;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
             $sendNotification = true;
             break;
         case 'recurring_payment':
             if ($first) {
                 $recur->start_date = $now;
             } else {
                 $recur->modified_date = $now;
             }
             //contribution installment is completed
             if ($_POST['profile_status'] == 'Expired') {
                 $recur->contribution_status_id = 1;
                 $recur->end_date = $now;
                 $sendNotification = true;
                 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
             }
             // make sure the contribution status is not done
             // since order of ipn's is unknown
             if ($recur->contribution_status_id != 1) {
                 $recur->contribution_status_id = 5;
             }
             break;
     }
     $recur->save();
     if ($sendNotification) {
         //send recurring Notification email for user
         require_once 'CRM/Contribute/BAO/ContributionPage.php';
         CRM_Contribute_BAO_ContributionPage::recurringNofify($subscriptionPaymentStatus, $ids['contact'], $ids['contributionPage'], $recur);
     }
     if ($txnType != 'recurring_payment') {
         return;
     }
     if (!$first) {
         // create a contribution and then get it processed
         $contribution =& new CRM_Contribute_DAO_Contribution();
         $contribution->contact_id = $ids['contact'];
         $contribution->contribution_type_id = $objects['contributionType']->id;
         $contribution->contribution_page_id = $ids['contributionPage'];
         $contribution->contribution_recur_id = $ids['contributionRecur'];
         $contribution->receive_date = $now;
         $contribution->currency = $objects['contribution']->currency;
         $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
         $contribution->amount_level = $objects['contribution']->amount_level;
         $objects['contribution'] =& $contribution;
     }
     $this->single($input, $ids, $objects, true, $first);
 }