Exemplo n.º 1
0
 /**
  * Set default values for the form. Note that in edit/view mode
  * the default values are retrieved from the database
  *
  *
  * @return void
  */
 public function setDefaultValues()
 {
     //parent::setDefaultValues();
     $defaults = array();
     if (isset($this->_id)) {
         $defaults = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
     }
     $defaults['member_is_active'] = $defaults['is_active'];
     // Set Display Minimum Fee default to true if we are adding a new membership block
     if (!isset($defaults['id'])) {
         $defaults['display_min_fee'] = 1;
     } else {
         $this->assign('membershipBlockId', $defaults['id']);
     }
     if ($this->_id && ($priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 3, 1))) {
         $defaults['member_price_set_id'] = $priceSetId;
         $this->_memPriceSetId = $priceSetId;
     } else {
         // for membership_types
         // if ( isset( $defaults['membership_types'] ) ) {
         $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 3);
         $this->assign('isQuick', 1);
         $this->_memPriceSetId = $priceSetId;
         $pFIDs = array();
         if ($priceSetId) {
             CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = array('html_type', 'name', 'label'));
             foreach ($pFIDs as $pid => $pValue) {
                 if ($pValue['html_type'] == 'Radio' && $pValue['name'] == 'membership_amount') {
                     $defaults['mem_price_field_id'] = $pValue['id'];
                     $defaults['membership_type_label'] = $pValue['label'];
                 }
             }
             if (!empty($defaults['mem_price_field_id'])) {
                 $options = array();
                 $priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($defaults['mem_price_field_id'], $options, 'id', 1);
                 foreach ($options as $k => $v) {
                     $newMembershipType[$v['membership_type_id']] = 1;
                     if (!empty($defaults['auto_renew'])) {
                         $defaults["auto_renew_" . $v['membership_type_id']] = $defaults['auto_renew'][$v['membership_type_id']];
                     }
                 }
                 $defaults['membership_type'] = $newMembershipType;
             }
         }
     }
     return $defaults;
 }
Exemplo n.º 2
0
 public function preProcess()
 {
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this);
     $this->_entityId = CRM_Utils_Request::retrieve('eid', 'Positive', $this, true);
     $page = CRM_Utils_Request::retrieve('page', 'String', $this, true);
     if ($page == 'contribution') {
         $this->_entityTable = 'civicrm_contribution_page';
         $this->_title = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_entityId, 'title');
     } elseif ($page == 'event') {
         $this->_entityTable = 'civicrm_event';
         $this->_title = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_entityId, 'title');
     } elseif ($page == 'pcp') {
         $this->_pcpBlockId = CRM_Utils_Request::retrieve('blockId', 'Positive', $this, true);
         CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_PCPBlock', 'id', $this->_pcpBlockId, $pcpBlock, array('is_tellfriend_enabled', 'tellfriend_limit'));
         if (!CRM_Utils_Array::value('is_tellfriend_enabled', $pcpBlock[$this->_pcpBlockId])) {
             CRM_Core_Error::fatal(ts('Tell Friend is disable for this Personal Campaign Page'));
         }
         $this->_mailLimit = $pcpBlock[$this->_pcpBlockId]['tellfriend_limit'];
         $this->_entityTable = 'civicrm_pcp';
         $this->_title = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PCP', $this->_entityId, 'title');
         $this->assign('context', 'pcp');
         $this->assign('pcpTitle', $this->_title);
     } else {
         CRM_Core_Error::fatal(ts('page argument missing or invalid'));
     }
     $session =& CRM_Core_Session::singleton();
     $this->_contactID = $session->get('userID');
     if (!$this->_contactID) {
         $this->_contactID = $session->get('transaction.userID');
     }
     if (!$this->_contactID) {
         CRM_Core_Error::fatal(ts('Could not get the contact ID'));
     }
     // we do not want to display recently viewed items, so turn off
     $this->assign('displayRecent', false);
 }
Exemplo n.º 3
0
 /**
  * Function to send the emails for Recurring Contribution Notication
  * 
  * @param string  $type         txnType 
  * @param int     $contactID    contact id for contributor
  * @param int     $pageID       contribution page id
  * @param object  $recur        object of recurring contribution table
  *
  * @return void
  * @access public
  * @static
  */
 static function recurringNofify($type, $contactID, $pageID, $recur)
 {
     $value = array();
     CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $pageID, $value, array('title', 'is_email_receipt', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt'));
     if ($value[$pageID]['is_email_receipt']) {
         $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$pageID]) . '" <' . $value[$pageID]['receipt_from_email'] . '>';
         require_once 'CRM/Contact/BAO/Contact/Location.php';
         list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, false);
         require_once 'CRM/Core/BAO/MessageTemplates.php';
         list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplateParams(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_recurring_notify', 'contactId' => $contactID, 'tplParams' => array('recur_frequency_interval' => $recur->frequency_interval, 'recur_frequency_unit' => $recur->frequency_unit, 'recur_installments' => $recur->installments, 'recur_start_date' => $recur->start_date, 'recur_end_date' => $recur->end_date, 'recur_amount' => $recur->amount, 'recur_txnType' => $type, 'displayName' => $displayName, 'receipt_from_name' => $value[$pageID]['receipt_from_name'], 'receipt_from_email' => $value[$pageID]['receipt_from_email']), 'from' => $receiptFrom, 'toName' => $displayName, 'toEmail' => $email));
         if ($sent) {
             CRM_Core_Error::debug_log_message('Success: mail sent for recurring notification.');
         } else {
             CRM_Core_Error::debug_log_message('Failure: mail not sent for recurring notification.');
         }
     }
 }
Exemplo n.º 4
0
 function updateRecurLinkedPledge(&$contribution)
 {
     $returnProperties = array('id', 'pledge_id');
     $paymentDetails = $paymentIDs = array();
     if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id, $paymentDetails, $returnProperties)) {
         foreach ($paymentDetails as $key => $value) {
             $paymentIDs[] = $value['id'];
             $pledgeId = $value['pledge_id'];
         }
     } else {
         //payment is not already linked - if it is linked with a pledge we need to create a link.
         // return if it is not recurring contribution
         if (!$contribution->contribution_recur_id) {
             return;
         }
         $relatedContributions = new CRM_Contribute_DAO_Contribution();
         $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
         $relatedContributions->find();
         while ($relatedContributions->fetch()) {
             CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id, $paymentDetails, $returnProperties);
         }
         if (empty($paymentDetails)) {
             // payment is not linked with a pledge and neither are any other contributions on this
             return;
         }
         foreach ($paymentDetails as $key => $value) {
             $pledgeId = $value['pledge_id'];
         }
         // we have a pledge now we need to get the oldest unpaid payment
         $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
         if (empty($paymentDetails['id'])) {
             // we can assume this pledge is now completed
             // return now so we don't create a core error & roll back
             return;
         }
         $paymentDetails['contribution_id'] = $contribution->id;
         $paymentDetails['status_id'] = $contribution->contribution_status_id;
         $paymentDetails['actual_amount'] = $contribution->total_amount;
         // put contribution against it
         $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
         $paymentIDs[] = $payment->id;
     }
     // update pledge and corresponding payment statuses
     CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id, NULL, $contribution->total_amount);
 }
Exemplo n.º 5
0
    /**
     * Function perform two task.
     * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
     * 2. Merge two cases of same contact - follow CRM-5598 rules.
     *
     * @param int $mainContactId contact id of main contact record.
     * @param int $mainCaseId case id of main case record.
     * @param int $otherContactId contact id of record which is going to merge.
     * @param int $otherCaseId case id of record which is going to merge.
     *
     * @param bool $changeClient
     *
     * @return integer|NULL
     * @static
     */
    static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL, $otherCaseId = NULL, $changeClient = FALSE)
    {
        $moveToTrash = TRUE;
        $duplicateContacts = FALSE;
        if ($mainContactId && $otherContactId && $mainContactId != $otherContactId) {
            $duplicateContacts = TRUE;
        }
        $duplicateCases = FALSE;
        if ($mainCaseId && $otherCaseId && $mainCaseId != $otherCaseId) {
            $duplicateCases = TRUE;
        }
        $mainCaseIds = array();
        if (!$duplicateContacts && !$duplicateCases) {
            return $mainCaseIds;
        }
        $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name');
        $activityStatuses = CRM_Core_PseudoConstant::activityStatus('name');
        $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
        $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
        $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
        $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
        $processCaseIds = array($otherCaseId);
        if ($duplicateContacts && !$duplicateCases) {
            if ($changeClient) {
                $processCaseIds = array($mainCaseId);
            } else {
                //get all case ids for other contact.
                $processCaseIds = self::retrieveCaseIdsByContactId($otherContactId, TRUE);
            }
            if (!is_array($processCaseIds)) {
                return;
            }
        }
        $session = CRM_Core_Session::singleton();
        $currentUserId = $session->get('userID');
        CRM_Utils_Hook::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
        // copy all cases and connect to main contact id.
        foreach ($processCaseIds as $otherCaseId) {
            if ($duplicateContacts) {
                $mainCase = CRM_Core_DAO::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
                $mainCaseId = $mainCase->id;
                if (!$mainCaseId) {
                    continue;
                }
                // CRM-11662 Copy Case custom data
                $extends = array('case');
                $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
                if ($groupTree) {
                    foreach ($groupTree as $groupID => $group) {
                        $table[$groupTree[$groupID]['table_name']] = array('entity_id');
                        foreach ($group['fields'] as $fieldID => $field) {
                            $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
                        }
                    }
                    foreach ($table as $tableName => $tableColumns) {
                        $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
                        $tableColumns[0] = $mainCaseId;
                        $select = 'SELECT ' . implode(', ', $tableColumns);
                        $from = ' FROM ' . $tableName;
                        $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
                        $query = $insert . $select . $from . $where;
                        $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
                    }
                }
                $mainCase->free();
                $mainCaseIds[] = $mainCaseId;
                //insert record for case contact.
                $otherCaseContact = new CRM_Case_DAO_CaseContact();
                $otherCaseContact->case_id = $otherCaseId;
                $otherCaseContact->find();
                while ($otherCaseContact->fetch()) {
                    $mainCaseContact = new CRM_Case_DAO_CaseContact();
                    $mainCaseContact->case_id = $mainCaseId;
                    $mainCaseContact->contact_id = $otherCaseContact->contact_id;
                    if ($mainCaseContact->contact_id == $otherContactId) {
                        $mainCaseContact->contact_id = $mainContactId;
                    }
                    //avoid duplicate object.
                    if (!$mainCaseContact->find(TRUE)) {
                        $mainCaseContact->save();
                    }
                    $mainCaseContact->free();
                }
                $otherCaseContact->free();
            } elseif (!$otherContactId) {
                $otherContactId = $mainContactId;
            }
            if (!$mainCaseId || !$otherCaseId || !$mainContactId || !$otherContactId) {
                continue;
            }
            // get all activities for other case.
            $otherCaseActivities = array();
            CRM_Core_DAO::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
            //for duplicate cases do not process singleton activities.
            $otherActivityIds = $singletonActivityIds = array();
            foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
                $otherActId = CRM_Utils_Array::value('activity_id', $otherIds);
                if (!$otherActId || in_array($otherActId, $otherActivityIds)) {
                    continue;
                }
                $otherActivityIds[] = $otherActId;
            }
            if ($duplicateCases) {
                if ($openCaseType = array_search('Open Case', $activityTypes)) {
                    $sql = "\nSELECT  id\n  FROM  civicrm_activity\n WHERE  activity_type_id = {$openCaseType}\n   AND  id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
                    $dao = CRM_Core_DAO::executeQuery($sql);
                    while ($dao->fetch()) {
                        $singletonActivityIds[] = $dao->id;
                    }
                    $dao->free();
                }
            }
            // migrate all activities and connect to main contact.
            $copiedActivityIds = $activityMappingIds = array();
            sort($otherActivityIds);
            foreach ($otherActivityIds as $otherActivityId) {
                //for duplicate cases -
                //do not migrate singleton activities.
                if (!$otherActivityId || in_array($otherActivityId, $singletonActivityIds)) {
                    continue;
                }
                //migrate activity record.
                $otherActivity = new CRM_Activity_DAO_Activity();
                $otherActivity->id = $otherActivityId;
                if (!$otherActivity->find(TRUE)) {
                    continue;
                }
                $mainActVals = array();
                $mainActivity = new CRM_Activity_DAO_Activity();
                CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
                $mainActivity->copyValues($mainActVals);
                $mainActivity->id = NULL;
                $mainActivity->activity_date_time = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
                $mainActivity->source_record_id = CRM_Utils_Array::value($mainActivity->source_record_id, $activityMappingIds);
                $mainActivity->original_id = CRM_Utils_Array::value($mainActivity->original_id, $activityMappingIds);
                $mainActivity->parent_id = CRM_Utils_Array::value($mainActivity->parent_id, $activityMappingIds);
                $mainActivity->save();
                $mainActivityId = $mainActivity->id;
                if (!$mainActivityId) {
                    continue;
                }
                $activityMappingIds[$otherActivityId] = $mainActivityId;
                // insert log of all activities
                CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
                $otherActivity->free();
                $mainActivity->free();
                $copiedActivityIds[] = $otherActivityId;
                //create case activity record.
                $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
                $mainCaseActivity->case_id = $mainCaseId;
                $mainCaseActivity->activity_id = $mainActivityId;
                $mainCaseActivity->save();
                $mainCaseActivity->free();
                //migrate source activity.
                $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
                $otherSourceActivity->activity_id = $otherActivityId;
                $otherSourceActivity->record_type_id = $sourceID;
                $otherSourceActivity->find();
                while ($otherSourceActivity->fetch()) {
                    $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
                    $mainActivitySource->record_type_id = $sourceID;
                    $mainActivitySource->activity_id = $mainActivityId;
                    $mainActivitySource->contact_id = $otherSourceActivity->contact_id;
                    if ($mainActivitySource->contact_id == $otherContactId) {
                        $mainActivitySource->contact_id = $mainContactId;
                    }
                    //avoid duplicate object.
                    if (!$mainActivitySource->find(TRUE)) {
                        $mainActivitySource->save();
                    }
                    $mainActivitySource->free();
                }
                $otherSourceActivity->free();
                //migrate target activities.
                $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
                $otherTargetActivity->activity_id = $otherActivityId;
                $otherTargetActivity->record_type_id = $targetID;
                $otherTargetActivity->find();
                while ($otherTargetActivity->fetch()) {
                    $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
                    $mainActivityTarget->record_type_id = $targetID;
                    $mainActivityTarget->activity_id = $mainActivityId;
                    $mainActivityTarget->contact_id = $otherTargetActivity->contact_id;
                    if ($mainActivityTarget->contact_id == $otherContactId) {
                        $mainActivityTarget->contact_id = $mainContactId;
                    }
                    //avoid duplicate object.
                    if (!$mainActivityTarget->find(TRUE)) {
                        $mainActivityTarget->save();
                    }
                    $mainActivityTarget->free();
                }
                $otherTargetActivity->free();
                //migrate assignee activities.
                $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
                $otherAssigneeActivity->activity_id = $otherActivityId;
                $otherAssigneeActivity->record_type_id = $assigneeID;
                $otherAssigneeActivity->find();
                while ($otherAssigneeActivity->fetch()) {
                    $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
                    $mainAssigneeActivity->activity_id = $mainActivityId;
                    $mainAssigneeActivity->record_type_id = $assigneeID;
                    $mainAssigneeActivity->contact_id = $otherAssigneeActivity->contact_id;
                    if ($mainAssigneeActivity->contact_id == $otherContactId) {
                        $mainAssigneeActivity->contact_id = $mainContactId;
                    }
                    //avoid duplicate object.
                    if (!$mainAssigneeActivity->find(TRUE)) {
                        $mainAssigneeActivity->save();
                    }
                    $mainAssigneeActivity->free();
                }
                $otherAssigneeActivity->free();
                // copy custom fields and attachments
                $aparams = array('activityID' => $otherActivityId, 'mainActivityId' => $mainActivityId);
                CRM_Activity_BAO_Activity::copyExtendedActivityData($aparams);
            }
            //copy case relationship.
            if ($duplicateContacts) {
                //migrate relationship records.
                $otherRelationship = new CRM_Contact_DAO_Relationship();
                $otherRelationship->case_id = $otherCaseId;
                $otherRelationship->find();
                $otherRelationshipIds = array();
                while ($otherRelationship->fetch()) {
                    $otherRelVals = array();
                    $updateOtherRel = FALSE;
                    CRM_Core_DAO::storeValues($otherRelationship, $otherRelVals);
                    $mainRelationship = new CRM_Contact_DAO_Relationship();
                    $mainRelationship->copyValues($otherRelVals);
                    $mainRelationship->id = NULL;
                    $mainRelationship->case_id = $mainCaseId;
                    if ($mainRelationship->contact_id_a == $otherContactId) {
                        $updateOtherRel = TRUE;
                        $mainRelationship->contact_id_a = $mainContactId;
                    }
                    //case creator change only when we merge user contact.
                    if ($mainRelationship->contact_id_b == $otherContactId) {
                        //do not change creator for change client.
                        if (!$changeClient) {
                            $updateOtherRel = TRUE;
                            $mainRelationship->contact_id_b = $currentUserId ? $currentUserId : $mainContactId;
                        }
                    }
                    $mainRelationship->end_date = CRM_Utils_Date::isoToMysql($otherRelationship->end_date);
                    $mainRelationship->start_date = CRM_Utils_Date::isoToMysql($otherRelationship->start_date);
                    //avoid duplicate object.
                    if (!$mainRelationship->find(TRUE)) {
                        $mainRelationship->save();
                    }
                    $mainRelationship->free();
                    //get the other relationship ids to update end date.
                    if ($updateOtherRel) {
                        $otherRelationshipIds[$otherRelationship->id] = $otherRelationship->id;
                    }
                }
                $otherRelationship->free();
                //update other relationships end dates
                if (!empty($otherRelationshipIds)) {
                    $sql = 'UPDATE  civicrm_relationship
                               SET  end_date = CURDATE()
                             WHERE  id IN ( ' . implode(',', $otherRelationshipIds) . ')';
                    CRM_Core_DAO::executeQuery($sql);
                }
            }
            //move other case to trash.
            $mergeCase = self::deleteCase($otherCaseId, $moveToTrash);
            if (!$mergeCase) {
                continue;
            }
            $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
            if ($changeClient) {
                $mainContactDisplayName = CRM_Contact_BAO_Contact::displayName($mainContactId);
                $otherContactDisplayName = CRM_Contact_BAO_Contact::displayName($otherContactId);
                $mergeActType = array_search('Reassigned Case', $activityTypes);
                $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.", array(1 => $otherCaseId, 2 => $otherContactDisplayName, 3 => $mainContactDisplayName, 4 => $mainCaseId));
            } elseif ($duplicateContacts) {
                $mergeActType = array_search('Merge Case', $activityTypes);
                $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.", array(1 => $otherCaseId, 2 => $otherContactId, 3 => $mainContactId, 4 => $mainCaseId));
            } else {
                $mergeActType = array_search('Merge Case', $activityTypes);
                $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
                if (!empty($copiedActivityIds)) {
                    $sql = '
SELECT id, subject, activity_date_time, activity_type_id
FROM civicrm_activity
WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
                    $dao = CRM_Core_DAO::executeQuery($sql);
                    while ($dao->fetch()) {
                        $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
                        if ($dao->subject) {
                            $mergeActSubjectDetails .= " :: {$dao->subject}";
                        }
                        $mergeActSubjectDetails .= "<br />";
                    }
                }
            }
            //create merge activity record.
            $activityParams = array('subject' => $mergeActSubject, 'details' => $mergeActSubjectDetails, 'status_id' => array_search('Completed', $activityStatuses), 'activity_type_id' => $mergeActType, 'source_contact_id' => $mainContactId, 'activity_date_time' => date('YmdHis'));
            $mergeActivity = CRM_Activity_BAO_Activity::create($activityParams);
            $mergeActivityId = $mergeActivity->id;
            if (!$mergeActivityId) {
                continue;
            }
            $mergeActivity->free();
            //connect merge activity to case.
            $mergeCaseAct = array('case_id' => $mainCaseId, 'activity_id' => $mergeActivityId);
            self::processCaseActivity($mergeCaseAct);
        }
        CRM_Utils_Hook::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
        return $mainCaseIds;
    }
Exemplo n.º 6
0
 /**
  * This function sets the default values for the form in edit/view mode
  * the default values are retrieved from the database
  *
  *
  * @param CRM_Core_Form $form
  *
  * @return void
  */
 public static function setDefaultValues(&$form)
 {
     $defaults = array();
     if ($form->_eventId) {
         //get receipt text and financial type
         $returnProperities = array('confirm_email_text', 'financial_type_id', 'campaign_id', 'start_date');
         $details = array();
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $form->_eventId, $details, $returnProperities);
         if (!empty($details[$form->_eventId]['financial_type_id'])) {
             $defaults[$form->_pId]['financial_type_id'] = $details[$form->_eventId]['financial_type_id'];
         }
     }
     if ($form->_pId) {
         $ids = array();
         $params = array('id' => $form->_pId);
         CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
         if ($form->_action == CRM_Core_Action::UPDATE) {
             $discounts = array();
             if (!empty($form->_values['discount'])) {
                 foreach ($form->_values['discount'] as $key => $value) {
                     $value = current($value);
                     $discounts[$key] = $value['name'];
                 }
             }
             if ($form->_discountId && !empty($discounts[$defaults[$form->_pId]['discount_id']])) {
                 $form->assign('discount', $discounts[$defaults[$form->_pId]['discount_id']]);
             }
             $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
             $form->assign('fee_level', CRM_Utils_Array::value('fee_level', $defaults[$form->_pId]));
         }
         $defaults[$form->_pId]['send_receipt'] = 0;
     } else {
         $defaults[$form->_pId]['send_receipt'] = strtotime(CRM_Utils_Array::value('start_date', $details[$form->_eventId])) >= time() ? 1 : 0;
         if ($form->_eventId && !empty($details[$form->_eventId]['confirm_email_text'])) {
             //set receipt text
             $defaults[$form->_pId]['receipt_text'] = $details[$form->_eventId]['confirm_email_text'];
         }
         list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults();
     }
     //CRM-11601 we should keep the record contribution
     //true by default while adding participant
     if ($form->_action == CRM_Core_Action::ADD && !$form->_mode && $form->_isPaidEvent) {
         $defaults[$form->_pId]['record_contribution'] = 1;
     }
     //CRM-13420
     if (empty($defaults['payment_instrument_id'])) {
         $defaults[$form->_pId]['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
     }
     if ($form->_mode) {
         $config = CRM_Core_Config::singleton();
         // set default country from config if no country set
         if (empty($defaults[$form->_pId]["billing_country_id-{$form->_bltID}"])) {
             $defaults[$form->_pId]["billing_country_id-{$form->_bltID}"] = $config->defaultContactCountry;
         }
         if (empty($defaults["billing_state_province_id-{$form->_bltID}"])) {
             $defaults[$form->_pId]["billing_state_province_id-{$form->_bltID}"] = $config->defaultContactStateProvince;
         }
         $billingDefaults = $form->getProfileDefaults('Billing', $form->_contactId);
         $defaults[$form->_pId] = array_merge($defaults[$form->_pId], $billingDefaults);
         //             // hack to simplify credit card entry for testing
         //             $defaults[$form->_pId]['credit_card_type']     = 'Visa';
         //             $defaults[$form->_pId]['credit_card_number']   = '4807731747657838';
         //             $defaults[$form->_pId]['cvv2']                 = '000';
         //             $defaults[$form->_pId]['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
     }
     // if user has selected discount use that to set default
     if (isset($form->_discountId)) {
         $defaults[$form->_pId]['discount_id'] = $form->_discountId;
         //hack to set defaults for already selected discount value
         if ($form->_action == CRM_Core_Action::UPDATE && !$form->_originalDiscountId) {
             $form->_originalDiscountId = $defaults[$form->_pId]['discount_id'];
             if ($form->_originalDiscountId) {
                 $defaults[$form->_pId]['discount_id'] = $form->_originalDiscountId;
             }
         }
         $discountId = $form->_discountId;
     } else {
         $discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
     }
     if ($discountId) {
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
     } else {
         $priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $form->_eventId);
     }
     if ($form->_action == CRM_Core_Action::ADD && $form->_eventId && $discountId) {
         // this case is for add mode, where we show discount automatically
         $defaults[$form->_pId]['discount_id'] = $discountId;
     }
     if ($priceSetId) {
         // get price set default values, CRM-4090
         if (in_array(get_class($form), array('CRM_Event_Form_Participant', 'CRM_Event_Form_Registration_Register', 'CRM_Event_Form_Registration_AdditionalParticipant'))) {
             $priceSetValues = self::setDefaultPriceSet($form->_pId, $form->_eventId);
             if (!empty($priceSetValues)) {
                 $defaults[$form->_pId] = array_merge($defaults[$form->_pId], $priceSetValues);
             }
         }
         if ($form->_action == CRM_Core_Action::ADD && !empty($form->_priceSet['fields'])) {
             foreach ($form->_priceSet['fields'] as $key => $val) {
                 foreach ($val['options'] as $keys => $values) {
                     if ($values['is_default']) {
                         if (get_class($form) != 'CRM_Event_Form_Participant' && !empty($values['is_full'])) {
                             continue;
                         }
                         if ($val['html_type'] == 'CheckBox') {
                             $defaults[$form->_pId]["price_{$key}"][$keys] = 1;
                         } else {
                             $defaults[$form->_pId]["price_{$key}"] = $keys;
                         }
                     }
                 }
             }
         }
         $form->assign('totalAmount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
         if ($form->_action == CRM_Core_Action::UPDATE) {
             $fee_level = $defaults[$form->_pId]['fee_level'];
             CRM_Event_BAO_Participant::fixEventLevel($fee_level);
             $form->assign('fee_level', $fee_level);
             $form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
         }
     }
     //CRM-4453
     if (!empty($defaults[$form->_pId]['participant_fee_currency'])) {
         $form->assign('fee_currency', $defaults[$form->_pId]['participant_fee_currency']);
     }
     // CRM-4395
     if ($contriId = $form->get('onlinePendingContributionId')) {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->id = $contriId;
         $contribution->find(TRUE);
         foreach (array('financial_type_id', 'payment_instrument_id', 'contribution_status_id', 'receive_date', 'total_amount') as $f) {
             if ($f == 'receive_date') {
                 list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults($contribution->{$f});
             } else {
                 $defaults[$form->_pId][$f] = $contribution->{$f};
             }
         }
     }
     return $defaults[$form->_pId];
 }
Exemplo n.º 7
0
 /**
  * Function to send Acknowledgment and create activity.
  *
  * @param object $form form object.
  * @param array  $params (reference ) an assoc array of name/value pairs.
  * @access public
  *
  * @return None.
  */
 function sendAcknowledgment(&$form, $params)
 {
     //handle Acknowledgment.
     $allPayments = $payments = array();
     //get All Payments status types.
     $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $returnProperties = array('status_id', 'scheduled_amount', 'scheduled_date', 'contribution_id');
     //get all paymnets details.
     CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $params['id'], $allPayments, $returnProperties);
     if (!empty($allPayments)) {
         foreach ($allPayments as $payID => $values) {
             $contributionValue = $contributionStatus = array();
             if (isset($values['contribution_id'])) {
                 $contributionParams = array('id' => $values['contribution_id']);
                 $returnProperties = array('contribution_status_id', 'receive_date');
                 CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_Contribution', $contributionParams, $contributionStatus, $returnProperties);
                 $contributionValue = array('status' => CRM_Utils_Array::value('contribution_status_id', $contributionStatus), 'receive_date' => CRM_Utils_Array::value('receive_date', $contributionStatus));
             }
             $payments[$payID] = array_merge($contributionValue, array('amount' => CRM_Utils_Array::value('scheduled_amount', $values), 'due_date' => CRM_Utils_Array::value('scheduled_date', $values)));
             //get the first valid payment id.
             if (!isset($form->paymentId) && ($paymentStatusTypes[$values['status_id']] == 'Pending' || $paymentStatusTypes[$values['status_id']] == 'Overdue')) {
                 $form->paymentId = $values['id'];
             }
         }
     }
     //end
     //assign pledge fields value to template.
     $pledgeFields = array('create_date', 'total_pledge_amount', 'frequency_interval', 'frequency_unit', 'installments', 'frequency_day', 'scheduled_amount', 'currency');
     foreach ($pledgeFields as $field) {
         if (CRM_Utils_Array::value($field, $params)) {
             $form->assign($field, $params[$field]);
         }
     }
     //assign all payments details.
     if ($payments) {
         $form->assign('payments', $payments);
     }
     //assign honor fields.
     $honor_block_is_active = FALSE;
     //make sure we have values for it
     if (CRM_Utils_Array::value('honor_type_id', $params) && (!empty($params['honor_first_name']) && !empty($params['honor_last_name']) || !empty($params['honor_email']))) {
         $honor_block_is_active = TRUE;
         $prefix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id');
         $honor = CRM_Core_PseudoConstant::get('CRM_Pledge_DAO_Pledge', 'honor_type_id');
         $form->assign('honor_type', $honor[$params['honor_type_id']]);
         $form->assign('honor_prefix', $prefix[$params['honor_prefix_id']]);
         $form->assign('honor_first_name', $params['honor_first_name']);
         $form->assign('honor_last_name', $params['honor_last_name']);
         $form->assign('honor_email', $params['honor_email']);
     }
     $form->assign('honor_block_is_active', $honor_block_is_active);
     //handle domain token values
     $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);
     }
     $form->assign('domain', $domainValues);
     //handle contact token values.
     $ids = array($params['contact_id']);
     $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::importableFields()), array('display_name', 'checksum', 'contact_id'));
     foreach ($fields as $key => $val) {
         $returnProperties[$val] = TRUE;
     }
     $details = CRM_Utils_Token::getTokenDetails($ids, $returnProperties, TRUE, TRUE, NULL, $tokens, get_class($form));
     $form->assign('contact', $details[0][$params['contact_id']]);
     //handle custom data.
     if (CRM_Utils_Array::value('hidden_custom', $params)) {
         $groupTree = CRM_Core_BAO_CustomGroup::getTree('Pledge', CRM_Core_DAO::$_nullObject, $params['id']);
         $pledgeParams = array(array('pledge_id', '=', $params['id'], 0, 0));
         $customGroup = array();
         // retrieve custom data
         foreach ($groupTree as $groupID => $group) {
             $customFields = $customValues = array();
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
             //to build array of customgroup & customfields in it
             CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $pledgeParams);
             $customGroup[$group['title']] = $customValues;
         }
         $form->assign('customGroup', $customGroup);
     }
     //handle acknowledgment email stuff.
     list($pledgerDisplayName, $pledgerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
     //check for online pledge.
     $session = CRM_Core_Session::singleton();
     if (CRM_Utils_Array::value('receipt_from_email', $params)) {
         $userName = CRM_Utils_Array::value('receipt_from_name', $params);
         $userEmail = CRM_Utils_Array::value('receipt_from_email', $params);
     } elseif (CRM_Utils_Array::value('from_email_id', $params)) {
         $receiptFrom = $params['from_email_id'];
     } elseif ($userID = $session->get('userID')) {
         //check for loged in user.
         list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     } else {
         //set the domain values.
         $userName = CRM_Utils_Array::value('name', $domainValues);
         $userEmail = CRM_Utils_Array::value('email', $domainValues);
     }
     if (!isset($receiptFrom)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
     }
     list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_pledge', 'valueName' => 'pledge_acknowledge', 'contactId' => $params['contact_id'], 'from' => $receiptFrom, 'toName' => $pledgerDisplayName, 'toEmail' => $pledgerEmail));
     //check if activity record exist for this pledge
     //Acknowledgment, if exist do not add activity.
     $activityType = 'Pledge Acknowledgment';
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $params['id'];
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name');
     $config = CRM_Core_Config::singleton();
     $details = 'Total Amount ' . CRM_Utils_Money::format($params['total_pledge_amount'], CRM_Utils_Array::value('currency', $params)) . ' To be paid in ' . $params['installments'] . ' installments of ' . CRM_Utils_Money::format($params['scheduled_amount'], CRM_Utils_Array::value('currency', $params)) . ' every ' . $params['frequency_interval'] . ' ' . $params['frequency_unit'] . '(s)';
     if (!$activity->find()) {
         $activityParams = array('subject' => $subject, 'source_contact_id' => $params['contact_id'], 'source_record_id' => $params['id'], 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($params['acknowledge_date']), 'is_test' => $params['is_test'], 'status_id' => 2, 'details' => $details, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params));
         //lets insert assignee record.
         if (CRM_Utils_Array::value('contact_id', $params)) {
             $activityParams['assignee_contact_id'] = $params['contact_id'];
         }
         if (is_a(CRM_Activity_BAO_Activity::create($activityParams), 'CRM_Core_Error')) {
             CRM_Core_Error::fatal("Failed creating Activity for acknowledgment");
         }
     }
 }
Exemplo n.º 8
0
 /**
  * Calculate the pledge status.
  *
  * @param int $pledgeId
  *   Pledge id.
  *
  * @return int
  *   $statusId calculated status id of pledge
  */
 public static function calculatePledgeStatus($pledgeId)
 {
     $paymentStatusTypes = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     // retrieve all pledge payments for this particular pledge
     $allPledgePayments = $allStatus = array();
     $returnProperties = array('status_id');
     CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $pledgeId, $allPledgePayments, $returnProperties);
     // build pledge payment statuses
     foreach ($allPledgePayments as $key => $value) {
         $allStatus[$value['id']] = $paymentStatusTypes[$value['status_id']];
     }
     if (array_search('Overdue', $allStatus)) {
         $statusId = array_search('Overdue', $paymentStatusTypes);
     } elseif (array_search('Completed', $allStatus)) {
         if (count(array_count_values($allStatus)) == 1) {
             $statusId = array_search('Completed', $paymentStatusTypes);
         } else {
             $statusId = array_search('In Progress', $paymentStatusTypes);
         }
     } else {
         $statusId = array_search('Pending', $paymentStatusTypes);
     }
     return $statusId;
 }
Exemplo n.º 9
0
 /** 
  * Function to build the form 
  * 
  * @return None 
  * @access public 
  */
 public function buildQuickForm()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if ($this->_context == 'standalone') {
         require_once 'CRM/Contact/Form/NewContact.php';
         CRM_Contact_Form_NewContact::buildQuickForm($this);
     }
     $showAdditionalInfo = false;
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     //fix to load honoree pane on edit.
     $defaults = array();
     if ($this->_honorID) {
         $defaults['hidden_Honoree'] = 1;
     }
     $paneNames = array('Honoree Information' => 'Honoree', 'Payment Reminders' => 'PaymentReminders');
     foreach ($paneNames as $name => $type) {
         $urlParams = "snippet=4&formType={$type}";
         $allPanes[$name] = array('url' => CRM_Utils_System::url('civicrm/contact/view/pledge', $urlParams), 'open' => 'false', 'id' => $type);
         //see if we need to include this paneName in the current form
         if ($this->_formType == $type || CRM_Utils_Array::value("hidden_{$type}", $_POST) || CRM_Utils_Array::value("hidden_{$type}", $defaults)) {
             $showAdditionalInfo = true;
             $allPanes[$name]['open'] = 'true';
         }
         eval('CRM_Contribute_Form_AdditionalInfo::build' . $type . '( $this );');
     }
     $this->assign('allPanes', $allPanes);
     $this->assign('showAdditionalInfo', $showAdditionalInfo);
     if ($this->_formType) {
         $this->assign('formType', $this->_formType);
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     //pledge fields.
     $attributes = CRM_Core_DAO::getAttribute('CRM_Pledge_DAO_Pledge');
     $this->assign('isPending', $this->_isPending);
     $js = array('onblur' => "calculatedPaymentAmount( );", 'onkeyup' => "calculatedPaymentAmount( );");
     $element =& $this->add('text', 'amount', ts('Total Pledge Amount'), array_merge($attributes['pledge_amount'], $js), true);
     $this->addRule('amount', ts('Please enter a valid monetary amount.'), 'money');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'installments', ts('To be paid in'), array_merge($attributes['installments'], $js), true);
     $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'frequency_interval', ts('every'), $attributes['frequency_interval'], true);
     $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     // Fix frequency unit display for use with frequency_interval
     $freqUnitsDisplay = array();
     foreach ($this->_freqUnits as $val => $label) {
         $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $val));
     }
     $element =& $this->add('select', 'frequency_unit', ts('Frequency'), array('' => ts('- select -')) + $freqUnitsDisplay, true);
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], true);
     $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 'READONLY'));
     //add various dates
     if (!$this->_id || $this->_isPending) {
         $this->addDate('create_date', ts('Pledge Made'));
         $this->addDate('start_date', ts('Payments Start'));
     }
     if ($this->_id && !$this->_isPending) {
         $eachPaymentAmount = floor($this->_values['amount'] / $this->_values['installments']);
         $this->assign("eachPaymentAmount", $eachPaymentAmount);
         $this->assign("hideCalender", true);
     }
     if (CRM_Utils_Array::value('status_id', $this->_values) != array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus())) {
         $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), null, array('onclick' => "return showHideByValue('is_acknowledge','','acknowledgeDate','table-row','radio',true);"));
     }
     $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
     $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType(), true);
     $pageIds = array();
     CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table', 'civicrm_contribution_page', $pageIds, array('entity_id'));
     $pages = CRM_Contribute_PseudoConstant::contributionPage();
     $pledgePages = array();
     foreach ($pageIds as $key => $value) {
         $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
     }
     $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'), array('' => ts('- select -')) + $pledgePages);
     require_once "CRM/Core/BAO/Preferences.php";
     $mailingInfo =& CRM_Core_BAO_Preferences::mailingPreferences();
     $this->assign('outBound_option', $mailingInfo['outBound_option']);
     //build custom data
     CRM_Custom_Form_Customdata::buildQuickForm($this);
     // make this form an upload since we dont know if the custom data injected dynamically
     // is of type file etc $uploadNames = $this->get( 'uploadNames' );
     $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save'), 'js' => array('onclick' => "return verify( );"), 'isDefault' => true), array('type' => 'upload', 'name' => ts('Save and New'), 'js' => array('onclick' => "return verify( );"), 'subName' => 'new'), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->freeze();
     }
 }
Exemplo n.º 10
0
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = false)
 {
     $contribution =& $objects['contribution'];
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $values = array();
     if ($input['component'] == 'contribute') {
         require_once 'CRM/Contribute/BAO/ContributionPage.php';
         CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
         $contribution->source = ts('Online Contribution') . ': ' . $values['title'];
         if ($values['is_email_receipt']) {
             $contribution->receipt_date = self::$_now;
         }
         if ($membership) {
             $format = '%Y%m%d';
             require_once 'CRM/Member/BAO/MembershipType.php';
             require_once 'CRM/Member/BAO/Membership.php';
             $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
             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 = 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, 2), '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);
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         require_once 'CRM/Event/BAO/Event.php';
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         require_once 'CRM/Event/BAO/Event.php';
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         require_once 'CRM/Core/BAO/Location.php';
         require_once 'CRM/Event/Form/ManageEvent/Location.php';
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         require_once 'CRM/Core/BAO/UFJoin.php';
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'weight' => 1);
         $values['custom_pre_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
         $ufJoinParams['weight'] = 2;
         $values['custom_post_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
         }
         $participant->status_id = 1;
         $participant->save();
     }
     if ($input['net_amount'] == 0 && $input['fee_amount'] != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     $contribution->contribution_status_id = 1;
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = $input['fee_amount'];
     $contribution->net_amount = $input['net_amount'];
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_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();
     // next create the transaction record
     if (isset($objects['paymentProcessor'])) {
         $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
     } else {
         $paymentProcessor = '';
     }
     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);
         require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
         $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
     }
     //update corresponding pledge payment record
     require_once 'CRM/Core/DAO.php';
     $returnProperties = array('id', 'pledge_id');
     if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_Payment', 'contribution_id', $contribution->id, $paymentDetails, $returnProperties)) {
         $paymentIDs = array();
         foreach ($paymentDetails as $key => $value) {
             $paymentIDs[] = $value['id'];
             $pledgeId = $value['pledge_id'];
         }
         // update pledge and corresponding payment statuses
         require_once 'CRM/Pledge/BAO/Payment.php';
         CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id);
     }
     // create an activity record
     require_once "CRM/Activity/BAO/Activity.php";
     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);
     } else {
         // event
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     self::sendMail($input, $ids, $objects, $values, $recur, false);
     CRM_Core_Error::debug_log_message("Success: Database updated and mail sent");
 }
Exemplo n.º 11
0
 /**
  * Build Pledge Block in Contribution Pages.
  *
  * @param CRM_Core_Form $form
  */
 public static function buildPledgeBlock($form)
 {
     //build pledge payment fields.
     if (!empty($form->_values['pledge_id'])) {
         //get all payments required details.
         $allPayments = array();
         $returnProperties = array('status_id', 'scheduled_date', 'scheduled_amount', 'currency', 'pledge_start_date');
         CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'pledge_id', $form->_values['pledge_id'], $allPayments, $returnProperties);
         // get all status
         $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         $nextPayment = array();
         $isNextPayment = FALSE;
         $overduePayments = array();
         foreach ($allPayments as $payID => $value) {
             if ($allStatus[$value['status_id']] == 'Overdue') {
                 $overduePayments[$payID] = array('id' => $payID, 'scheduled_amount' => CRM_Utils_Rule::cleanMoney($value['scheduled_amount']), 'scheduled_amount_currency' => $value['currency'], 'scheduled_date' => CRM_Utils_Date::customFormat($value['scheduled_date'], '%B %d'));
             } elseif (!$isNextPayment && $allStatus[$value['status_id']] == 'Pending') {
                 // get the next payment.
                 $nextPayment = array('id' => $payID, 'scheduled_amount' => CRM_Utils_Rule::cleanMoney($value['scheduled_amount']), 'scheduled_amount_currency' => $value['currency'], 'scheduled_date' => CRM_Utils_Date::customFormat($value['scheduled_date'], '%B %d'));
                 $isNextPayment = TRUE;
             }
         }
         // build check box array for payments.
         $payments = array();
         if (!empty($overduePayments)) {
             foreach ($overduePayments as $id => $payment) {
                 $label = ts("%1 - due on %2 (overdue)", array(1 => CRM_Utils_Money::format(CRM_Utils_Array::value('scheduled_amount', $payment), CRM_Utils_Array::value('scheduled_amount_currency', $payment)), 2 => CRM_Utils_Array::value('scheduled_date', $payment)));
                 $paymentID = CRM_Utils_Array::value('id', $payment);
                 $payments[] = $form->createElement('checkbox', $paymentID, NULL, $label, array('amount' => CRM_Utils_Array::value('scheduled_amount', $payment)));
             }
         }
         if (!empty($nextPayment)) {
             $label = ts("%1 - due on %2", array(1 => CRM_Utils_Money::format(CRM_Utils_Array::value('scheduled_amount', $nextPayment), CRM_Utils_Array::value('scheduled_amount_currency', $nextPayment)), 2 => CRM_Utils_Array::value('scheduled_date', $nextPayment)));
             $paymentID = CRM_Utils_Array::value('id', $nextPayment);
             $payments[] = $form->createElement('checkbox', $paymentID, NULL, $label, array('amount' => CRM_Utils_Array::value('scheduled_amount', $nextPayment)));
         }
         // give error if empty or build form for payment.
         if (empty($payments)) {
             CRM_Core_Error::fatal(ts("Oops. It looks like there is no valid payment status for online payment."));
         } else {
             $form->assign('is_pledge_payment', TRUE);
             $form->addGroup($payments, 'pledge_amount', ts('Make Pledge Payment(s):'), '<br />');
         }
     } else {
         $pledgeBlock = self::getPledgeBlock($form->_id);
         // build form for pledge creation.
         $pledgeOptions = array('0' => ts('I want to make a one-time contribution'), '1' => ts('I pledge to contribute this amount every'));
         $form->addRadio('is_pledge', ts('Pledge Frequency Interval'), $pledgeOptions, NULL, array('<br/>'));
         $form->addElement('text', 'pledge_installments', ts('Installments'), array('size' => 3));
         if (!empty($pledgeBlock['is_pledge_interval'])) {
             $form->assign('is_pledge_interval', CRM_Utils_Array::value('is_pledge_interval', $pledgeBlock));
             $form->addElement('text', 'pledge_frequency_interval', NULL, array('size' => 3));
         } else {
             $form->add('hidden', 'pledge_frequency_interval', 1);
         }
         // Frequency unit drop-down label suffixes switch from *ly to *(s)
         $freqUnitVals = explode(CRM_Core_DAO::VALUE_SEPARATOR, $pledgeBlock['pledge_frequency_unit']);
         $freqUnits = array();
         $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units');
         foreach ($freqUnitVals as $key => $val) {
             if (array_key_exists($val, $frequencyUnits)) {
                 $freqUnits[$val] = !empty($pledgeBlock['is_pledge_interval']) ? "{$frequencyUnits[$val]}(s)" : $frequencyUnits[$val];
             }
         }
         $form->addElement('select', 'pledge_frequency_unit', NULL, $freqUnits);
         // CRM-18854
         if (CRM_Utils_Array::value('is_pledge_start_date_visible', $pledgeBlock)) {
             if (CRM_Utils_Array::value('pledge_start_date', $pledgeBlock)) {
                 $defaults = array();
                 $date = (array) json_decode($pledgeBlock['pledge_start_date']);
                 list($field, $value) = each($date);
                 switch ($field) {
                     case 'contribution_date':
                         $form->addDate('start_date', ts('First installment payment'));
                         $paymentDate = $value = date('d/m/Y');
                         list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value);
                         $form->assign('is_date', TRUE);
                         break;
                     case 'calendar_date':
                         $form->addDate('start_date', ts('First installment payment'));
                         list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($value);
                         $form->assign('is_date', TRUE);
                         $paymentDate = $value;
                         break;
                     case 'calendar_month':
                         $month = CRM_Utils_Date::getCalendarDayOfMonth();
                         $form->add('select', 'start_date', ts('Day of month installments paid'), $month);
                         $paymentDate = CRM_Pledge_BAO_Pledge::getPaymentDate($value);
                         list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($paymentDate);
                         break;
                     default:
                         break;
                 }
                 $form->setDefaults($defaults);
                 $form->assign('start_date_display', $paymentDate);
                 $form->assign('start_date_editable', FALSE);
                 if (CRM_Utils_Array::value('is_pledge_start_date_editable', $pledgeBlock)) {
                     $form->assign('start_date_editable', TRUE);
                     if ($field == 'calendar_month') {
                         $form->assign('is_date', FALSE);
                         $form->setDefaults(array('start_date' => $value));
                     }
                 }
             }
         }
     }
 }
 /**
  * @param $params
  *
  * @return mixed
  */
 function emailReceipt(&$params)
 {
     $updatedLineItem = CRM_Price_BAO_LineItem::getLineItems($this->_participantId, 'participant', NULL, FALSE);
     $lineItem = array();
     if ($updatedLineItem) {
         $lineItem[] = $updatedLineItem;
     }
     $this->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
     // offline receipt sending
     if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
         $receiptFrom = $params['from_email_address'];
     }
     $this->assign('module', 'Event Registration');
     //use of the message template below requires variables in different format
     $event = $events = array();
     $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
     //get all event details.
     CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
     $event = $events[$params['event_id']];
     unset($event['start_date']);
     unset($event['end_date']);
     $role = CRM_Event_PseudoConstant::participantRole();
     $participantRoles = CRM_Utils_Array::value('role_id', $params);
     if (is_array($participantRoles)) {
         $selectedRoles = array();
         foreach (array_keys($participantRoles) as $roleId) {
             $selectedRoles[] = $role[$roleId];
         }
         $event['participant_role'] = implode(', ', $selectedRoles);
     } else {
         $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
     }
     $event['is_monetary'] = $this->_isPaidEvent;
     if ($params['receipt_text']) {
         $event['confirm_email_text'] = $params['receipt_text'];
     }
     $this->assign('isAmountzero', 1);
     $this->assign('event', $event);
     $this->assign('isShowLocation', $event['is_show_location']);
     if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
         $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
         $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
         $this->assign('location', $location);
     }
     $status = CRM_Event_PseudoConstant::participantStatus();
     if ($this->_isPaidEvent) {
         $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
         if (!$this->_mode) {
             if (isset($params['payment_instrument_id'])) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
         }
         $this->assign('totalAmount', $this->contributionAmt);
         $this->assign('isPrimary', 1);
         $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
     }
     $this->assign('register_date', $params['register_date']);
     $template = CRM_Core_Smarty::singleton();
     // Retrieve the name and email of the contact - this will be the TO for receipt email
     list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
     $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
     if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
         $this->assign('isOnWaitlist', TRUE);
     }
     $this->assign('contactID', $this->_contactId);
     $this->assign('participantID', $this->_participantId);
     $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $this->_contactId, 'isTest' => FALSE, 'PDFFilename' => ts('confirmation') . '.pdf');
     // try to send emails only if email id is present
     // and the do-not-email option is not checked for that contact
     if ($this->_contributorEmail && !$this->_toDoNotEmail) {
         $sendTemplateParams['from'] = $receiptFrom;
         $sendTemplateParams['toName'] = $this->_contributorDisplayName;
         $sendTemplateParams['toEmail'] = $this->_contributorEmail;
         $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
         $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
     }
     list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
     return $mailSent;
 }
Exemplo n.º 13
0
 /**
  * Process the form.
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $status = NULL;
     // now set the values for the billing location.
     foreach ($this->_fields as $name => $value) {
         $fields[$name] = 1;
     }
     $fields["email-{$this->_bltID}"] = 1;
     $processorParams = array();
     foreach ($params as $key => $val) {
         $key = str_replace('billing_', '', $key);
         list($key) = explode('-', $key);
         $processorParams[$key] = $val;
     }
     $processorParams['state_province'] = CRM_Core_PseudoConstant::stateProvince($params["billing_state_province_id-{$this->_bltID}"], FALSE);
     $processorParams['country'] = CRM_Core_PseudoConstant::country($params["billing_country_id-{$this->_bltID}"], FALSE);
     $processorParams['month'] = $processorParams['credit_card_exp_date']['M'];
     $processorParams['year'] = $processorParams['credit_card_exp_date']['Y'];
     $processorParams['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
     $processorParams['amount'] = $this->_subscriptionDetails->amount;
     $updateSubscription = $this->_paymentProcessorObj->updateSubscriptionBillingInfo($message, $processorParams);
     if (is_a($updateSubscription, 'CRM_Core_Error')) {
         CRM_Core_Error::displaySessionError($updateSubscription);
     } elseif ($updateSubscription) {
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_subscriptionDetails->contact_id, 'contact_type');
         $contact =& CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_subscriptionDetails->contact_id, NULL, NULL, $ctype);
         // build tpl params
         if ($this->_subscriptionDetails->membership_id) {
             $inputParams = array('id' => $this->_subscriptionDetails->membership_id);
             CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
             $tplParams = $tplParams[$this->_subscriptionDetails->membership_id];
             $tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
             $tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
             $status = ts('Billing details for your automatically renewed %1 membership have been updated.', array(1 => $tplParams['membershipType']));
             $msgTitle = ts('Details Updated');
             $msgType = 'success';
         } else {
             $status = ts('Billing details for the recurring contribution of %1, every %2 %3 have been updated.', array(1 => $this->_subscriptionDetails->amount, 2 => $this->_subscriptionDetails->frequency_interval, 3 => $this->_subscriptionDetails->frequency_unit));
             $msgTitle = ts('Details Updated');
             $msgType = 'success';
             $tplParams = array('recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval, 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit, 'amount' => $this->_subscriptionDetails->amount);
         }
         // format new address for display
         $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
         foreach ($addressParts as $part) {
             $addressParts[$part] = CRM_Utils_Array::value($part, $processorParams);
         }
         $tplParams['address'] = CRM_Utils_Address::format($addressParts);
         // format old address to store in activity details
         $this->_defaults["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvince($this->_defaults["state_province-{$this->_bltID}"], FALSE);
         $this->_defaults["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::country($this->_defaults["country-{$this->_bltID}"], FALSE);
         $addressParts = array("street_address", "city", "postal_code", "state_province", "country");
         foreach ($addressParts as $part) {
             $key = "{$part}-{$this->_bltID}";
             $addressParts[$part] = CRM_Utils_Array::value($key, $this->_defaults);
         }
         $this->_defaults['address'] = CRM_Utils_Address::format($addressParts);
         // format new billing name
         $name = $processorParams['first_name'];
         if (!empty($processorParams['middle_name'])) {
             $name .= " {$processorParams['middle_name']}";
         }
         $name .= ' ' . $processorParams['last_name'];
         $name = trim($name);
         $tplParams['billingName'] = $name;
         // format old billing name
         $name = $this->_defaults['first_name'];
         if (!empty($this->_defaults['middle_name'])) {
             $name .= " {$this->_defaults['middle_name']}";
         }
         $name .= ' ' . $this->_defaults['last_name'];
         $name = trim($name);
         $this->_defaults['billingName'] = $name;
         $message .= "\n<br/><br/>New Billing Name and Address\n<br/>==============================\n<br/>{$tplParams['billingName']}\n<br/>{$tplParams['address']}\n\n<br/><br/>Previous Billing Name and Address\n<br/>==================================\n<br/>{$this->_defaults['billingName']}\n<br/>{$this->_defaults['address']}";
         $activityParams = array('source_contact_id' => $this->_subscriptionDetails->contact_id, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Update Recurring Contribution Billing Details', 'name'), 'subject' => ts('Recurring Contribution Billing Details Updated'), 'details' => $message, '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);
         // send notification
         if ($this->_subscriptionDetails->contribution_page_id) {
             CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $this->_subscriptionDetails->contribution_page_id, $value, array('title', 'receipt_from_name', 'receipt_from_email'));
             $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
         } else {
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>";
         }
         list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
         $tplParams['contact'] = array('display_name' => $donorDisplayName);
         $date = CRM_Utils_Date::format($processorParams['credit_card_exp_date']);
         $tplParams['credit_card_exp_date'] = CRM_Utils_Date::mysqlToIso($date);
         $tplParams['credit_card_number'] = CRM_Utils_System::mungeCreditCard($processorParams['credit_card_number']);
         $tplParams['credit_card_type'] = $processorParams['credit_card_type'];
         $sendTemplateParams = array('groupName' => $this->_subscriptionDetails->membership_id ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution', 'valueName' => $this->_subscriptionDetails->membership_id ? 'membership_autorenew_billing' : 'contribution_recurring_billing', 'contactId' => $this->_subscriptionDetails->contact_id, 'tplParams' => $tplParams, 'isTest' => $this->_subscriptionDetails->is_test, 'PDFFilename' => 'receipt.pdf', 'from' => $receiptFrom, 'toName' => $donorDisplayName, 'toEmail' => $donorEmail);
         list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
     } else {
         $status = ts('There was some problem updating the billing details.');
         $msgTitle = ts('Update Error');
         $msgType = 'error';
     }
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     if ($userID && $status) {
         $session->setStatus($status, $msgTitle, $msgType);
     } elseif (!$userID) {
         if ($status) {
             CRM_Utils_System::setUFMessage($status);
         }
         $result = (int) ($updateSubscription && isset($ctype));
         if (isset($tplParams)) {
             $session->set('resultParams', $tplParams);
         }
         return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus', "reset=1&task=billing&result={$result}"));
     }
 }
Exemplo n.º 14
0
 /**
  * Run the page.
  *
  * This method is called after the page is created. It checks for the
  * type of action and executes that action.
  * Finally it calls the parent's run method.
  *
  * @return void
  */
 public function run()
 {
     $session = CRM_Core_Session::singleton();
     $config = CRM_Core_Config::singleton();
     $permissionCheck = FALSE;
     $statusMessage = '';
     if ($config->userFramework != 'Joomla') {
         $permissionCheck = CRM_Core_Permission::check('administer CiviCRM');
     }
     //get the pcp id.
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
     $prms = array('id' => $this->_id);
     CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $prms, $pcpInfo);
     $this->_component = $pcpInfo['page_type'];
     if (empty($pcpInfo)) {
         $statusMessage = ts('The personal campaign page you requested is currently unavailable.');
         CRM_Core_Error::statusBounce($statusMessage, $config->userFrameworkBaseURL);
     }
     CRM_Utils_System::setTitle($pcpInfo['title']);
     $this->assign('pcp', $pcpInfo);
     $pcpStatus = CRM_Core_OptionGroup::values("pcp_status");
     $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
     // check if PCP is created by anonymous user
     $anonymousPCP = CRM_Utils_Request::retrieve('ap', 'Boolean', $this);
     if ($anonymousPCP) {
         $loginURL = $config->userSystem->getLoginURL();
         $anonMessage = ts('Once you\'ve received your new account welcome email, you can <a href=%1>click here</a> to login and promote your campaign page.', array(1 => $loginURL));
         CRM_Core_Session::setStatus($anonMessage, ts('Success'), 'success');
     } else {
         $statusMessage = ts('The personal campaign page you requested is currently unavailable. However you can still support the campaign by making a contribution here.');
     }
     $pcpBlock = new CRM_PCP_DAO_PCPBlock();
     $pcpBlock->entity_table = CRM_PCP_BAO_PCP::getPcpEntityTable($pcpInfo['page_type']);
     $pcpBlock->entity_id = $pcpInfo['page_id'];
     $pcpBlock->find(TRUE);
     // Redirect back to source page in case of error.
     if ($pcpInfo['page_type'] == 'contribute') {
         $urlBase = 'civicrm/contribute/transact';
     } elseif ($pcpInfo['page_type'] == 'event') {
         $urlBase = 'civicrm/event/register';
     }
     if ($pcpInfo['status_id'] != $approvedId || !$pcpInfo['is_active']) {
         if ($pcpInfo['contact_id'] != $session->get('userID') && !$permissionCheck) {
             CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url($urlBase, "reset=1&id=" . $pcpInfo['page_id'], FALSE, NULL, FALSE, TRUE));
         }
     } else {
         $getStatus = CRM_PCP_BAO_PCP::getStatus($this->_id, $this->_component);
         if (!$getStatus) {
             // PCP not enabled for this contribution page. Forward everyone to source page
             CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url($urlBase, "reset=1&id=" . $pcpInfo['page_id'], FALSE, NULL, FALSE, TRUE));
         }
     }
     $default = array();
     if ($pcpBlock->target_entity_type == 'contribute') {
         $urlBase = 'civicrm/contribute/transact';
     } elseif ($pcpBlock->target_entity_type == 'event') {
         $urlBase = 'civicrm/event/register';
     }
     if ($pcpBlock->entity_table == 'civicrm_event') {
         $page_class = 'CRM_Event_DAO_Event';
         $this->assign('pageName', CRM_Event_PseudoConstant::event($pcpInfo['page_id']));
         CRM_Core_DAO::commonRetrieveAll($page_class, 'id', $pcpInfo['page_id'], $default, array('start_date', 'end_date', 'registration_start_date', 'registration_end_date'));
     } elseif ($pcpBlock->entity_table == 'civicrm_contribution_page') {
         $page_class = 'CRM_Contribute_DAO_ContributionPage';
         $this->assign('pageName', CRM_Contribute_PseudoConstant::contributionPage($pcpInfo['page_id'], TRUE));
         CRM_Core_DAO::commonRetrieveAll($page_class, 'id', $pcpInfo['page_id'], $default, array('start_date', 'end_date'));
     }
     $pageInfo = $default[$pcpInfo['page_id']];
     if ($pcpInfo['contact_id'] == $session->get('userID')) {
         $owner = $pageInfo;
         $owner['status'] = CRM_Utils_Array::value($pcpInfo['status_id'], $pcpStatus);
         $this->assign('owner', $owner);
         $link = CRM_PCP_BAO_PCP::pcpLinks();
         $hints = array(CRM_Core_Action::UPDATE => ts('Change the content and appearance of your page'), CRM_Core_Action::DETACH => ts('Send emails inviting your friends to support your campaign!'), CRM_Core_Action::VIEW => ts('Copy this link to share directly with your network!'), CRM_Core_Action::BROWSE => ts('Update your personal contact information'), CRM_Core_Action::DISABLE => ts('De-activate the page (you can re-activate it later)'), CRM_Core_Action::ENABLE => ts('Activate the page (you can de-activate it later)'), CRM_Core_Action::DELETE => ts('Remove the page (this cannot be undone!)'));
         $replace = array('id' => $this->_id, 'block' => $pcpBlock->id, 'pageComponent' => $this->_component);
         if (!$pcpBlock->is_tellfriend_enabled || CRM_Utils_Array::value('status_id', $pcpInfo) != $approvedId) {
             unset($link['all'][CRM_Core_Action::DETACH]);
         }
         switch ($pcpInfo['is_active']) {
             case 1:
                 unset($link['all'][CRM_Core_Action::ENABLE]);
                 break;
             case 0:
                 unset($link['all'][CRM_Core_Action::DISABLE]);
                 break;
         }
         $this->assign('links', $link['all']);
         $this->assign('hints', $hints);
         $this->assign('replace', $replace);
     }
     $honor = CRM_PCP_BAO_PCP::honorRoll($this->_id);
     $entityFile = CRM_Core_BAO_File::getEntityFile('civicrm_pcp', $this->_id);
     if (!empty($entityFile)) {
         $fileInfo = reset($entityFile);
         $fileId = $fileInfo['fileID'];
         $image = '<img src="' . CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileId}&eid={$this->_id}") . '" />';
         $this->assign('image', $image);
     }
     $totalAmount = CRM_PCP_BAO_PCP::thermoMeter($this->_id);
     $achieved = round($totalAmount / $pcpInfo['goal_amount'] * 100, 2);
     if ($pcpBlock->is_active == 1) {
         $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign', "action=add&reset=1&pageId={$pcpInfo['page_id']}&component={$pcpInfo['page_type']}", TRUE, NULL, TRUE, TRUE);
         $this->assign('linkTextUrl', $linkTextUrl);
         $this->assign('linkText', $pcpBlock->link_text);
     }
     $this->assign('honor', $honor);
     $this->assign('total', $totalAmount ? $totalAmount : '0.0');
     $this->assign('achieved', $achieved <= 100 ? $achieved : 100);
     if ($achieved <= 100) {
         $this->assign('remaining', 100 - $achieved);
     }
     // make sure that we are between contribution page start and end dates OR registration start date and end dates if they are set
     if ($pcpBlock->entity_table == 'civicrm_event') {
         $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('registration_start_date', $pageInfo));
         $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('registration_end_date', $pageInfo));
     } else {
         $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('start_date', $pageInfo));
         $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $pageInfo));
     }
     $now = time();
     $validDate = TRUE;
     if ($startDate && $startDate >= $now) {
         $validDate = FALSE;
     }
     if ($endDate && $endDate < $now) {
         $validDate = FALSE;
     }
     $this->assign('validDate', $validDate);
     // form parent page url
     if ($action == CRM_Core_Action::PREVIEW) {
         $parentUrl = CRM_Utils_System::url($urlBase, "id={$pcpInfo['page_id']}&reset=1&action=preview", TRUE, NULL, TRUE, TRUE);
     } else {
         $parentUrl = CRM_Utils_System::url($urlBase, "id={$pcpInfo['page_id']}&reset=1", TRUE, NULL, TRUE, TRUE);
     }
     $this->assign('parentURL', $parentUrl);
     if ($validDate) {
         $contributionText = ts('Contribute Now');
         if (!empty($pcpInfo['donate_link_text'])) {
             $contributionText = $pcpInfo['donate_link_text'];
         }
         $this->assign('contributionText', $contributionText);
         // we always generate urls for the front end in joomla
         if ($action == CRM_Core_Action::PREVIEW) {
             $url = CRM_Utils_System::url($urlBase, "id=" . $pcpBlock->target_entity_id . "&pcpId={$this->_id}&reset=1&action=preview", TRUE, NULL, TRUE, TRUE);
         } else {
             $url = CRM_Utils_System::url($urlBase, "id=" . $pcpBlock->target_entity_id . "&pcpId={$this->_id}&reset=1", TRUE, NULL, TRUE, TRUE);
         }
         $this->assign('contributeURL', $url);
     }
     // we do not want to display recently viewed items, so turn off
     $this->assign('displayRecent', FALSE);
     $single = $permission = FALSE;
     switch ($action) {
         case CRM_Core_Action::BROWSE:
             $subForm = 'PCPAccount';
             $form = "CRM_PCP_Form_{$subForm}";
             $single = TRUE;
             break;
         case CRM_Core_Action::UPDATE:
             $subForm = 'Campaign';
             $form = "CRM_PCP_Form_{$subForm}";
             $single = TRUE;
             break;
     }
     $userID = $session->get('userID');
     //make sure the user has "administer CiviCRM" permission
     //OR has created the PCP
     if (CRM_Core_Permission::check('administer CiviCRM') || $userID && CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $this->_id, 'contact_id') == $userID) {
         $permission = TRUE;
     }
     if ($single && $permission) {
         $controller = new CRM_Core_Controller_Simple($form, $subForm, $action);
         $controller->set('id', $this->_id);
         $controller->set('single', TRUE);
         $controller->process();
         return $controller->run();
     }
     $session->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1&id=' . $this->_id));
     parent::run();
 }
Exemplo n.º 15
0
 /**
  * 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);
     }
 }
 /**
  * Send the emails for Recurring Contribution Notication.
  *
  * @param string $type
  *   TxnType.
  * @param int $contactID
  *   Contact id for contributor.
  * @param int $pageID
  *   Contribution page id.
  * @param object $recur
  *   Object of recurring contribution table.
  * @param bool|object $autoRenewMembership is it a auto renew membership.
  *
  * @return void
  */
 public static function recurringNotify($type, $contactID, $pageID, $recur, $autoRenewMembership = FALSE)
 {
     $value = array();
     if ($pageID) {
         CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $pageID, $value, array('title', 'is_email_receipt', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt'));
     }
     $isEmailReceipt = CRM_Utils_Array::value('is_email_receipt', $value[$pageID]);
     $isOfflineRecur = FALSE;
     if (!$pageID && $recur->id) {
         $isOfflineRecur = TRUE;
     }
     if ($isEmailReceipt || $isOfflineRecur) {
         if ($pageID) {
             $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$pageID]) . '" <' . $value[$pageID]['receipt_from_email'] . '>';
             $receiptFromName = $value[$pageID]['receipt_from_name'];
             $receiptFromEmail = $value[$pageID]['receipt_from_email'];
         } else {
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>";
             $receiptFromName = $domainValues[0];
             $receiptFromEmail = $domainValues[1];
         }
         list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE);
         $templatesParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_recurring_notify', 'contactId' => $contactID, 'tplParams' => array('recur_frequency_interval' => $recur->frequency_interval, 'recur_frequency_unit' => $recur->frequency_unit, 'recur_installments' => $recur->installments, 'recur_start_date' => $recur->start_date, 'recur_end_date' => $recur->end_date, 'recur_amount' => $recur->amount, 'recur_txnType' => $type, 'displayName' => $displayName, 'receipt_from_name' => $receiptFromName, 'receipt_from_email' => $receiptFromEmail, 'auto_renew_membership' => $autoRenewMembership), 'from' => $receiptFrom, 'toName' => $displayName, 'toEmail' => $email);
         //CRM-13811
         if ($pageID) {
             $templatesParams['cc'] = CRM_Utils_Array::value('cc_receipt', $value[$pageID]);
             $templatesParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $value[$pageID]);
         }
         if ($recur->id) {
             // in some cases its just recurringNotify() thats called for the first time and these urls don't get set.
             // like in PaypalPro, & therefore we set it here additionally.
             $template = CRM_Core_Smarty::singleton();
             $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj');
             $url = $paymentProcessor->subscriptionURL($recur->id, 'recur');
             $template->assign('cancelSubscriptionUrl', $url);
             $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'billing');
             $template->assign('updateSubscriptionBillingUrl', $url);
             $url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'update');
             $template->assign('updateSubscriptionUrl', $url);
         }
         list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($templatesParams);
         if ($sent) {
             CRM_Core_Error::debug_log_message('Success: mail sent for recurring notification.');
         } else {
             CRM_Core_Error::debug_log_message('Failure: mail not sent for recurring notification.');
         }
     }
 }
Exemplo n.º 17
0
 /**
  * This is a common method called to insert the data into the custom table
  */
 private function insertCustomData($gid, $columnVals)
 {
     $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $gid, 'table_name', 'id');
     $cfDetails = array();
     CRM_Core_DAO::commonRetrieveAll('CRM_Core_BAO_CustomField', 'custom_group_id', $gid, $cfDetails);
     foreach ($cfDetails as $fieldID => $value) {
         $columnNames[] = $value['column_name'];
     }
     $ignoreFieldsByGroup = array('Qualifications' => array('evidence_file_26'), 'Identify' => array('evidence_file_37', 'is_government'), 'Medical_Disability' => array('evidence_file_39'), 'Immigration' => array('evidence_file_41'), 'Career' => array('evidence_file_42'));
     foreach ($ignoreFieldsByGroup as $groupName => $ignoreFields) {
         if ($gid == CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $groupName, 'id', 'name')) {
             $columnNames = array_diff($columnNames, $ignoreFields);
         }
     }
     $columns = implode("`,`", $columnNames);
     $columnValues = implode("','", array_values($columnVals));
     $query = "INSERT INTO {$tableName} (`entity_id`,`{$columns}`) VALUES ('{$columnValues}')";
     $dao = CRM_Core_DAO::executeQuery($query);
 }
 /**
  * called after the user submits the form.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     // store the submitted values in an array
     $params = $this->exportValues();
     if ($this->_selfService && $this->_donorEmail) {
         // for self service force notify
         $params['is_notify'] = 1;
     }
     // if this is an update of an existing recurring contribution, pass the ID
     $params['id'] = $this->_subscriptionDetails->recur_id;
     $message = '';
     $params['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
     $updateSubscription = TRUE;
     if ($this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) {
         $updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params);
     }
     if (is_a($updateSubscription, 'CRM_Core_Error')) {
         CRM_Core_Error::displaySessionError($updateSubscription);
         $status = ts('Could not update the Recurring contribution details');
         $msgTitle = ts('Update Error');
         $msgType = 'error';
     } elseif ($updateSubscription) {
         // save the changes
         $result = CRM_Contribute_BAO_ContributionRecur::add($params);
         $status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.', array(1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency), 2 => $this->_subscriptionDetails->frequency_interval, 3 => $this->_subscriptionDetails->frequency_unit, 4 => $params['installments']));
         $msgTitle = ts('Update Success');
         $msgType = 'success';
         $contactID = $this->_subscriptionDetails->contact_id;
         if ($this->_subscriptionDetails->amount != $params['amount']) {
             $message .= "<br /> " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.", array(1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency), 2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency))) . ' ';
         }
         if ($this->_subscriptionDetails->installments != $params['installments']) {
             $message .= "<br /> " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", array(1 => $this->_subscriptionDetails->installments, 2 => $params['installments'])) . ' ';
         }
         $activityParams = array('source_contact_id' => $contactID, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Update Recurring Contribution', 'name'), 'subject' => ts('Recurring Contribution Updated'), 'details' => $message, '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 (!empty($params['is_notify'])) {
             // send notification
             if ($this->_subscriptionDetails->contribution_page_id) {
                 CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $this->_subscriptionDetails->contribution_page_id, $value, array('title', 'receipt_from_name', 'receipt_from_email'));
                 $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
             } else {
                 $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
                 $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>";
             }
             list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $tplParams = array('recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval, 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit, 'amount' => CRM_Utils_Money::format($params['amount']), 'installments' => $params['installments']);
             $tplParams['contact'] = array('display_name' => $donorDisplayName);
             $tplParams['receipt_from_email'] = $receiptFrom;
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_recurring_edit', 'contactId' => $contactID, 'tplParams' => $tplParams, 'isTest' => $this->_subscriptionDetails->is_test, 'PDFFilename' => 'receipt.pdf', 'from' => $receiptFrom, 'toName' => $donorDisplayName, 'toEmail' => $donorEmail);
             list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
         }
     }
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     if ($userID && $status) {
         CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
     } elseif (!$userID) {
         if ($status) {
             CRM_Utils_System::setUFMessage($status);
         }
         // keep result as 1, since we not displaying anything on the redirected page anyway
         return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus', "reset=1&task=update&result=1"));
     }
 }
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE);
     $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id));
     $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description'));
     $this->add('text', 'minimum_fee', ts('Minimum Fee'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee'));
     $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
     $this->addElement('select', 'duration_unit', ts('Duration') . ' ', CRM_Core_SelectValues::unitList('duration'), array('onchange' => 'showHidePeriodSettings()'));
     //period type
     $this->addElement('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues::periodType(), array('onchange' => 'showHidePeriodSettings()'));
     $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval'));
     $memberOrg =& $this->add('text', 'member_org', ts('Membership Organization'), 'size=30 maxlength=120');
     //start day
     $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE);
     $msgTemplates = CRM_Core_BAO_MessageTemplates::getMessageTemplates(FALSE);
     $hasMsgTemplates = FALSE;
     if (!empty($msgTemplates)) {
         $hasMsgTemplates = TRUE;
     }
     //Auto-renew Option
     $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
     $isAuthorize = FALSE;
     $options = array();
     $allowAutoRenewMsg = FALSE;
     if (is_array($paymentProcessor) && !empty($paymentProcessor)) {
         $isAuthorize = TRUE;
         $options = array(ts('No auto-renew option'), ts('Give option, but not required'), ts('Auto-renew required '));
         if ($hasMsgTemplates) {
             $allowAutoRenewMsg = TRUE;
             $autoRenewReminderMsg = $this->add('select', 'autorenewal_msg_id', ts('Auto-renew Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
         }
     }
     $this->addRadio('auto_renew', ts('Auto-renew Option'), $options, array('onclick' => "setReminder(this.value);"));
     $this->assign('authorize', $isAuthorize);
     $this->assign('allowAutoRenewMsg', $allowAutoRenewMsg);
     //rollover day
     $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE);
     // required in form rule
     $this->add('hidden', 'action', $this->_action);
     $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType());
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
     if (is_array($relTypeInd)) {
         asort($relTypeInd);
     }
     $memberRel =& $this->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $relTypeInd);
     $memberRel->setMultiple(TRUE);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::memberVisibility());
     $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight'));
     $this->add('checkbox', 'is_active', ts('Enabled?'));
     if ($hasMsgTemplates) {
         $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
     }
     $this->assign('hasMsgTemplates', $hasMsgTemplates);
     $reminderDay =& $this->add('text', 'renewal_reminder_day', ts('Renewal Reminder Day'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'renewal_reminder_day'));
     $searchRows = $this->get('searchRows');
     $searchCount = $this->get('searchCount');
     $searchDone = $this->get('searchDone');
     if ($searchRows) {
         $checkBoxes = array();
         $chekFlag = 0;
         foreach ($searchRows as $id => $row) {
             $checked = '';
             if (!$chekFlag) {
                 $checked = array('checked' => NULL);
                 $chekFlag++;
             }
             $checkBoxes[$id] = $this->createElement('radio', NULL, NULL, NULL, $id, $checked);
         }
         $this->addGroup($checkBoxes, 'contact_check');
         $this->assign('searchRows', $searchRows);
     }
     $this->assign('searchCount', $searchCount);
     $this->assign('searchDone', $searchDone);
     if ($searchDone) {
         $searchBtn = ts('Search Again');
     } elseif ($this->_action & CRM_Core_Action::UPDATE) {
         $searchBtn = ts('Change');
     } else {
         $searchBtn = ts('Search');
     }
     $membershipRecords = FALSE;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $membershipType = new CRM_Member_BAO_Membership();
         $membershipType->membership_type_id = $this->_id;
         if ($membershipType->find(TRUE)) {
             $membershipRecords = TRUE;
             $memberRel->freeze();
         }
         $memberOrg->freeze();
         if ($searchDone) {
             $memberOrg->unfreeze();
         }
     }
     $this->assign('membershipRecordsExists', $membershipRecords);
     if ($this->_action & CRM_Core_Action::UPDATE && $reminderDay) {
         $renewMessage = array();
         $returnProperties = array('renewal_msg_id', 'renewal_reminder_day');
         CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_MembershipType', 'id', $this->_id, $renewMessage, $returnProperties);
         if (CRM_Utils_Array::value('renewal_msg_id', $renewMessage[$this->_id]) && CRM_Utils_Array::value('renewal_reminder_day', $renewMessage[$this->_id]) && $membershipRecords) {
             $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
             $reminderDay->freeze();
         }
     }
     $this->addElement('submit', $this->getButtonName('refresh'), $searchBtn, array('class' => 'form-submit'));
     $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
     $this->assign('membershipTypeId', $this->_id);
 }
Exemplo n.º 20
0
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     if ($this->_action & CRM_Core_Action::DELETE) {
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), true);
     $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id));
     $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description'));
     $this->add('text', 'minimum_fee', ts('Minimum Fee'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee'));
     $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money');
     $this->addElement('select', 'duration_unit', ts('Duration') . ' ', CRM_Core_SelectValues::unitList('duration'), array('onchange' => 'showHidePeriodSettings()'));
     //period type
     $this->addElement('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues::periodType(), array('onchange' => 'showHidePeriodSettings()'));
     $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval'));
     $memberOrg =& $this->add('text', 'member_org', ts('Membership Organization'), 'size=30 maxlength=120');
     //start day
     $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date('custom', 3, 1, "Md"), false);
     //rollover day
     $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date('custom', 3, 1, "Md"), false);
     $this->add('hidden', 'action', $this->_action);
     //required in form rule
     require_once 'CRM/Contribute/PseudoConstant.php';
     $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType());
     require_once 'CRM/Contact/BAO/Relationship.php';
     $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true);
     if (is_array($relTypeInd)) {
         asort($relTypeInd);
     }
     $memberRel =& $this->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $relTypeInd);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::memberVisibility());
     $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight'));
     $this->add('checkbox', 'is_active', ts('Enabled?'));
     require_once "CRM/Core/BAO/MessageTemplates.php";
     $msgTemplates = CRM_Core_BAO_MessageTemplates::getMessageTemplates();
     if (!empty($msgTemplates)) {
         $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
     } else {
         $this->assign('noMsgTemplates', true);
     }
     $reminderDay =& $this->add('text', 'renewal_reminder_day', ts('Renewal Reminder Day'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'renewal_reminder_day'));
     $searchRows = $this->get('searchRows');
     $searchCount = $this->get('searchCount');
     $searchDone = $this->get('searchDone');
     if ($searchRows) {
         $checkBoxes = array();
         $chekFlag = 0;
         foreach ($searchRows as $id => $row) {
             $checked = '';
             if (!$chekFlag) {
                 $checked = array('checked' => null);
                 $chekFlag++;
             }
             $checkBoxes[$id] = $this->createElement('radio', null, null, null, $id, $checked);
         }
         $this->addGroup($checkBoxes, 'contact_check');
         $this->assign('searchRows', $searchRows);
     }
     $this->assign('searchCount', $searchCount);
     $this->assign('searchDone', $searchDone);
     if ($searchDone) {
         $searchBtn = ts('Search Again');
     } elseif ($this->_action & CRM_Core_Action::UPDATE) {
         $searchBtn = ts('Change');
     } else {
         $searchBtn = ts('Search');
     }
     $membershipRecords = false;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         require_once 'CRM/Member/BAO/Membership.php';
         $membershipType = new CRM_Member_BAO_Membership();
         $membershipType->membership_type_id = $this->_id;
         if ($membershipType->find(true)) {
             $membershipRecords = true;
             $memberRel->freeze();
         }
         $memberOrg->freeze();
         if ($searchDone) {
             $memberOrg->unfreeze();
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE && $reminderDay) {
         $renewMessage = array();
         $returnProperties = array('renewal_msg_id', 'renewal_reminder_day');
         CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_MembershipType', 'id', $this->_id, $renewMessage, $returnProperties);
         if (CRM_Utils_Array::value('renewal_msg_id', $renewMessage[$this->_id]) && CRM_Utils_Array::value('renewal_reminder_day', $renewMessage[$this->_id]) && $membershipRecords) {
             $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates);
             $reminderDay->freeze();
             $reminderMsg->freeze();
         }
     }
     $this->addElement('submit', $this->getButtonName('refresh'), $searchBtn, array('class' => 'form-submit'));
     $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule'));
     $this->assign('membershipTypeId', $this->_id);
 }
Exemplo n.º 21
0
 /**
  * This function sets the default values for the form. Note that in edit/view mode
  * the default values are retrieved from the database
  *
  * @access public
  *
  * @return void
  */
 function setDefaultValues()
 {
     $defaults = parent::setDefaultValues();
     $title = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'title');
     CRM_Utils_System::setTitle(ts('Contribution Amounts (%1)', array(1 => $title)));
     if (!CRM_Utils_Array::value('pay_later_text', $defaults)) {
         $defaults['pay_later_text'] = ts('I will send payment by check');
     }
     if (CRM_Utils_Array::value('amount_block_is_active', $defaults)) {
         if ($priceSetId = CRM_Price_BAO_Set::getFor('civicrm_contribution_page', $this->_id, NULL)) {
             if ($isQuick = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'is_quick_config')) {
                 $this->assign('isQuick', $isQuick);
                 //$priceField = CRM_Core_DAO::getFieldValue( 'CRM_Price_DAO_Field', $priceSetId, 'id', 'price_set_id' );
                 $options = $pFIDs = array();
                 $priceFieldParams = array('price_set_id' => $priceSetId);
                 $priceFields = CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_Field', 'price_set_id', $priceSetId, $pFIDs, $return = array('html_type', 'name', 'is_active'));
                 foreach ($priceFields as $priceField) {
                     if ($priceField['id'] && $priceField['html_type'] == 'Radio' && $priceField['name'] == 'contribution_amount') {
                         $defaults['price_field_id'] = $priceField['id'];
                         $priceFieldOptions = CRM_Price_BAO_FieldValue::getValues($priceField['id'], $options, 'id', 1);
                         $countRow = 0;
                         foreach ($options as $optionId => $optionValue) {
                             $countRow++;
                             $defaults['value'][$countRow] = $optionValue['amount'];
                             $defaults['label'][$countRow] = CRM_Utils_Array::value('label', $optionValue);
                             $defaults['name'][$countRow] = CRM_Utils_Array::value('name', $optionValue);
                             $defaults['weight'][$countRow] = $optionValue['weight'];
                             $defaults["price_field_value"][$countRow] = $optionValue['id'];
                             if ($optionValue['is_default']) {
                                 $defaults['default'] = $countRow;
                             }
                         }
                     } elseif ($priceField['id'] && $priceField['html_type'] == 'Text' && ($priceField['name'] = 'other_amount' && $priceField['is_active'])) {
                         $defaults['price_field_other'] = $priceField['id'];
                     }
                 }
             }
         }
         if (CRM_Utils_Array::value('value', $defaults) && is_array($defaults['value'])) {
             // CRM-4038: fix value display
             foreach ($defaults['value'] as &$amount) {
                 $amount = trim(CRM_Utils_Money::format($amount, ' '));
             }
         }
     }
     // fix the display of the monetary value, CRM-4038
     if (isset($defaults['min_amount'])) {
         $defaults['min_amount'] = CRM_Utils_Money::format($defaults['min_amount'], NULL, '%a');
     }
     if (isset($defaults['max_amount'])) {
         $defaults['max_amount'] = CRM_Utils_Money::format($defaults['max_amount'], NULL, '%a');
     }
     if (CRM_Utils_Array::value('payment_processor', $defaults)) {
         $defaults['payment_processor'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR, $defaults['payment_processor']), '1');
     }
     return $defaults;
 }
Exemplo n.º 22
0
 /**
  * @param array $params
  *
  * @return mixed
  */
 public function emailReceipt(&$params)
 {
     // email receipt sending
     // send message template
     if ($this->_component == 'event') {
         $eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $eventId, $events, $returnProperties);
         $event = $events[$eventId];
         unset($event['start_date']);
         unset($event['end_date']);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
     }
     // assign payment info here
     $paymentConfig['confirm_email_text'] = CRM_Utils_Array::value('confirm_email_text', $params);
     $this->assign('paymentConfig', $paymentConfig);
     $isRefund = $this->_paymentType == 'refund' ? TRUE : FALSE;
     $this->assign('isRefund', $isRefund);
     if ($isRefund) {
         $this->assign('totalPaid', $this->_amtPaid);
         $this->assign('totalAmount', $this->_amtTotal);
         $this->assign('refundAmount', $params['total_amount']);
     } else {
         $balance = $this->_amtTotal - ($this->_amtPaid + $params['total_amount']);
         $paymentsComplete = $balance == 0 ? 1 : 0;
         $this->assign('amountOwed', $balance);
         $this->assign('totalAmount', $this->_amtTotal);
         $this->assign('paymentAmount', $params['total_amount']);
         $this->assign('paymentsComplete', $paymentsComplete);
     }
     $this->assign('contactDisplayName', $this->_contributorDisplayName);
     // assign trxn details
     $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $params));
     $this->assign('receive_date', CRM_Utils_Array::value('trxn_date', $params));
     $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
     if (array_key_exists('payment_instrument_id', $params)) {
         $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
     }
     $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
     $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'payment_or_refund_notification', 'contactId' => $this->_contactId, 'PDFFilename' => ts('notification') . '.pdf');
     // try to send emails only if email id is present
     // and the do-not-email option is not checked for that contact
     if ($this->_contributorEmail && !$this->_toDoNotEmail) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $sendTemplateParams['from'] = $receiptFrom;
         $sendTemplateParams['toName'] = $this->_contributorDisplayName;
         $sendTemplateParams['toEmail'] = $this->_contributorEmail;
         $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
         $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
     }
     list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
     return $mailSent;
 }
Exemplo n.º 23
0
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 function buildQuickForm()
 {
     $this->addElement('checkbox', 'is_active', ts('Enable Personal Campaign Pages (for this contribution page)?'), null, array('onclick' => "return showHideByValue('is_active',true,'pcpFields','table-row','radio',false);"));
     $this->addElement('checkbox', 'is_approval_needed', ts('Approval required'));
     $profile = array();
     $isUserRequired = null;
     $config =& CRM_Core_Config::singleton();
     if ($config->userFramework != 'Standalone') {
         $isUserRequired = 2;
     }
     CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, array('title', 'is_active'));
     if (!empty($profiles)) {
         foreach ($profiles as $key => $value) {
             if ($value['is_active']) {
                 $profile[$key] = $value['title'];
             }
         }
         $this->assign('profile', $profile);
     }
     $this->add('select', 'supporter_profile_id', ts('Supporter profile'), array('' => ts('- select -')) + $profile);
     $this->addElement('checkbox', 'is_tellfriend_enabled', ts("Allow 'Tell a friend' functionality"), null, array('onclick' => "return showHideByValue('is_tellfriend_enabled',true,'tflimit','table-row','radio',false);"));
     $this->add('text', 'tellfriend_limit', ts("'Tell a friend' maximum recipients limit"), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'pcp_tellfriend_limit'));
     $this->addRule('tellfriend_limit', ts('Please enter a valid limit.'), 'integer');
     $this->add('text', 'link_text', ts("'Create Personal Campaign Page' link text"), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_PCPBlock', 'pcp_link_text'));
     $this->add('text', 'notify_email', ts('Notify Email'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_PCPBlock', 'notify_email'));
     parent::buildQuickForm();
     $this->addFormRule(array('CRM_Contribute_Form_ContributionPage_PCP', 'formRule'), $this);
 }
Exemplo n.º 24
0
 /**
  * Build the form object.
  */
 public function buildQuickForm()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if ($this->_context == 'standalone') {
         $this->addEntityRef('contact_id', ts('Contact'), array('create' => TRUE, 'api' => array('extra' => array('email'))), TRUE);
     }
     $showAdditionalInfo = FALSE;
     $this->_formType = CRM_Utils_Array::value('formType', $_GET);
     $defaults = array();
     $paneNames = array('Payment Reminders' => 'PaymentReminders');
     foreach ($paneNames as $name => $type) {
         $urlParams = "snippet=4&formType={$type}";
         $allPanes[$name] = array('url' => CRM_Utils_System::url('civicrm/contact/view/pledge', $urlParams), 'open' => 'false', 'id' => $type);
         // see if we need to include this paneName in the current form
         if ($this->_formType == $type || !empty($_POST["hidden_{$type}"]) || CRM_Utils_Array::value("hidden_{$type}", $defaults)) {
             $showAdditionalInfo = TRUE;
             $allPanes[$name]['open'] = 'true';
         }
         $fnName = "build{$type}";
         CRM_Contribute_Form_AdditionalInfo::$fnName($this);
     }
     $this->assign('allPanes', $allPanes);
     $this->assign('showAdditionalInfo', $showAdditionalInfo);
     if ($this->_formType) {
         $this->assign('formType', $this->_formType);
         return;
     }
     $this->applyFilter('__ALL__', 'trim');
     // pledge fields.
     $attributes = CRM_Core_DAO::getAttribute('CRM_Pledge_DAO_Pledge');
     $this->assign('isPending', $this->_isPending);
     $js = array('onblur' => "calculatedPaymentAmount( );", 'onkeyup' => "calculatedPaymentAmount( );");
     $currencyFreeze = FALSE;
     if ($this->_id && !$this->_isPending) {
         $currencyFreeze = TRUE;
     }
     $element = $this->addMoney('amount', ts('Total Pledge Amount'), TRUE, array_merge($attributes['pledge_amount'], $js), TRUE, 'currency', NULL, $currencyFreeze);
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'installments', ts('To be paid in'), array_merge($attributes['installments'], $js), TRUE);
     $this->addRule('installments', ts('Please enter a valid number of installments.'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'frequency_interval', ts('every'), $attributes['pledge_frequency_interval'], TRUE);
     $this->addRule('frequency_interval', ts('Please enter a number for frequency (e.g. every "3" months).'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     // Fix frequency unit display for use with frequency_interval
     $freqUnitsDisplay = array();
     foreach ($this->_freqUnits as $val => $label) {
         $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label));
     }
     $element =& $this->add('select', 'frequency_unit', ts('Frequency'), array('' => ts('- select -')) + $freqUnitsDisplay, TRUE);
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $element =& $this->add('text', 'frequency_day', ts('Payments are due on the'), $attributes['frequency_day'], TRUE);
     $this->addRule('frequency_day', ts('Please enter a valid payment due day.'), 'positiveInteger');
     if ($this->_id && !$this->_isPending) {
         $element->freeze();
     }
     $this->add('text', 'eachPaymentAmount', ts('each'), array('size' => 10, 'style' => "background-color:#EBECE4", 0 => 'READONLY'));
     // add various dates
     if (!$this->_id || $this->_isPending) {
         $this->addDate('create_date', ts('Pledge Made'), TRUE);
         $this->addDate('start_date', ts('Payments Start'), TRUE);
     }
     if ($this->_id && !$this->_isPending) {
         $eachPaymentAmount = $this->_values['original_installment_amount'];
         $this->assign('currency', $this->_values['currency']);
         $this->assign('eachPaymentAmount', $eachPaymentAmount);
         $this->assign('hideCalender', TRUE);
     }
     if (CRM_Utils_Array::value('status_id', $this->_values) != array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
         $this->addElement('checkbox', 'is_acknowledge', ts('Send Acknowledgment?'), NULL, array('onclick' => "showHideByValue( 'is_acknowledge', '', 'acknowledgeDate', 'table-row', 'radio', true); showHideByValue( 'is_acknowledge', '', 'fromEmail', 'table-row', 'radio', false );"));
         $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails);
     }
     $this->addDate('acknowledge_date', ts('Acknowledgment Date'));
     $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(), TRUE);
     // CRM-7362 --add campaigns.
     CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
     $pageIds = array();
     CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgeBlock', 'entity_table', 'civicrm_contribution_page', $pageIds, array('entity_id'));
     $pages = CRM_Contribute_PseudoConstant::contributionPage();
     $pledgePages = array();
     foreach ($pageIds as $key => $value) {
         $pledgePages[$value['entity_id']] = $pages[$value['entity_id']];
     }
     $ele = $this->add('select', 'contribution_page_id', ts('Self-service Payments Page'), array('' => ts('- select -')) + $pledgePages);
     $mailingInfo = Civi::settings()->get('mailing_backend');
     $this->assign('outBound_option', $mailingInfo['outBound_option']);
     // build custom data
     CRM_Custom_Form_CustomData::buildQuickForm($this);
     // make this form an upload since we dont know if the custom data injected dynamically
     // is of type file etc $uploadNames = $this->get( 'uploadNames' );
     $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save'), 'js' => array('onclick' => "return verify( );"), 'isDefault' => TRUE), array('type' => 'upload', 'name' => ts('Save and New'), 'js' => array('onclick' => "return verify( );"), 'subName' => 'new'), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->addFormRule(array('CRM_Pledge_Form_Pledge', 'formRule'), $this);
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->freeze();
     }
 }
Exemplo n.º 25
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Exemplo n.º 26
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     unset($params['amount']);
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
         }
         $params['discount_id'] = null;
         //re-enter the values for UPDATE mode
         $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
         $params['fee_amount'] = $participantBAO->fee_amount;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactID}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactID;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO =& new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $event['participant_role'] = $role[$params['role_id']];
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $location = CRM_Core_BAO_Location::getValues($locationParams, true);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template =& CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $params['amount_level'], 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($params['send_receipt'] && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
Exemplo n.º 27
0
Arquivo: PCP.php Projeto: kidaa30/yes
 /**
  * Build the form object.
  *
  * @param CRM_Core_Form $form
  *   Form object.
  *
  * @return void
  */
 public static function buildPCPForm($form)
 {
     $form->addElement('checkbox', 'pcp_active', ts('Enable Personal Campaign Pages?'), NULL, array('onclick' => "return showHideByValue('pcp_active',true,'pcpFields','block','radio',false);"));
     $form->addElement('checkbox', 'is_approval_needed', ts('Approval required'));
     $profile = array();
     $isUserRequired = NULL;
     $config = CRM_Core_Config::singleton();
     if ($config->userFramework != 'Standalone') {
         $isUserRequired = 2;
     }
     CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_UFGroup', 'is_cms_user', $isUserRequired, $profiles, array('title', 'is_active'));
     if (!empty($profiles)) {
         foreach ($profiles as $key => $value) {
             if ($value['is_active']) {
                 $profile[$key] = $value['title'];
             }
         }
         $form->assign('profile', $profile);
     }
     $form->add('select', 'supporter_profile_id', ts('Supporter Profile'), array('' => ts('- select -')) + $profile, TRUE);
     //CRM-15821 - To add new option for PCP "Owner" notification
     $ownerNotifications = CRM_Core_OptionGroup::values('pcp_owner_notify');
     $form->addRadio('owner_notify_id', ts('Owner Email Notification'), $ownerNotifications, NULL, '<br/>', TRUE);
     $form->addElement('checkbox', 'is_tellfriend_enabled', ts("Allow 'Tell a friend' functionality"), NULL, array('onclick' => "return showHideByValue('is_tellfriend_enabled',true,'tflimit','table-row','radio',false);"));
     $form->add('text', 'tellfriend_limit', ts("'Tell a friend' maximum recipients limit"), CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'tellfriend_limit'));
     $form->addRule('tellfriend_limit', ts('Please enter a valid limit.'), 'integer');
     $form->add('text', 'link_text', ts("'Create Personal Campaign Page' link text"), CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'link_text'));
     $form->add('text', 'notify_email', ts('Notify Email'), CRM_Core_DAO::getAttribute('CRM_PCP_DAO_PCPBlock', 'notify_email'));
 }
Exemplo n.º 28
0
 /**
  * takes an associative array and creates a membership object
  *
  * @param array    $params      (reference ) an assoc array of name/value pairs
  * @param array    $ids         the array that holds all the db ids
  * @param boolean  $callFromAPI Is this function called from API?
  * 
  * @return object CRM_Member_BAO_Membership object 
  * @access public
  * @static
  */
 static function &create(&$params, &$ids, $skipRedirect = false, $activityType = 'Membership Signup')
 {
     // always cal status if is_override/skipStatusCal is not true.
     // giving respect to is_override during import.  CRM-4012
     // To skip status cal we should use 'skipStatusCal'.
     // eg pay later membership, membership update cron CRM-3984
     if (!CRM_Utils_Array::value('is_override', $params) && !CRM_Utils_Array::value('skipStatusCal', $params)) {
         require_once 'CRM/Utils/Date.php';
         $startDate = $endDate = $joinDate = null;
         if (isset($params['start_date'])) {
             $startDate = CRM_Utils_Date::customFormat($params['start_date'], '%Y%m%d');
         }
         if (isset($params['end_date'])) {
             $endDate = CRM_Utils_Date::customFormat($params['end_date'], '%Y%m%d');
         }
         if (isset($params['join_date'])) {
             $joinDate = CRM_Utils_Date::customFormat($params['join_date'], '%Y%m%d');
         }
         require_once 'CRM/Member/BAO/MembershipStatus.php';
         //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
         $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, false);
         //CRM-3724 always skip is_admin if is_override != true.
         if (!$excludeIsAdmin && !CRM_Utils_Array::value('is_override', $params)) {
             $excludeIsAdmin = true;
         }
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
         if (empty($calcStatus)) {
             if (!$skipRedirect) {
                 // Redirect the form in case of error
                 CRM_Core_Session::setStatus(ts('The membership cannot be saved.') . '<br/>' . ts('No valid membership status for given dates.'));
                 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member"));
             }
             // Return the error message to the api
             $error = array();
             $error['is_error'] = ts('The membership cannot be saved. No valid membership status for given dates');
             return $error;
         }
         $params['status_id'] = $calcStatus['id'];
     }
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $membership =& self::add($params, $ids);
     if (is_a($membership, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $membership;
     }
     // add custom field values
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
     }
     $params['membership_id'] = $membership->id;
     if (isset($ids['membership'])) {
         $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $ids['membership'], 'contribution_id', 'membership_id');
     }
     //record contribution for this membership
     if (CRM_Utils_Array::value('contribution_status_id', $params)) {
         $contributionParams = array();
         $config = CRM_Core_Config::singleton();
         $contributionParams['currency'] = $config->defaultCurrency;
         $contributionParams['receipt_date'] = CRM_Utils_Array::value('receipt_date', $params) ? $params['receipt_date'] : 'null';
         $contributionParams['source'] = CRM_Utils_Array::value('contribution_source', $params);
         $contributionParams['non_deductible_amount'] = 'null';
         $recordContribution = array('contact_id', 'total_amount', 'receive_date', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'is_test', 'contribution_status_id', 'check_number');
         foreach ($recordContribution as $f) {
             $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
         }
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
         //insert payment record for this membership
         if (!CRM_Utils_Array::value('contribution', $ids) || CRM_Utils_Array::value('is_recur', $params)) {
             require_once 'CRM/Member/DAO/MembershipPayment.php';
             $mpDAO = new CRM_Member_DAO_MembershipPayment();
             $mpDAO->membership_id = $membership->id;
             $mpDAO->contribution_id = $contribution->id;
             if (CRM_Utils_Array::value('is_recur', $params)) {
                 $mpDAO->find();
             }
             CRM_Utils_Hook::pre('create', 'MembershipPayment', null, $mpDAO);
             $mpDAO->save();
             CRM_Utils_Hook::post('create', 'MembershipPayment', $mpDAO->id, $mpDAO);
         }
     }
     // add activity record only during create mode and renew mode
     // also add activity if status changed CRM-3984 and CRM-2521
     if (!CRM_Utils_Array::value('membership', $ids) || $activityType == 'Membership Renewal' || CRM_Utils_Array::value('createActivity', $params)) {
         if (CRM_Utils_Array::value('membership', $ids)) {
             CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership', 'id', $membership->id, $data, array('contact_id', 'membership_type_id', 'source'));
             $membership->contact_id = $data[$membership->id]['contact_id'];
             $membership->membership_type_id = $data[$membership->id]['membership_type_id'];
             $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]);
         }
         // since we are going to create activity record w/
         // individual contact as a target in case of on behalf signup,
         // so get the copy of organization id, CRM-5551
         $realMembershipContactId = $membership->contact_id;
         // create activity source = individual, target = org CRM-4027
         $targetContactID = null;
         if (CRM_Utils_Array::value('is_for_organization', $params)) {
             $targetContactID = $membership->contact_id;
             $membership->contact_id = $ids['userId'];
         }
         require_once 'CRM/Activity/BAO/Activity.php';
         CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         // we might created activity record w/ individual
         // contact as target so update membership object w/
         // original organization id, CRM-5551
         $membership->contact_id = $realMembershipContactId;
     }
     $transaction->commit();
     self::createRelatedMemberships($params, $membership);
     // do not add to recent items for import, CRM-4399
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         require_once 'CRM/Utils/Recent.php';
         require_once 'CRM/Member/PseudoConstant.php';
         require_once 'CRM/Contact/BAO/Contact.php';
         $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id];
         require_once 'CRM/Core/Permission.php';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         // add the recently created Membership
         CRM_Utils_Recent::add($title, $url, $membership->id, 'Membership', $membership->contact_id, null, $recentOther);
     }
     return $membership;
 }
Exemplo n.º 29
0
 /**
  * Takes an associative array and creates a membership object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  * @param bool $skipRedirect
  * @param string $activityType
  *
  * @throws CRM_Core_Exception
  *
  * @return CRM_Member_BAO_Membership|CRM_Core_Error
  */
 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup')
 {
     // always calculate status if is_override/skipStatusCal is not true.
     // giving respect to is_override during import.  CRM-4012
     // To skip status calculation we should use 'skipStatusCal'.
     // eg pay later membership, membership update cron CRM-3984
     if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
         $dates = array('start_date', 'end_date', 'join_date');
         // Declare these out of courtesy as IDEs don't pick up the setting of them below.
         $start_date = $end_date = $join_date = NULL;
         foreach ($dates as $date) {
             ${$date} = $params[$date] = CRM_Utils_Date::processDate(CRM_Utils_Array::value($date, $params), NULL, TRUE, 'Ymd');
         }
         //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
         $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, FALSE);
         //CRM-3724 always skip is_admin if is_override != true.
         if (!$excludeIsAdmin && empty($params['is_override'])) {
             $excludeIsAdmin = TRUE;
         }
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($start_date, $end_date, $join_date, 'today', $excludeIsAdmin, CRM_Utils_Array::value('membership_type_id', $params), $params);
         if (empty($calcStatus)) {
             // Redirect the form in case of error
             // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
             // however since we have no idea how (if) this is triggered we can't safely move / remove it
             // NB I tried really hard to trigger this error from backoffice membership form in order to test it
             // and am convinced form validation is complete on that form WRT this error.
             $errorParams = array('message_title' => ts('No valid membership status for given dates.'), 'legacy_redirect_path' => 'civicrm/contact/view', 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member");
             throw new CRM_Core_Exception(ts("The membership cannot be saved because the status cannot be calculated for start_date: {$start_date} end_date {$end_date} join_date {$join_date} as at " . date('Y-m-d H:i:s')), 0, $errorParams);
         }
         $params['status_id'] = $calcStatus['id'];
     }
     // data cleanup only: all verifications on number of related memberships are done upstream in:
     // CRM_Member_BAO_Membership::createRelatedMemberships()
     // CRM_Contact_BAO_Relationship::relatedMemberships()
     if (isset($params['owner_membership_id'])) {
         unset($params['max_related']);
     } else {
         // if membership allows related, default max_related to value in membership_type
         if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($params['membership_type_id']);
             if (isset($membershipType['relationship_type_id'])) {
                 $params['max_related'] = CRM_Utils_Array::value('max_related', $membershipType);
             }
         }
     }
     $transaction = new CRM_Core_Transaction();
     $membership = self::add($params, $ids);
     if (is_a($membership, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $membership;
     }
     // add custom field values
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
     }
     $params['membership_id'] = $membership->id;
     if (isset($ids['membership'])) {
         $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
     }
     $params['skipLineItem'] = TRUE;
     //record contribution for this membership
     if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
         $memInfo = array_merge($params, array('membership_id' => $membership->id));
         $params['contribution'] = self::recordMembershipContribution($memInfo, $ids);
     }
     if (!empty($params['lineItems'])) {
         $params['line_item'] = $params['lineItems'];
     }
     //do cleanup line  items if membership edit the Membership type.
     if (empty($ids['contribution']) && !empty($ids['membership'])) {
         CRM_Price_BAO_LineItem::deleteLineItems($ids['membership'], 'civicrm_membership');
     }
     if (!empty($params['line_item']) && empty($ids['contribution'])) {
         CRM_Price_BAO_LineItem::processPriceSet($membership->id, $params['line_item'], CRM_Utils_Array::value('contribution', $params));
     }
     //insert payment record for this membership
     if (!empty($params['relate_contribution_id'])) {
         CRM_Member_BAO_MembershipPayment::create(array('membership_id' => $membership->id, 'membership_type_id' => $membership->membership_type_id, 'contribution_id' => $params['relate_contribution_id']));
     }
     // add activity record only during create mode and renew mode
     // also add activity if status changed CRM-3984 and CRM-2521
     if (empty($ids['membership']) || $activityType == 'Membership Renewal' || !empty($params['createActivity'])) {
         if (!empty($ids['membership'])) {
             $data = array();
             CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership', 'id', $membership->id, $data, array('contact_id', 'membership_type_id', 'source'));
             $membership->contact_id = $data[$membership->id]['contact_id'];
             $membership->membership_type_id = $data[$membership->id]['membership_type_id'];
             $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]);
         }
         // since we are going to create activity record w/
         // individual contact as a target in case of on behalf signup,
         // so get the copy of organization id, CRM-5551
         $realMembershipContactId = $membership->contact_id;
         // create activity source = individual, target = org CRM-4027
         $targetContactID = NULL;
         if (!empty($params['is_for_organization'])) {
             $targetContactID = $membership->contact_id;
             $membership->contact_id = CRM_Utils_Array::value('userId', $ids);
         }
         if (empty($membership->contact_id) && !empty($membership->owner_membership_id)) {
             $membership->contact_id = $realMembershipContactId;
         }
         if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         } elseif (empty($ids['membership'])) {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         }
         // we might created activity record w/ individual
         // contact as target so update membership object w/
         // original organization id, CRM-5551
         $membership->contact_id = $realMembershipContactId;
     }
     $transaction->commit();
     self::createRelatedMemberships($params, $membership);
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         if (empty($membership->membership_type_id)) {
             // ie in an update situation.
             $membership->find(TRUE);
         }
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id];
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         // add the recently created Membership
         CRM_Utils_Recent::add($title, $url, $membership->id, 'Membership', $membership->contact_id, NULL, $recentOther);
     }
     return $membership;
 }
Exemplo n.º 30
0
 /**
  * @return array
  */
 public static function getGreetingOptions()
 {
     $options = array();
     $greetings = array('postal_greeting' => 'postal_greeting_other', 'addressee' => 'addressee_other');
     foreach ($greetings as $key => $value) {
         $params = array();
         $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $key, 'id', 'name');
         CRM_Core_DAO::commonRetrieveAll('CRM_Core_DAO_OptionValue', 'option_group_id', $optionGroupId, $params, array('label', 'filter'));
         $greetingCount = 1;
         $options[$key] = array("{$greetingCount}" => ts('List of names'));
         foreach ($params as $id => $field) {
             if (CRM_Utils_Array::value('filter', $field) == 4) {
                 $options[$key][++$greetingCount] = $field['label'];
             }
         }
         $options[$key][++$greetingCount] = ts('Other');
     }
     return $options;
 }