/**
  * Testing Activity Generation through Entity Recursion.
  */
 public function testActivityGeneration()
 {
     //Activity set initial params
     $daoActivity = new CRM_Activity_DAO_Activity();
     $daoActivity->activity_type_id = 1;
     $daoActivity->subject = "Initial Activity";
     $daoActivity->activity_date_time = '20141002103000';
     $daoActivity->save();
     $recursion = new CRM_Core_BAO_RecurringEntity();
     $recursion->entity_id = $daoActivity->id;
     $recursion->entity_table = 'civicrm_activity';
     $recursion->dateColumns = array('activity_date_time');
     $recursion->schedule = array('entity_value' => $daoActivity->id, 'start_action_date' => $daoActivity->activity_date_time, 'entity_status' => 'fourth saturday', 'repetition_frequency_unit' => 'month', 'repetition_frequency_interval' => 3, 'start_action_offset' => 5, 'used_for' => 'activity');
     $generatedEntities = $recursion->generate();
     $this->assertEquals(5, count($generatedEntities['civicrm_activity']), "Cehck if number of iterations are 5");
     $expectedDates = array('20141025103000', '20141227103000', '20150328103000', '20150627103000', '20150926103000');
     foreach ($generatedEntities['civicrm_activity'] as $entityID) {
         $this->assertDBNotNull('CRM_Activity_DAO_Activity', $entityID, 'id', 'id', 'Check DB if repeating activities were created');
     }
     // set mode to ALL, i.e any change to changing activity affects all related recurring activities
     $recursion->mode(3);
     // lets change subject of initial activity that we created in beginning
     $daoActivity->find(TRUE);
     $daoActivity->subject = 'Changed Activity';
     $daoActivity->save();
     // check if other activities were affected
     $actualDates = array();
     foreach ($generatedEntities['civicrm_activity'] as $entityID) {
         $this->assertDBCompareValue('CRM_Activity_DAO_Activity', $entityID, 'subject', 'id', 'Changed Activity', 'Check if subject was updated');
         $actualDates[] = date('YmdHis', strtotime(CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $entityID, 'activity_date_time', 'id')));
     }
     $resultDates = array_diff($actualDates, $expectedDates);
     $this->assertEquals(0, count($resultDates), "Check if all the value in expected array matches actual array");
 }
 /**
  * Get a list of Commendations matching the params, where each param key is:
  *  1. the key of a field in civicrm_activity, except for activity_type_id
  *  2. the key of a custom field on the activity (volunteer_project_id)
  *  3. the key of a field in civicrm_contact
  *
  * @param array $params
  * @return array of CRM_Volunteer_BAO_Project objects
  */
 public static function retrieve(array $params)
 {
     $activity_fields = CRM_Activity_DAO_Activity::fields();
     $contact_fields = CRM_Contact_DAO_Contact::fields();
     $custom_fields = self::getCustomFields();
     // This is the "real" id
     $activity_fields['id'] = $activity_fields['activity_id'];
     unset($activity_fields['activity_id']);
     // enforce restrictions on parameters
     $allowed_params = array_flip(array_merge(array_keys($activity_fields), array_keys($contact_fields), array_keys($custom_fields)));
     unset($allowed_params['activity_type_id']);
     $filtered_params = array_intersect_key($params, $allowed_params);
     $custom_group = self::getCustomGroup();
     $customTableName = $custom_group['table_name'];
     foreach ($custom_fields as $name => $field) {
         $selectClause[] = "{$customTableName}.{$field['column_name']} AS {$name}";
     }
     $customSelect = implode(', ', $selectClause);
     $activityContactTypes = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContactTypes);
     $placeholders = array(1 => array($targetID, 'Integer'), 2 => array(self::getActivityTypeId(), 'Integer'));
     $i = count($placeholders) + 1;
     $where = array();
     $whereClause = NULL;
     foreach ($filtered_params as $key => $value) {
         if (CRM_Utils_Array::value($key, $activity_fields)) {
             $dataType = CRM_Utils_Type::typeToString($activity_fields[$key]['type']);
             $fieldName = $activity_fields[$key]['name'];
             $tableName = CRM_Activity_DAO_Activity::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $contact_fields)) {
             $dataType = CRM_Utils_Type::typeToString($contact_fields[$key]['type']);
             $fieldName = $contact_fields[$key]['name'];
             $tableName = CRM_Contact_DAO_Contact::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $custom_fields)) {
             $dataType = $custom_fields[$key]['data_type'];
             $fieldName = $custom_fields[$key]['column_name'];
             $tableName = $customTableName;
         }
         $where[] = "{$tableName}.{$fieldName} = %{$i}";
         $placeholders[$i] = array($value, $dataType);
         $i++;
     }
     if (count($where)) {
         $whereClause = 'AND ' . implode("\nAND ", $where);
     }
     $query = "\n      SELECT\n        civicrm_activity.*,\n        {$customSelect},\n        activityContact.contact_id AS volunteer_contact_id,\n        volunteer_contact.sort_name AS volunteer_sort_name,\n        volunteer_contact.display_name AS volunteer_display_name\n      FROM civicrm_activity\n      INNER JOIN civicrm_activity_contact activityContact\n        ON (\n          activityContact.activity_id = civicrm_activity.id\n          AND activityContact.record_type_id = %1\n        )\n      INNER JOIN civicrm_contact volunteer_contact\n        ON activityContact.contact_id = volunteer_contact.id\n      INNER JOIN {$customTableName}\n        ON ({$customTableName}.entity_id = civicrm_activity.id)\n      WHERE civicrm_activity.activity_type_id = %2\n      {$whereClause}\n    ";
     $dao = CRM_Core_DAO::executeQuery($query, $placeholders);
     $rows = array();
     while ($dao->fetch()) {
         $rows[$dao->id] = $dao->toArray();
     }
     return $rows;
 }
/**
 * take the input parameter list as specified in the data model and
 * convert it into the same format that we use in QF and BAO object
 *
 * @param array $params
 *   Associative array of property name/value.
 *                             pairs to insert in new contact.
 * @param array $values
 *   The reformatted properties that we can use internally.
 *
 * @param array|bool $create Is the formatted Values array going to
 *                             be used for CRM_Activity_BAO_Activity::create()
 *
 * @return array|CRM_Error
 */
function _civicrm_api3_deprecated_activity_formatted_param(&$params, &$values, $create = FALSE)
{
    // copy all the activity fields as is
    $fields = CRM_Activity_DAO_Activity::fields();
    _civicrm_api3_store_values($fields, $params, $values);
    require_once 'CRM/Core/OptionGroup.php';
    $customFields = CRM_Core_BAO_CustomField::getFields('Activity');
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        //Handling Custom Data
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            $values[$key] = $value;
            $type = $customFields[$customFieldID]['html_type'];
            if ($type == 'CheckBox' || $type == 'Multi-Select') {
                $mulValues = explode(',', $value);
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                $values[$key] = array();
                foreach ($mulValues as $v1) {
                    foreach ($customOption as $customValueID => $customLabel) {
                        $customValue = $customLabel['value'];
                        if (strtolower(trim($customLabel['label'])) == strtolower(trim($v1)) || strtolower(trim($customValue)) == strtolower(trim($v1))) {
                            if ($type == 'CheckBox') {
                                $values[$key][$customValue] = 1;
                            } else {
                                $values[$key][] = $customValue;
                            }
                        }
                    }
                }
            } elseif ($type == 'Select' || $type == 'Radio') {
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                foreach ($customOption as $customFldID => $customValue) {
                    $val = CRM_Utils_Array::value('value', $customValue);
                    $label = CRM_Utils_Array::value('label', $customValue);
                    $label = strtolower($label);
                    $value = strtolower(trim($value));
                    if ($value == $label || $value == strtolower($val)) {
                        $values[$key] = $val;
                    }
                }
            }
        }
        if ($key == 'target_contact_id') {
            if (!CRM_Utils_Rule::integer($value)) {
                return civicrm_api3_create_error("contact_id not valid: {$value}");
            }
            $contactID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}");
            if (!$contactID) {
                return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
            }
        }
    }
    return NULL;
}
Exemple #4
0
 static function convertToCaseActivity()
 {
     $params = array('caseID', 'activityID', 'contactID', 'newSubject', 'targetContactIds', 'mode');
     foreach ($params as $param) {
         ${$param} = CRM_Utils_Array::value($param, $_POST);
     }
     if (!$activityID || !$caseID) {
         echo json_encode(array('error_msg' => 'required params missing.'));
         CRM_Utils_System::civiExit();
     }
     require_once "CRM/Activity/DAO/Activity.php";
     $otherActivity = new CRM_Activity_DAO_Activity();
     $otherActivity->id = $activityID;
     if (!$otherActivity->find(true)) {
         echo json_encode(array('error_msg' => 'activity record is missing.'));
         CRM_Utils_System::civiExit();
     }
     $actDateTime = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
     //create new activity record.
     $mainActivity = new CRM_Activity_DAO_Activity();
     $mainActVals = array();
     CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
     //get new activity subject.
     if (!empty($newSubject)) {
         $mainActVals['subject'] = $newSubject;
     }
     $mainActivity->copyValues($mainActVals);
     $mainActivity->id = null;
     $mainActivity->activity_date_time = $actDateTime;
     //make sure this is current revision.
     $mainActivity->is_current_revision = true;
     //drop all relations.
     $mainActivity->parent_id = $mainActivity->original_id = null;
     $mainActivity->save();
     $mainActivityId = $mainActivity->id;
     require_once 'CRM/Activity/BAO/Activity.php';
     CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
     $mainActivity->free();
     //mark previous activity as deleted.
     if (in_array($mode, array('move', 'file'))) {
         $otherActivity->activity_date_time = $actDateTime;
         $otherActivity->is_deleted = 1;
         $otherActivity->save();
     }
     $otherActivity->free();
     require_once "CRM/Activity/BAO/Activity.php";
     $targetContacts = array();
     if (!empty($targetContactIds)) {
         $targetContacts = array_unique(explode(',', $targetContactIds));
     }
     foreach ($targetContacts as $key => $value) {
         $params = array('activity_id' => $mainActivityId, 'target_contact_id' => $value);
         CRM_Activity_BAO_Activity::createActivityTarget($params);
     }
     //attach newly created activity to case.
     require_once "CRM/Case/DAO/CaseActivity.php";
     $caseActivity = new CRM_Case_DAO_CaseActivity();
     $caseActivity->case_id = $caseID;
     $caseActivity->activity_id = $mainActivityId;
     $caseActivity->save();
     $error_msg = $caseActivity->_lastError;
     $caseActivity->free();
     echo json_encode(array('error_msg' => $error_msg));
     CRM_Utils_System::civiExit();
 }
 /**
  * returns the list of fields that can be exported
  *
  * @access public
  * return array
  * @static
  */
 static function &export($prefix = false)
 {
     if (!self::$_export) {
         self::$_export = array();
         $fields = self::fields();
         foreach ($fields as $name => $field) {
             if (CRM_Utils_Array::value('export', $field)) {
                 if ($prefix) {
                     self::$_export['activity'] =& $fields[$name];
                 } else {
                     self::$_export[$name] =& $fields[$name];
                 }
             }
         }
     }
     return self::$_export;
 }
 /**
  * Takes an associative array and creates a contribution object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  *
  * @return CRM_Contribute_BAO_Contribution
  */
 public static function create(&$params, $ids = array())
 {
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     $transaction = new CRM_Core_Transaction();
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
     }
     $session = CRM_Core_Session::singleton();
     if (!empty($params['note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams);
     }
     // make entry in batch entity batch table
     if (!empty($params['batch_id'])) {
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id');
         $retrieveRequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieveRequired = 1;
                 break;
             }
         }
         if ($retrieveRequired == 1) {
             $contribution->find(TRUE);
         }
     }
     // Handle soft credit and / or link to personal campaign page
     $softIDs = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id);
     $pcpId = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id, TRUE);
     if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
         $softParams = array();
         $softParams['id'] = $pcpId ? $pcpId : NULL;
         $softParams['contribution_id'] = $contribution->id;
         $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
         $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp['pcp_made_through_id'], 'contact_id');
         $softParams['currency'] = $contribution->currency;
         $softParams['amount'] = $contribution->total_amount;
         $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
         $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
         $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
         $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
         $contributionSoft = CRM_Contribute_BAO_ContributionSoft::add($softParams);
         //Send notification to owner for PCP
         if ($contributionSoft->pcp_id && empty($pcpId)) {
             CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
         }
     } elseif (array_key_exists('pcp', $params) && $pcpId) {
         $deleteParams = array('id' => $pcpId);
         CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
     }
     if (isset($params['soft_credit'])) {
         $softParams = $params['soft_credit'];
         foreach ($softParams as $softParam) {
             if (!empty($softIDs)) {
                 $key = key($softIDs);
                 $softParam['id'] = $softIDs[$key];
                 unset($softIDs[$key]);
             }
             $softParam['contribution_id'] = $contribution->id;
             $softParam['currency'] = $contribution->currency;
             //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
             if (empty($softParam['amount'])) {
                 $softParam['amount'] = $contribution->total_amount;
             }
             CRM_Contribute_BAO_ContributionSoft::add($softParam);
         }
         if (!empty($softIDs)) {
             foreach ($softIDs as $softID) {
                 if (!in_array($softID, $params['soft_credit_ids'])) {
                     $deleteParams = array('id' => $softID);
                     CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
                 }
             }
         }
     }
     $transaction->commit();
     // check if activity record exist for this contribution, if
     // not add activity
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find(TRUE)) {
         if (empty($contribution->contact_id)) {
             $contribution->find(TRUE);
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     } else {
         // CRM-13237 : if activity record found, update it with campaign id of contribution
         CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
     }
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id');
         $retrieveRequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieveRequired = 1;
                 break;
             }
         }
         if ($retrieveRequired == 1) {
             $contribution->find(TRUE);
         }
         $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, NULL, $recentOther);
     }
     return $contribution;
 }
 /**
  * Does user has sufficient permission for view/edit activity record.
  *
  * @param int $activityId
  *   Activity record id.
  * @param int $action
  *   Edit/view.
  *
  * @return bool
  */
 public static function checkPermission($activityId, $action)
 {
     $allow = FALSE;
     if (!$activityId || !in_array($action, array(CRM_Core_Action::UPDATE, CRM_Core_Action::VIEW))) {
         return $allow;
     }
     $activity = new CRM_Activity_DAO_Activity();
     $activity->id = $activityId;
     if (!$activity->find(TRUE)) {
         return $allow;
     }
     // Component related permissions.
     $compPermissions = array('CiviCase' => array('administer CiviCase', 'access my cases and activities', 'access all cases and activities'), 'CiviMail' => array('access CiviMail'), 'CiviEvent' => array('access CiviEvent'), 'CiviGrant' => array('access CiviGrant'), 'CiviPledge' => array('access CiviPledge'), 'CiviMember' => array('access CiviMember'), 'CiviReport' => array('access CiviReport'), 'CiviContribute' => array('access CiviContribute'), 'CiviCampaign' => array('administer CiviCampaign'));
     // Return early when it is case activity.
     $isCaseActivity = CRM_Case_BAO_Case::isCaseActivity($activityId);
     // Check for civicase related permission.
     if ($isCaseActivity) {
         $allow = FALSE;
         foreach ($compPermissions['CiviCase'] as $per) {
             if (CRM_Core_Permission::check($per)) {
                 $allow = TRUE;
                 break;
             }
         }
         // Check for case specific permissions.
         if ($allow) {
             $oper = 'view';
             if ($action == CRM_Core_Action::UPDATE) {
                 $oper = 'edit';
             }
             $allow = CRM_Case_BAO_Case::checkPermission($activityId, $oper, $activity->activity_type_id);
         }
         return $allow;
     }
     // First check the component permission.
     $sql = "\n    SELECT  component_id\n      FROM  civicrm_option_value val\nINNER JOIN  civicrm_option_group grp ON ( grp.id = val.option_group_id AND grp.name = %1 )\n     WHERE  val.value = %2";
     $params = array(1 => array('activity_type', 'String'), 2 => array($activity->activity_type_id, 'Integer'));
     $componentId = CRM_Core_DAO::singleValueQuery($sql, $params);
     if ($componentId) {
         $componentName = CRM_Core_Component::getComponentName($componentId);
         $compPermission = CRM_Utils_Array::value($componentName, $compPermissions);
         // Here we are interesting in any single permission.
         if (is_array($compPermission)) {
             foreach ($compPermission as $per) {
                 if (CRM_Core_Permission::check($per)) {
                     $allow = TRUE;
                     break;
                 }
             }
         }
     }
     // Check for this permission related to contact.
     $permission = CRM_Core_Permission::VIEW;
     if ($action == CRM_Core_Action::UPDATE) {
         $permission = CRM_Core_Permission::EDIT;
     }
     $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);
     // Check for source contact.
     if (!$componentId || $allow) {
         $sourceContactId = self::getActivityContact($activity->id, $sourceID);
         // Account for possibility of activity not having a source contact (as it may have been deleted).
         if ($sourceContactId) {
             $allow = CRM_Contact_BAO_Contact_Permission::allow($sourceContactId, $permission);
         }
     }
     // Check for target and assignee contacts.
     if ($allow) {
         // First check for supper permission.
         $supPermission = 'view all contacts';
         if ($action == CRM_Core_Action::UPDATE) {
             $supPermission = 'edit all contacts';
         }
         $allow = CRM_Core_Permission::check($supPermission);
         // User might have sufficient permission, through acls.
         if (!$allow) {
             $allow = TRUE;
             // Get the target contacts.
             $targetContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $targetID);
             foreach ($targetContacts as $cnt => $contactId) {
                 if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
                     $allow = FALSE;
                     break;
                 }
             }
             // Get the assignee contacts.
             if ($allow) {
                 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($activity->id, $assigneeID);
                 foreach ($assigneeContacts as $cnt => $contactId) {
                     if (!CRM_Contact_BAO_Contact_Permission::allow($contactId, $permission)) {
                         $allow = FALSE;
                         break;
                     }
                 }
             }
         }
     }
     return $allow;
 }
 /**
  * check survey activity.
  *
  * @param int $activityId
  *   Activity id.
  * @return bool
  */
 public static function isSurveyActivity($activityId)
 {
     $isSurveyActivity = FALSE;
     if (!$activityId) {
         return $isSurveyActivity;
     }
     $activity = new CRM_Activity_DAO_Activity();
     $activity->id = $activityId;
     $activity->selectAdd('source_record_id, activity_type_id');
     if ($activity->find(TRUE) && $activity->source_record_id) {
         $surveyActTypes = self::getSurveyActivityType();
         if (array_key_exists($activity->activity_type_id, $surveyActTypes)) {
             $isSurveyActivity = TRUE;
         }
     }
     return $isSurveyActivity;
 }
 /**
  * Process the form submission.
  *
  *
  * @param array $params
  *
  * @return void
  */
 public function postProcess($params = NULL)
 {
     $transaction = new CRM_Core_Transaction();
     if ($this->_action & CRM_Core_Action::DELETE) {
         $statusMsg = NULL;
         //block deleting activities which affects
         //case attributes.CRM-4543
         $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
         $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
         if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
             $params = array('id' => $this->_activityId);
             $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, TRUE);
             if ($activityDelete) {
                 $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />');
             }
         } else {
             $statusMsg = ts("Selected Activity cannot be deleted.");
         }
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus('', $statusMsg, 'info');
         return;
     }
     if ($this->_action & CRM_Core_Action::RENEW) {
         $statusMsg = NULL;
         $params = array('id' => $this->_activityId);
         $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
         if ($activityRestore) {
             $statusMsg = ts('The selected activity has been restored.<br />');
         }
         CRM_Core_Session::setStatus('', $statusMsg, 'info');
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     //set parent id if its edit mode
     if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
         $params['parent_id'] = $parentId;
     }
     // store the dates with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     $params['activity_type_id'] = $this->_activityTypeId;
     // format with contact (target contact) values
     if (isset($params['target_contact_id'])) {
         $params['target_contact_id'] = explode(',', $params['target_contact_id']);
     } else {
         $params['target_contact_id'] = array();
     }
     // format activity custom data
     if (!empty($params['hidden_custom'])) {
         if ($this->_activityId) {
             // unset custom fields-id from params since we want custom
             // fields to be saved for new activity.
             foreach ($params as $key => $value) {
                 $match = array();
                 if (preg_match('/^(custom_\\d+_)(\\d+)$/', $key, $match)) {
                     $params[$match[1] . '-1'] = $params[$key];
                     // for autocomplete transfer hidden value instead of label
                     if ($params[$key] && isset($params[$key . '_id'])) {
                         $params[$match[1] . '-1_id'] = $params[$key . '_id'];
                         unset($params[$key . '_id']);
                     }
                     unset($params[$key]);
                 }
             }
         }
         // build custom data getFields array
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, NULL, NULL, TRUE));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_activityId, 'Activity');
     }
     // assigning formatted value
     if (!empty($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = array();
     }
     if (isset($this->_activityId)) {
         // activity which hasn't been modified by a user yet
         if ($this->_defaults['is_auto'] == 1) {
             $params['is_auto'] = 0;
         }
         // always create a revision of an case activity. CRM-4533
         $newActParams = $params;
         // add target contact values in update mode
         if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
             $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
         }
     }
     if (!isset($newActParams)) {
         // add more attachments if needed for old activity
         CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($params);
         foreach ($this->_caseId as $key => $val) {
             $params['case_id'] = $val;
             // activity create/update
             $activity = CRM_Activity_BAO_Activity::create($params);
             $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
             // call end post process, after the activity has been created/updated.
             $this->endPostProcess($params, $activity);
         }
     } else {
         // since the params we need to set are very few, and we don't want rest of the
         // work done by bao create method , lets use dao object to make the changes
         $params = array('id' => $this->_activityId);
         $params['is_current_revision'] = 0;
         $activity = new CRM_Activity_DAO_Activity();
         $activity->copyValues($params);
         $activity->save();
     }
     // create a new version of activity if activity was found to
     // have been modified/created by user
     if (isset($newActParams)) {
         // set proper original_id
         if (!empty($this->_defaults['original_id'])) {
             $newActParams['original_id'] = $this->_defaults['original_id'];
         } else {
             $newActParams['original_id'] = $activity->id;
         }
         //is_current_revision will be set to 1 by default.
         // add attachments if any
         CRM_Core_BAO_File::formatAttachment($newActParams, $newActParams, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($newActParams);
         foreach ($this->_caseId as $key => $val) {
             $newActParams['case_id'] = $val;
             $activity = CRM_Activity_BAO_Activity::create($newActParams);
             $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
             // call end post process, after the activity has been created/updated.
             $this->endPostProcess($newActParams, $activity);
         }
         // copy files attached to old activity if any, to new one,
         // as long as users have not selected the 'delete attachment' option.
         if (empty($newActParams['is_delete_attachment'])) {
             CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId, 'civicrm_activity', $activity->id);
         }
         // copy back params to original var
         $params = $newActParams;
     }
     foreach ($vvalue as $vkey => $vval) {
         if ($vval['actId']) {
             // add tags if exists
             $tagParams = array();
             if (!empty($params['tag'])) {
                 foreach ($params['tag'] as $tag) {
                     $tagParams[$tag] = 1;
                 }
             }
             //save static tags
             CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $vval['actId']);
             //save free tags
             if (isset($params['taglist']) && !empty($params['taglist'])) {
                 CRM_Core_Form_Tag::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
             }
         }
         // update existing case record if needed
         $caseParams = $params;
         $caseParams['id'] = $vval['case_id'];
         if (!empty($caseParams['case_status_id'])) {
             $caseParams['status_id'] = $caseParams['case_status_id'];
         }
         // unset params intended for activities only
         unset($caseParams['subject'], $caseParams['details'], $caseParams['status_id'], $caseParams['custom']);
         $case = CRM_Case_BAO_Case::create($caseParams);
         // create case activity record
         $caseParams = array('activity_id' => $vval['actId'], 'case_id' => $vval['case_id']);
         CRM_Case_BAO_Case::processCaseActivity($caseParams);
     }
     // Insert civicrm_log record for the activity (e.g. store the
     // created / edited by contact id and date for the activity)
     // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
     // send copy to selected contacts.
     $mailStatus = '';
     $mailToContacts = array();
     //CRM-5695
     //check for notification settings for assignee contacts
     $selectedContacts = array('contact_check');
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'activity_assignee_notification')) {
         $selectedContacts[] = 'assignee_contact_id';
     }
     foreach ($vvalue as $vkey => $vval) {
         foreach ($selectedContacts as $dnt => $val) {
             if (array_key_exists($val, $params) && !CRM_Utils_array::crmIsEmptyArray($params[$val])) {
                 if ($val == 'contact_check') {
                     $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
                 } else {
                     $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
                     $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
                 }
                 //build an associative array with unique email addresses.
                 foreach ($params[$val] as $key => $value) {
                     if ($val == 'contact_check') {
                         $id = $key;
                     } else {
                         $id = $value;
                     }
                     if (isset($id) && array_key_exists($id, $this->_relatedContacts) && isset($this->_relatedContacts[$id]['email'])) {
                         //if email already exists in array then append with ', ' another role only otherwise add it to array.
                         if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
                             $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
                             $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
                         } else {
                             $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
                         }
                     }
                 }
             }
         }
         $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId);
         $result = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts, $extraParams);
         if (empty($result)) {
             $mailStatus = '';
         }
         // create follow up activity if needed
         $followupStatus = '';
         if (!empty($params['followup_activity_type_id'])) {
             $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($vval['actId'], $params);
             if ($followupActivity) {
                 $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $vval['case_id']);
                 CRM_Case_BAO_Case::processCaseActivity($caseParams);
                 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
             }
         }
         $title = ts("%1 Saved", array(1 => $this->_activityTypeName));
         CRM_Core_Session::setStatus($followupStatus . $mailStatus, $title, 'success');
     }
 }
Exemple #10
0
 /**
  * This function delete activity record related to contact record,
  * when there are no target and assignee record w/ other contact.
  *
  * @param  int $contactId contactId
  *
  * @return true/null
  * @access public
  */
 public function cleanupActivity($contactId)
 {
     $result = null;
     if (!$contactId) {
         return $result;
     }
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     // delete activity if there are no record in
     // civicrm_activity_assignment or civicrm_activity_target
     // pointing to any other contact record.
     require_once 'CRM/Activity/DAO/ActivityTarget.php';
     require_once 'CRM/Activity/DAO/ActivityAssignment.php';
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_contact_id = $contactId;
     $activity->find();
     while ($activity->fetch()) {
         $noTarget = $noAssignee = true;
         // check for target activity record.
         $target = new CRM_Activity_DAO_ActivityTarget();
         $target->activity_id = $activity->id;
         $target->find();
         while ($target->fetch()) {
             if ($target->target_contact_id != $contactId) {
                 $noTarget = false;
                 break;
             }
         }
         $target->free();
         // check for assignee activity record.
         $assignee = new CRM_Activity_DAO_ActivityAssignment();
         $assignee->activity_id = $activity->id;
         $assignee->find();
         while ($assignee->fetch()) {
             if ($assignee->assignee_contact_id != $contactId) {
                 $noAssignee = false;
                 break;
             }
         }
         $assignee->free();
         // finally delete activity.
         if ($noTarget && $noAssignee) {
             $activityParams = array('id' => $activity->id);
             $result = self::deleteActivity($activityParams);
         }
     }
     $activity->free();
     $transaction->commit();
     return $result;
 }
Exemple #11
0
/**
 * take the input parameter list as specified in the data model and 
 * convert it into the same format that we use in QF and BAO object
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs to insert in new contact.
 * @param array  $values       The reformatted properties that we can use internally
 *
 * @param array  $create       Is the formatted Values array going to
 *                             be used for CRM_Activity_BAO_Activity::create()
 *
 * @return array|CRM_Error
 * @access public
 */
function _civicrm_activity_formatted_param(&$params, &$values, $create = false)
{
    $fields =& CRM_Activity_DAO_Activity::fields();
    _civicrm_store_values($fields, $params, $values);
    require_once 'CRM/Core/OptionGroup.php';
    $customFields = CRM_Core_BAO_CustomField::getFields('Activity');
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        //Handling Custom Data
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            $values[$key] = $value;
            $type = $customFields[$customFieldID]['html_type'];
            if ($type == 'CheckBox' || $type == 'Multi-Select') {
                $mulValues = explode(',', $value);
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                $values[$key] = array();
                foreach ($mulValues as $v1) {
                    foreach ($customOption as $customValueID => $customLabel) {
                        $customValue = $customLabel['value'];
                        if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            if ($type == 'CheckBox') {
                                $values[$key][$customValue] = 1;
                            } else {
                                $values[$key][] = $customValue;
                            }
                        }
                    }
                }
            } else {
                if ($type == 'Select' || $type == 'Radio') {
                    $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
                    foreach ($customOption as $customValue => $customLabel) {
                        if (strtolower($customLabel) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            $values[$key] = $customValue;
                        }
                    }
                }
            }
        }
    }
    return null;
}
 /**
  * @param array $params
  *
  * @return mixed
  */
 public static function registerInterview($params)
 {
     $activityId = CRM_Utils_Array::value('activity_id', $params);
     $surveyTypeId = CRM_Utils_Array::value('activity_type_id', $params);
     if (!is_array($params) || !$surveyTypeId || !$activityId) {
         return FALSE;
     }
     static $surveyFields;
     if (!is_array($surveyFields)) {
         $surveyFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $surveyTypeId, NULL, FALSE, TRUE);
     }
     static $statusId;
     if (!$statusId) {
         $statusId = array_search('Completed', CRM_Core_PseudoConstant::activityStatus('name'));
     }
     //format custom fields.
     $customParams = CRM_Core_BAO_CustomField::postProcess($params, $activityId, 'Activity');
     CRM_Core_BAO_CustomValueTable::store($customParams, 'civicrm_activity', $activityId);
     //process contact data.
     $contactParams = $fields = array();
     $contactFieldTypes = array_merge(array('Contact'), CRM_Contact_BAO_ContactType::basicTypes());
     $responseFields = CRM_Campaign_BAO_Survey::getSurveyResponseFields($params['survey_id']);
     if (!empty($responseFields)) {
         foreach ($params as $key => $value) {
             if (array_key_exists($key, $responseFields)) {
                 if (in_array($responseFields[$key]['field_type'], $contactFieldTypes)) {
                     $fields[$key] = $responseFields[$key];
                     $contactParams[$key] = $value;
                     if (isset($params["{$key}_id"])) {
                         $contactParams["{$key}_id"] = $params["{$key}_id"];
                     }
                 }
             }
         }
     }
     $contactId = CRM_Utils_Array::value('voter_id', $params);
     if ($contactId && !empty($contactParams)) {
         CRM_Contact_BAO_Contact::createProfileContact($contactParams, $fields, $contactId);
     }
     //update activity record.
     $activity = new CRM_Activity_DAO_Activity();
     $activity->id = $activityId;
     $activity->selectAdd();
     $activity->selectAdd('activity_date_time, status_id, result, subject');
     $activity->find(TRUE);
     $activity->activity_date_time = date('YmdHis');
     $activity->status_id = $statusId;
     if (!empty($params['activity_date_time'])) {
         $activity->activity_date_time = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     }
     $subject = '';
     $surveyTitle = CRM_Utils_Array::value('surveyTitle', $params);
     if ($surveyTitle) {
         $subject = $surveyTitle . ' - ';
     }
     $subject .= ts('Respondent Interview');
     $activity->subject = $subject;
     $activityParams = array('details' => 'details', 'result' => 'result', 'engagement_level' => 'activity_engagement_level', 'subject' => 'activity_subject', 'status_id' => 'activity_status_id', 'source_contact_id' => 'source_contact', 'location' => 'activity_location', 'campaign_id' => 'activity_campaign_id', 'duration' => 'activity_duration');
     foreach ($activityParams as $key => $field) {
         if (!empty($params[$field])) {
             $activity->{$key} = $params[$field];
         }
     }
     $activity->save();
     //really this should use Activity BAO& not be here but refactoring will have to be later
     //actually the whole ajax call could be done as an api ajax call & post hook would be sorted
     CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
     $activity->free();
     return $activityId;
 }
 static function registerInterview($params)
 {
     $activityId = CRM_Utils_Array::value('activity_id', $params);
     $surveyTypeId = CRM_Utils_Array::value('activity_type_id', $params);
     if (!is_array($params) || !$surveyTypeId || !$activityId) {
         return false;
     }
     static $surveyFields;
     if (!is_array($surveyFields)) {
         require_once 'CRM/Core/BAO/CustomField.php';
         $surveyFields = CRM_Core_BAO_CustomField::getFields('Activity', false, false, $surveyTypeId, null, false, true);
     }
     static $statusId;
     if (!$statusId) {
         require_once 'CRM/Core/PseudoConstant.php';
         $statusId = array_search('Completed', CRM_Core_PseudoConstant::activityStatus('name'));
     }
     //format custom fields.
     $customParams = CRM_Core_BAO_CustomField::postProcess($params, $surveyFields, $activityId, 'Activity');
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     CRM_Core_BAO_CustomValueTable::store($customParams, 'civicrm_activity', $activityId);
     //update activity record.
     require_once 'CRM/Activity/DAO/Activity.php';
     $activity = new CRM_Activity_DAO_Activity();
     $activity->id = $activityId;
     $activity->selectAdd();
     $activity->selectAdd('activity_date_time, status_id, result, subject');
     $activity->find(true);
     $activity->activity_date_time = date('Ymdhis');
     $activity->status_id = $statusId;
     if (CRM_Utils_Array::value('details', $params)) {
         $activity->details = $params['details'];
     }
     if ($result = CRM_Utils_Array::value('result', $params)) {
         $activity->result = $result;
     }
     $subject = '';
     $surveyTitle = CRM_Utils_Array::value('surveyTitle', $params);
     if ($surveyTitle) {
         $subject = ts('%1', array(1 => $surveyTitle));
         $subject .= ' - ';
     }
     $subject .= ts('Respondent Interview');
     $activity->subject = $subject;
     $activity->save();
     $activity->free();
     return $activityId;
 }
/**
 * Creates or updates an Activity. See the example for usage
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs for the activity.
 * {@getfields activity_create}
 *
 * @return array Array containing 'is_error' to denote success or failure and details of the created activity
 *
 * @example ActivityCreate.php Standard create example
 * @example Activity/ContactRefCustomField.php Create example including setting a contact reference custom field
 * {@example ActivityCreate.php 0}
 *
 */
function civicrm_api3_activity_create($params)
{
    if (!CRM_Utils_Array::value('id', $params)) {
        // an update does not require any mandatory parameters
        civicrm_api3_verify_one_mandatory($params, NULL, array('activity_name', 'activity_type_id', 'activity_label'));
    }
    $errors = array();
    // check for various error and required conditions
    $errors = _civicrm_api3_activity_check_params($params);
    if (!empty($errors)) {
        return $errors;
    }
    // processing for custom data
    $values = array();
    _civicrm_api3_custom_format_params($params, $values, 'Activity');
    if (!empty($values['custom'])) {
        $params['custom'] = $values['custom'];
    }
    $params['skipRecentView'] = TRUE;
    // If this is a case activity, see if there is an existing activity
    // and set it as an old revision. Also retrieve details we'll need.
    $case_id = '';
    $createRevision = FALSE;
    $oldActivityValues = array();
    if (CRM_Utils_Array::value('case_id', $params)) {
        $case_id = $params['case_id'];
        if (CRM_Utils_Array::value('id', $params)) {
            $oldActivityParams = array('id' => $params['id']);
            if (!$oldActivityValues) {
                CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
            }
            if (empty($oldActivityValues)) {
                return civicrm_api3_create_error(ts("Unable to locate existing activity."), NULL, CRM_Core_DAO::$_nullObject);
            } else {
                require_once 'CRM/Activity/DAO/Activity.php';
                $activityDAO = new CRM_Activity_DAO_Activity();
                $activityDAO->id = $params['id'];
                $activityDAO->is_current_revision = 0;
                if (!$activityDAO->save()) {
                    return civicrm_api3_create_error(ts("Unable to revision existing case activity."), NULL, $activityDAO);
                }
                $createRevision = TRUE;
            }
        }
    }
    $deleteActivityAssignment = FALSE;
    if (isset($params['assignee_contact_id'])) {
        $deleteActivityAssignment = TRUE;
    }
    $deleteActivityTarget = FALSE;
    if (isset($params['target_contact_id'])) {
        $deleteActivityTarget = TRUE;
    }
    $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
    $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
    if ($case_id && $createRevision) {
        // This is very similar to the copy-to-case action.
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
            $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
        }
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
            $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
        }
        $oldActivityValues['mode'] = 'copy';
        $oldActivityValues['caseID'] = $case_id;
        $oldActivityValues['activityID'] = $oldActivityValues['id'];
        $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
        require_once 'CRM/Activity/Page/AJAX.php';
        $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
        if (empty($copyToCase['error_msg'])) {
            // now fix some things that are different from copy-to-case
            // then fall through to the create below to update with the passed in params
            $params['id'] = $copyToCase['newId'];
            $params['is_auto'] = 0;
            $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
        } else {
            return civicrm_api3_create_error(ts("Unable to create new revision of case activity."), NULL, CRM_Core_DAO::$_nullObject);
        }
    }
    // create activity
    $activityBAO = CRM_Activity_BAO_Activity::create($params);
    if (isset($activityBAO->id)) {
        if ($case_id && !$createRevision) {
            // If this is a brand new case activity we need to add this
            $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
            require_once 'CRM/Case/BAO/Case.php';
            CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
        }
        _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
        return civicrm_api3_create_success($activityArray, $params, 'activity', 'get', $activityBAO);
    }
}
 static function recordAdditionPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL)
 {
     $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
     $getInfoOf['id'] = $contributionId;
     $defaults = array();
     $contributionDAO = CRM_Contribute_BAO_Contribution::retrieve($getInfoOf, $defaults, CRM_Core_DAO::$_nullArray);
     if ($paymentType == 'owed') {
         // build params for recording financial trxn entry
         $params['contribution'] = $contributionDAO;
         $params = array_merge($defaults, $params);
         $params['skipLineItem'] = TRUE;
         $params['partial_payment_total'] = $contributionDAO->total_amount;
         $params['partial_amount_pay'] = $trxnsData['total_amount'];
         $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
         // record the entry
         $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
         $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Receivable Account is' "));
         $toFinancialAccount = CRM_Contribute_PseudoConstant::financialAccountType($contributionDAO->financial_type_id, $relationTypeId);
         $trxnId = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId, $contributionDAO->financial_type_id);
         $trxnId = $trxnId['trxn_id'];
         // update statuses
         // criteria for updates contribution total_amount == financial_trxns of partial_payments
         $sql = "SELECT SUM(ft.total_amount) as sum_of_payments\nFROM civicrm_financial_trxn ft\nLEFT JOIN civicrm_entity_financial_trxn eft\n  ON (ft.id = eft.financial_trxn_id)\nWHERE eft.entity_table = 'civicrm_contribution'\n  AND eft.entity_id = {$contributionId}\n  AND ft.to_financial_account_id != {$toFinancialAccount}\n  AND ft.status_id = {$statusId}\n";
         $sumOfPayments = CRM_Core_DAO::singleValueQuery($sql);
         // update statuses
         if ($contributionDAO->total_amount == $sumOfPayments) {
             // update contribution status
             $contributionUpdate['id'] = $contributionId;
             $contributionUpdate['contribution_status_id'] = $statusId;
             $contributionUpdate['skipLineItem'] = TRUE;
             // note : not using the self::add method,
             // the reason because it performs 'status change' related code execution for financial records
             // which in 'Partial Paid' => 'Completed' is not useful, instead specific financial record updates
             // are coded below i.e. just updating financial_item status to 'Paid'
             $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
             if ($participantId) {
                 // update participant status
                 $participantUpdate['id'] = $participantId;
                 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
                 $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
                 CRM_Event_BAO_Participant::add($participantUpdate);
             }
             // update financial item statuses
             $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
             $paidStatus = array_search('Paid', $financialItemStatus);
             $sqlFinancialItemUpdate = "\nUPDATE civicrm_financial_item fi\n  LEFT JOIN civicrm_entity_financial_trxn eft\n    ON (eft.entity_id = fi.id AND eft.entity_table = 'civicrm_financial_item')\nSET status_id = {$paidStatus}\nWHERE eft.financial_trxn_id = {$trxnId}\n";
             CRM_Core_DAO::executeQuery($sqlFinancialItemUpdate);
         }
     } elseif ($paymentType == 'refund') {
         // build params for recording financial trxn entry
         $params['contribution'] = $contributionDAO;
         $params = array_merge($defaults, $params);
         $params['skipLineItem'] = TRUE;
         $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
         $trxnsData['total_amount'] = -$trxnsData['total_amount'];
         $trxnsData['status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', 'Refunded', 'name');
         // record the entry
         $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
         // note : not using the self::add method,
         // the reason because it performs 'status change' related code execution for financial records
         // which in 'Pending Refund' => 'Completed' is not useful, instead specific financial record updates
         // are coded below i.e. just updating financial_item status to 'Paid'
         $contributionDetails = CRM_Core_DAO::setFieldValue('CRM_Contribute_BAO_Contribution', $contributionId, 'contribution_status_id', $statusId);
         // add financial item entry
         $financialItemStatus = CRM_Core_PseudoConstant::get('CRM_Financial_DAO_FinancialItem', 'status_id');
         $getLine['entity_id'] = $contributionDAO->id;
         $getLine['entity_table'] = 'civicrm_contribution';
         $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
         $addFinancialEntry = array('transaction_date' => $financialTrxn->trxn_date, 'contact_id' => $contributionDAO->contact_id, 'amount' => $financialTrxn->total_amount, 'status_id' => array_search('Paid', $financialItemStatus), 'entity_id' => $lineItemId->id, 'entity_table' => 'civicrm_line_item');
         $trxnIds['id'] = $financialTrxn->id;
         CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
         if ($participantId) {
             // update participant status
             $participantUpdate['id'] = $participantId;
             $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
             $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
             CRM_Event_BAO_Participant::add($participantUpdate);
         }
     }
     // activity creation
     if (!empty($financialTrxn)) {
         if ($participantId) {
             $inputParams['id'] = $participantId;
             $values = array();
             $ids = array();
             $component = 'event';
             $entityObj = CRM_Event_BAO_Participant::getValues($inputParams, $values, $ids);
             $entityObj = $entityObj[$participantId];
         }
         $activityType = $paymentType == 'refund' ? 'Refund' : 'Payment';
         // creation of activity
         $activity = new CRM_Activity_DAO_Activity();
         $activity->source_record_id = $financialTrxn->id;
         $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name');
         if (!$activity->find(TRUE)) {
             self::addActivityForPayment($entityObj, $financialTrxn, $activityType, $component);
         }
     }
     return $financialTrxn;
 }
Exemple #16
0
 static function isSurveyActivity($activityId)
 {
     $isSurveyActivity = false;
     if (!$activityId) {
         return $isSurveyActivity;
     }
     require_once 'CRM/Activity/DAO/Activity.php';
     $activity = new CRM_Activity_DAO_Activity();
     $activity->id = $activityId;
     $activity->selectAdd('source_record_id, activity_type_id');
     if ($activity->find(true) && $activity->source_record_id) {
         $surveyActTypes = self::getSurveyActivityType();
         if (array_key_exists($activity->activity_type_id, $surveyActTypes)) {
             $isSurveyActivity = true;
         }
     }
     return $isSurveyActivity;
 }
 /**
  * Process the form submission.
  *
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param $activity
  */
 public static function endPostProcess(&$form, &$params, $activity)
 {
     if (!empty($params['start_date'])) {
         $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
     }
     $caseType = CRM_Utils_Array::first($form->_caseType);
     $caseId = CRM_Utils_Array::first($form->_caseId);
     if (!$caseType && $caseId) {
         $caseType = CRM_Case_BAO_Case::getCaseType($caseId, 'title');
     }
     if (!$form->_currentlyViewedContactId || !$form->_currentUserId || !$caseId || !$caseType) {
         CRM_Core_Error::fatal('Required parameter missing for ChangeCaseType - end post processing');
     }
     $config = CRM_Core_Config::singleton();
     $params['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
     $activity->status_id = $params['status_id'];
     $params['priority_id'] = CRM_Core_OptionGroup::getValue('priority', 'Normal', 'name');
     $activity->priority_id = $params['priority_id'];
     // 1. save activity subject with new start date
     $currentStartDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseId, 'start_date'), $config->dateformatFull);
     $newStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Date::mysqlToIso($params['start_date']), $config->dateformatFull);
     $subject = 'Change Case Start Date from ' . $currentStartDate . ' to ' . $newStartDate;
     $activity->subject = $subject;
     $activity->save();
     // 2. initiate xml processor
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $xmlProcessorParams = array('clientID' => $form->_currentlyViewedContactId, 'creatorID' => $form->_currentUserId, 'standardTimeline' => 0, 'activity_date_time' => $params['start_date'], 'caseID' => $caseId, 'caseType' => $caseType, 'activityTypeName' => 'Change Case Start Date', 'activitySetName' => 'standard_timeline', 'resetTimeline' => 1);
     $xmlProcessor->run($caseType, $xmlProcessorParams);
     // 2.5 Update open case activity date
     // Multiple steps since revisioned
     if ($form->openCaseActivityId) {
         $abao = new CRM_Activity_BAO_Activity();
         $oldParams = array('id' => $form->openCaseActivityId);
         $oldActivityDefaults = array();
         $oldActivity = $abao->retrieve($oldParams, $oldActivityDefaults);
         // save the old values
         require_once 'api/v3/utils.php';
         $openCaseParams = array();
         //@todo calling api functions directly is not supported
         _civicrm_api3_object_to_array($oldActivity, $openCaseParams);
         // update existing revision
         $oldParams = array('id' => $form->openCaseActivityId, 'is_current_revision' => 0);
         $oldActivity = new CRM_Activity_DAO_Activity();
         $oldActivity->copyValues($oldParams);
         $oldActivity->save();
         // change some params for the new one
         unset($openCaseParams['id']);
         $openCaseParams['activity_date_time'] = $params['start_date'];
         $openCaseParams['target_contact_id'] = $oldActivityDefaults['target_contact'];
         $openCaseParams['assignee_contact_id'] = $oldActivityDefaults['assignee_contact'];
         $session = CRM_Core_Session::singleton();
         $openCaseParams['source_contact_id'] = $session->get('userID');
         // original_id always refers to the first activity, so only update if null (i.e. this is the second revision)
         $openCaseParams['original_id'] = $openCaseParams['original_id'] ? $openCaseParams['original_id'] : $form->openCaseActivityId;
         $newActivity = CRM_Activity_BAO_Activity::create($openCaseParams);
         if (is_a($newActivity, 'CRM_Core_Error')) {
             CRM_Core_Error::fatal('Unable to update Open Case activity');
         } else {
             // Create linkage to case
             $caseActivityParams = array('activity_id' => $newActivity->id, 'case_id' => $caseId);
             CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
             $caseActivityParams = array('activityID' => $form->openCaseActivityId, 'mainActivityId' => $newActivity->id);
             CRM_Activity_BAO_Activity::copyExtendedActivityData($caseActivityParams);
         }
     }
     // 3.status msg
     $params['statusMsg'] = ts('Case Start Date changed successfully.');
 }
Exemple #18
0
/**
 * Creates or updates an Activity.
 *
 * @param array $params
 *   Array per getfields documentation.
 *
 * @throws API_Exception
 * @return array
 *   API result array
 */
function civicrm_api3_activity_create($params)
{
    if (empty($params['id'])) {
        // an update does not require any mandatory parameters
        civicrm_api3_verify_one_mandatory($params, NULL, array('activity_name', 'activity_type_id', 'activity_label'));
    }
    // check for various error and required conditions
    // note that almost all the processing in there should be managed by the wrapper layer
    // & should be removed - needs testing
    $errors = _civicrm_api3_activity_check_params($params);
    // this should not be required as should throw exception rather than return errors -
    //needs testing
    if (!empty($errors)) {
        return $errors;
    }
    // processing for custom data
    $values = $activityArray = array();
    _civicrm_api3_custom_format_params($params, $values, 'Activity');
    if (!empty($values['custom'])) {
        $params['custom'] = $values['custom'];
    }
    // this should be set as a default rather than hard coded
    // needs testing
    $params['skipRecentView'] = TRUE;
    // If this is a case activity, see if there is an existing activity
    // and set it as an old revision. Also retrieve details we'll need.
    // this handling should all be moved to the BAO layer
    $case_id = '';
    $createRevision = FALSE;
    $oldActivityValues = array();
    // Lookup case id if not supplied
    if (!isset($params['case_id']) && !empty($params['id'])) {
        $params['case_id'] = CRM_Core_DAO::singleValueQuery("SELECT case_id FROM civicrm_case_activity WHERE activity_id = " . (int) $params['id']);
    }
    if (!empty($params['case_id'])) {
        $case_id = $params['case_id'];
        if (!empty($params['id'])) {
            $oldActivityParams = array('id' => $params['id']);
            if (!$oldActivityValues) {
                CRM_Activity_BAO_Activity::retrieve($oldActivityParams, $oldActivityValues);
            }
            if (empty($oldActivityValues)) {
                throw new API_Exception(ts("Unable to locate existing activity."));
            } else {
                $activityDAO = new CRM_Activity_DAO_Activity();
                $activityDAO->id = $params['id'];
                $activityDAO->is_current_revision = 0;
                if (!$activityDAO->save()) {
                    if (is_object($activityDAO)) {
                        $activityDAO->free();
                    }
                    throw new API_Exception(ts("Unable to revision existing case activity."));
                }
                $createRevision = TRUE;
            }
        }
    }
    $deleteActivityAssignment = FALSE;
    if (isset($params['assignee_contact_id'])) {
        $deleteActivityAssignment = TRUE;
    }
    $deleteActivityTarget = FALSE;
    if (isset($params['target_contact_id'])) {
        $deleteActivityTarget = TRUE;
    }
    // this should all be handled at the BAO layer
    $params['deleteActivityAssignment'] = CRM_Utils_Array::value('deleteActivityAssignment', $params, $deleteActivityAssignment);
    $params['deleteActivityTarget'] = CRM_Utils_Array::value('deleteActivityTarget', $params, $deleteActivityTarget);
    if ($case_id && $createRevision) {
        // This is very similar to the copy-to-case action.
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['target_contact'])) {
            $oldActivityValues['targetContactIds'] = implode(',', array_unique($oldActivityValues['target_contact']));
        }
        if (!CRM_Utils_Array::crmIsEmptyArray($oldActivityValues['assignee_contact'])) {
            $oldActivityValues['assigneeContactIds'] = implode(',', array_unique($oldActivityValues['assignee_contact']));
        }
        $oldActivityValues['mode'] = 'copy';
        $oldActivityValues['caseID'] = $case_id;
        $oldActivityValues['activityID'] = $oldActivityValues['id'];
        $oldActivityValues['contactID'] = $oldActivityValues['source_contact_id'];
        $copyToCase = CRM_Activity_Page_AJAX::_convertToCaseActivity($oldActivityValues);
        if (empty($copyToCase['error_msg'])) {
            // now fix some things that are different from copy-to-case
            // then fall through to the create below to update with the passed in params
            $params['id'] = $copyToCase['newId'];
            $params['is_auto'] = 0;
            $params['original_id'] = empty($oldActivityValues['original_id']) ? $oldActivityValues['id'] : $oldActivityValues['original_id'];
        } else {
            throw new API_Exception(ts("Unable to create new revision of case activity."));
        }
    }
    // create activity
    $activityBAO = CRM_Activity_BAO_Activity::create($params);
    if (isset($activityBAO->id)) {
        if ($case_id && !$createRevision) {
            // If this is a brand new case activity we need to add this
            $caseActivityParams = array('activity_id' => $activityBAO->id, 'case_id' => $case_id);
            CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
        }
        _civicrm_api3_object_to_array($activityBAO, $activityArray[$activityBAO->id]);
        return civicrm_api3_create_success($activityArray, $params, 'Activity', 'get', $activityBAO);
    }
}
 /**
  * Takes an associative array and creates a contribution object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  *
  * @return CRM_Contribute_BAO_Contribution
  */
 public static function create(&$params, $ids = array())
 {
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     //if contribution is created with cancelled or refunded status, add credit note id
     if (!empty($params['contribution_status_id'])) {
         $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         if ($params['contribution_status_id'] == array_search('Refunded', $contributionStatus) || $params['contribution_status_id'] == array_search('Cancelled', $contributionStatus)) {
             if (empty($params['creditnote_id']) || $params['creditnote_id'] == "null") {
                 $params['creditnote_id'] = self::createCreditNoteId();
             }
         }
     }
     $transaction = new CRM_Core_Transaction();
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
     }
     $session = CRM_Core_Session::singleton();
     if (!empty($params['note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams);
     }
     // make entry in batch entity batch table
     if (!empty($params['batch_id'])) {
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id');
         $retrieveRequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieveRequired = 1;
                 break;
             }
         }
         if ($retrieveRequired == 1) {
             $contribution->find(TRUE);
         }
     }
     CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
     $transaction->commit();
     // check if activity record exist for this contribution, if
     // not add activity
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find(TRUE)) {
         if (empty($contribution->contact_id)) {
             $contribution->find(TRUE);
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     } else {
         // CRM-13237 : if activity record found, update it with campaign id of contribution
         CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
     }
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id');
         $retrieveRequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieveRequired = 1;
                 break;
             }
         }
         if ($retrieveRequired == 1) {
             $contribution->find(TRUE);
         }
         $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, NULL, $recentOther);
     }
     return $contribution;
 }
 /**
  * Validate contact permission for
  * given operation on activity record.
  *
  * @param int     $activityId      activity record id.
  * @param string  $operation       user operation.
  * @param int     $actTypeId       activity type id.
  * @param int     $contactId       contact id/if not pass consider logged in
  * @param boolean $checkComponent  do we need to check component enabled.
  *
  * @return boolean $allow  true/false
  * @static
  */
 function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE)
 {
     $allow = FALSE;
     if (!$actTypeId && $activityId) {
         $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
     }
     if (!$activityId || !$operation || !$actTypeId) {
         return $allow;
     }
     //do check for civicase component enabled.
     if ($checkComponent) {
         static $componentEnabled;
         if (!isset($componentEnabled)) {
             $config = CRM_Core_Config::singleton();
             $componentEnabled = FALSE;
             if (in_array('CiviCase', $config->enableComponents)) {
                 $componentEnabled = TRUE;
             }
         }
         if (!$componentEnabled) {
             return $allow;
         }
     }
     //do check for cases.
     $caseActOperations = array('File On Case', 'Link Cases', 'Move To Case', 'Copy To Case');
     if (in_array($operation, $caseActOperations)) {
         static $unclosedCases;
         if (!is_array($unclosedCases)) {
             $unclosedCases = self::getUnclosedCases();
         }
         if ($operation == 'File On Case') {
             $allow = empty($unclosedCases) ? FALSE : TRUE;
         } else {
             $allow = count($unclosedCases) > 1 ? TRUE : FALSE;
         }
     }
     $actionOperations = array('view', 'edit', 'delete');
     if (in_array($operation, $actionOperations)) {
         //do cache when user has non/supper permission.
         static $allowOperations;
         if (!is_array($allowOperations) || !array_key_exists($operation, $allowOperations)) {
             if (!$contactId) {
                 $session = CRM_Core_Session::singleton();
                 $contactId = $session->get('userID');
             }
             //check for permissions.
             $permissions = array('view' => array('access my cases and activities', 'access all cases and activities'), 'edit' => array('access my cases and activities', 'access all cases and activities'), 'delete' => array('delete activities'));
             //check for core permission.
             $hasPermissions = array();
             $checkPermissions = CRM_Utils_Array::value($operation, $permissions);
             if (is_array($checkPermissions)) {
                 foreach ($checkPermissions as $per) {
                     if (CRM_Core_Permission::check($per)) {
                         $hasPermissions[$operation][] = $per;
                     }
                 }
             }
             //has permissions.
             if (!empty($hasPermissions)) {
                 //need to check activity object specific.
                 if (in_array($operation, array('view', 'edit'))) {
                     //do we have supper permission.
                     if (in_array('access all cases and activities', $hasPermissions[$operation])) {
                         $allowOperations[$operation] = $allow = TRUE;
                     } else {
                         //user has only access to my cases and activity.
                         //here object specific permmions come in picture.
                         //edit - contact must be source or assignee
                         //view - contact must be source/assignee/target
                         $isTarget = $isAssignee = $isSource = FALSE;
                         $target = new CRM_Activity_DAO_ActivityTarget();
                         $target->activity_id = $activityId;
                         $target->target_contact_id = $contactId;
                         if ($target->find(TRUE)) {
                             $isTarget = TRUE;
                         }
                         $assignee = new CRM_Activity_DAO_ActivityAssignment();
                         $assignee->activity_id = $activityId;
                         $assignee->assignee_contact_id = $contactId;
                         if ($assignee->find(TRUE)) {
                             $isAssignee = TRUE;
                         }
                         $activity = new CRM_Activity_DAO_Activity();
                         $activity->id = $activityId;
                         $activity->source_contact_id = $contactId;
                         if ($activity->find(TRUE)) {
                             $isSource = TRUE;
                         }
                         if ($operation == 'edit') {
                             if ($isAssignee || $isSource) {
                                 $allow = TRUE;
                             }
                         }
                         if ($operation == 'view') {
                             if ($isTarget || $isAssignee || $isSource) {
                                 $allow = TRUE;
                             }
                         }
                     }
                 } elseif (is_array($hasPermissions[$operation])) {
                     $allowOperations[$operation] = $allow = TRUE;
                 }
             } else {
                 //contact do not have permission.
                 $allowOperations[$operation] = FALSE;
             }
         } else {
             //use cache.
             //here contact might have supper/non permission.
             $allow = $allowOperations[$operation];
         }
     }
     //do further only when operation is granted.
     if ($allow) {
         $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name');
         //get the activity type name.
         $actTypeName = CRM_Utils_Array::value($actTypeId, $activityTypes);
         //do not allow multiple copy / edit action.
         $singletonNames = array('Open Case', 'Reassigned Case', 'Merge Case', 'Link Cases', 'Assign Case Role', 'Email', 'Inbound Email');
         //do not allow to delete these activities, CRM-4543
         $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
         //allow edit operation.
         $allowEditNames = array('Open Case');
         // do not allow File on Case
         $doNotFileNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date', 'Reassigned Case', 'Merge Case', 'Link Cases', 'Assign Case Role');
         if (in_array($actTypeName, $singletonNames)) {
             $allow = FALSE;
             if ($operation == 'File On Case') {
                 $allow = in_array($actTypeName, $doNotFileNames) ? FALSE : TRUE;
             }
             if (in_array($operation, $actionOperations)) {
                 $allow = TRUE;
                 if ($operation == 'edit') {
                     $allow = in_array($actTypeName, $allowEditNames) ? TRUE : FALSE;
                 } elseif ($operation == 'delete') {
                     $allow = in_array($actTypeName, $doNotDeleteNames) ? FALSE : TRUE;
                 }
             }
         }
         if ($allow && $operation == 'delete' && in_array($actTypeName, $doNotDeleteNames)) {
             $allow = FALSE;
         }
         if ($allow && $operation == 'File On Case' && in_array($actTypeName, $doNotFileNames)) {
             $allow = FALSE;
         }
         //check settings file for masking actions
         //on the basis the activity types
         //hide Edit link if activity type is NOT editable
         //(special case activities).CRM-5871
         if ($allow && in_array($operation, $actionOperations)) {
             static $actionFilter = array();
             if (!array_key_exists($operation, $actionFilter)) {
                 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
                 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
             }
             if (array_key_exists($operation, $actionFilter[$operation]) && in_array($actTypeId, $actionFilter[$operation][$operation])) {
                 $allow = FALSE;
             }
         }
     }
     return $allow;
 }
 /**
  * Get a list of Assignments matching the params, where each param key is:
  *  1. the key of a field in civicrm_activity
  *     except for activity_type_id and activity_duration
  *  2. the key of a custom field on the activity
  *     (volunteer_need_id, time_scheduled, time_completed)
  *  3. the key of a field in civicrm_contact
  *  4. project_id
  *
  * @param array $params
  * @return array of CRM_Volunteer_BAO_Project objects
  */
 static function retrieve(array $params)
 {
     $activity_fields = CRM_Activity_DAO_Activity::fields();
     $contact_fields = CRM_Contact_DAO_Contact::fields();
     $custom_fields = self::getCustomFields();
     $foreign_fields = array('project_id', 'target_contact_id');
     // This is the "real" id
     $activity_fields['id'] = $activity_fields['activity_id'];
     unset($activity_fields['activity_id']);
     // enforce restrictions on parameters
     $allowed_params = array_flip(array_merge(array_keys($activity_fields), array_keys($contact_fields), array_keys($custom_fields), $foreign_fields));
     unset($allowed_params['activity_type_id']);
     unset($allowed_params['activity_duration']);
     $filtered_params = array_intersect_key($params, $allowed_params);
     $custom_group = self::getCustomGroup();
     $customTableName = $custom_group['table_name'];
     foreach ($custom_fields as $name => $field) {
         $selectClause[] = "{$customTableName}.{$field['column_name']} AS {$name}";
     }
     $customSelect = implode(', ', $selectClause);
     $activityContactTypes = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContactTypes);
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContactTypes);
     $volunteerStatus = CRM_Activity_BAO_Activity::buildOptions('status_id', 'validate');
     $available = CRM_Utils_Array::key('Available', $volunteerStatus);
     $scheduled = CRM_Utils_Array::key('Scheduled', $volunteerStatus);
     $placeholders = array(1 => array($assigneeID, 'Integer'), 2 => array(self::volunteerActivityTypeId(), 'Integer'), 3 => array($scheduled, 'Integer'), 4 => array($available, 'Integer'), 5 => array($targetID, 'Integer'));
     $i = count($placeholders) + 1;
     $where = array();
     $whereClause = NULL;
     foreach ($filtered_params as $key => $value) {
         if (CRM_Utils_Array::value($key, $activity_fields)) {
             $dataType = CRM_Utils_Type::typeToString($activity_fields[$key]['type']);
             $fieldName = $activity_fields[$key]['name'];
             $tableName = CRM_Activity_DAO_Activity::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $contact_fields)) {
             $dataType = CRM_Utils_Type::typeToString($contact_fields[$key]['type']);
             $fieldName = $contact_fields[$key]['name'];
             $tableName = CRM_Contact_DAO_Contact::$_tableName;
         } elseif (CRM_Utils_Array::value($key, $custom_fields)) {
             $dataType = $custom_fields[$key]['data_type'];
             $fieldName = $custom_fields[$key]['column_name'];
             $tableName = $customTableName;
         } elseif ($key == 'project_id') {
             $dataType = 'Int';
             $fieldName = 'id';
             $tableName = CRM_Volunteer_DAO_Project::$_tableName;
         } elseif ($key == 'target_contact_id') {
             $dataType = 'Int';
             $fieldName = 'contact_id';
             $tableName = 'tgt';
             // this is an alias for civicrm_activity_contact
         }
         $where[] = "{$tableName}.{$fieldName} = %{$i}";
         $placeholders[$i] = array($value, $dataType);
         $i++;
     }
     if (count($where)) {
         $whereClause = 'AND ' . implode("\nAND ", $where);
     }
     $query = "\n      SELECT\n        civicrm_activity.*,\n        assignee.contact_id AS assignee_contact_id,\n        {$customSelect},\n        civicrm_volunteer_need.start_time,\n        civicrm_volunteer_need.is_flexible,\n        civicrm_volunteer_need.role_id,\n        assignee_contact.sort_name AS assignee_sort_name,\n        assignee_contact.display_name AS assignee_display_name,\n        assignee_phone.phone AS assignee_phone,\n        assignee_phone.phone_ext AS assignee_phone_ext,\n        assignee_email.email AS assignee_email,\n        -- begin target contact fields\n        tgt.contact_id AS target_contact_id,\n        tgt_contact.sort_name AS target_sort_name,\n        tgt_contact.display_name AS target_display_name,\n        tgt_phone.phone AS target_phone,\n        tgt_phone.phone_ext AS target_phone_ext,\n        tgt_email.email AS target_email\n        -- end target contact fields\n      FROM civicrm_activity\n      INNER JOIN civicrm_activity_contact assignee\n        ON (\n          assignee.activity_id = civicrm_activity.id\n          AND assignee.record_type_id = %1\n        )\n      INNER JOIN civicrm_contact assignee_contact\n        ON assignee.contact_id = assignee_contact.id\n      LEFT JOIN civicrm_email assignee_email\n        ON assignee_email.contact_id = assignee_contact.id AND assignee_email.is_primary = 1\n      LEFT JOIN civicrm_phone assignee_phone\n        ON assignee_phone.contact_id = assignee_contact.id AND assignee_phone.is_primary = 1\n      -- begin target contact joins\n      LEFT JOIN civicrm_activity_contact tgt\n        ON (\n          tgt.activity_id = civicrm_activity.id\n          AND tgt.record_type_id = %5\n        )\n      LEFT JOIN civicrm_contact tgt_contact\n        ON tgt.contact_id = tgt_contact.id\n      LEFT JOIN civicrm_email tgt_email\n        ON tgt_email.contact_id = tgt_contact.id AND tgt_email.is_primary = 1\n      LEFT JOIN civicrm_phone tgt_phone\n        ON tgt_phone.contact_id = tgt_contact.id AND tgt_phone.is_primary = 1\n      -- end target contact joins\n      INNER JOIN {$customTableName}\n        ON ({$customTableName}.entity_id = civicrm_activity.id)\n      INNER JOIN civicrm_volunteer_need\n        ON (civicrm_volunteer_need.id = {$customTableName}.{$custom_fields['volunteer_need_id']['column_name']})\n      INNER JOIN civicrm_volunteer_project\n        ON (civicrm_volunteer_project.id = civicrm_volunteer_need.project_id)\n      WHERE civicrm_activity.activity_type_id = %2\n      AND civicrm_activity.status_id IN (%3, %4 )\n      {$whereClause}\n    ";
     $dao = CRM_Core_DAO::executeQuery($query, $placeholders);
     $rows = array();
     while ($dao->fetch()) {
         $rows[$dao->id] = $dao->toArray();
     }
     /*
      * For clarity we want the fields associated with each contact prefixed with
      * the contact type (e.g., target_phone). For backwards compatibility,
      * however, we want the fields associated with each assignee contact to be
      * accessible sans prefix. Eventually we should deprecate the non-prefixed
      * field names.
      */
     foreach ($rows as $id => $fields) {
         foreach ($fields as $key => $value) {
             if (substr($key, 0, 9) == 'assignee_') {
                 $rows[$id][substr($key, 9)] = $value;
             }
         }
     }
     return $rows;
 }
 function callback()
 {
     $apiMsgID = $this->retrieve('apiMsgId', 'String');
     $activity = new CRM_Activity_DAO_Activity();
     $activity->result = $apiMsgID;
     if ($activity->find(TRUE)) {
         $actStatusIDs = array_flip(CRM_Core_OptionGroup::values('activity_status'));
         $status = $this->retrieve('status', 'String');
         switch ($status) {
             case "001":
                 $statusID = $actStatusIDs['Cancelled'];
                 $clickStat = $this->_messageStatus[$status] . " - Message Unknown";
                 break;
             case "002":
                 $statusID = $actStatusIDs['Scheduled'];
                 $clickStat = $this->_messageStatus[$status] . " - Message Queued";
                 break;
             case "003":
                 $statusID = $actStatusIDs['Completed'];
                 $clickStat = $this->_messageStatus[$status] . " - Delivered to Gateway";
                 break;
             case "004":
                 $statusID = $actStatusIDs['Completed'];
                 $clickStat = $this->_messageStatus[$status] . " - Received by Recipient";
                 break;
             case "005":
                 $statusID = $actStatusIDs['Cancelled'];
                 $clickStat = $this->_messageStatus[$status] . " - Error with Message";
                 break;
             case "006":
                 $statusID = $actStatusIDs['Cancelled'];
                 $clickStat = $this->_messageStatus[$status] . " - User cancelled message";
                 break;
             case "007":
                 $statusID = $actStatusIDs['Cancelled'];
                 $clickStat = $this->_messageStatus[$status] . " - Error delivering message";
                 break;
             case "008":
                 $statusID = $actStatusIDs['Completed'];
                 $clickStat = $this->_messageStatus[$status] . " - Ok, Message Received by Gateway";
                 break;
             case "009":
                 $statusID = $actStatusIDs['Cancelled'];
                 $clickStat = $this->_messageStatus[$status] . " - Routing Error";
                 break;
             case "010":
                 $statusID = $actStatusIDs['Cancelled'];
                 $clickStat = $this->_messageStatus[$status] . " - Message Expired";
                 break;
             case "011":
                 $statusID = $actStatusIDs['Scheduled'];
                 $clickStat = $this->_messageStatus[$status] . " - Message Queued for Later";
                 break;
             case "012":
                 $statusID = $actStatusIDs['Cancelled'];
                 $clickStat = $this->_messageStatus[$status] . " - Out of Credit";
                 break;
         }
         if ($statusID) {
             // update activity with status + msg in location
             $activity->status_id = $statusID;
             $activity->location = $clickStat;
             $activity->activity_date_time = CRM_Utils_Date::isoToMysql($activity->activity_date_time);
             $activity->save();
             CRM_Core_Error::debug_log_message("SMS Response updated for apiMsgId={$apiMsgID}.");
             return TRUE;
         }
     }
     // if no update is done
     CRM_Core_Error::debug_log_message("Could not update SMS Response for apiMsgId={$apiMsgID}.");
     return FALSE;
 }
Exemple #23
0
 /**
  * @param array $params
  *
  * @return array
  */
 public static function _convertToCaseActivity($params)
 {
     if (!$params['activityID'] || !$params['caseID']) {
         return array('error_msg' => 'required params missing.');
     }
     $otherActivity = new CRM_Activity_DAO_Activity();
     $otherActivity->id = $params['activityID'];
     if (!$otherActivity->find(TRUE)) {
         return array('error_msg' => 'activity record is missing.');
     }
     $actDateTime = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
     // Create new activity record.
     $mainActivity = new CRM_Activity_DAO_Activity();
     $mainActVals = array();
     CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
     // Get new activity subject.
     if (!empty($params['newSubject'])) {
         $mainActVals['subject'] = $params['newSubject'];
     }
     $mainActivity->copyValues($mainActVals);
     $mainActivity->id = NULL;
     $mainActivity->activity_date_time = $actDateTime;
     // Make sure this is current revision.
     $mainActivity->is_current_revision = TRUE;
     // Drop all relations.
     $mainActivity->parent_id = $mainActivity->original_id = NULL;
     $mainActivity->save();
     $mainActivityId = $mainActivity->id;
     CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
     $mainActivity->free();
     // Mark previous activity as deleted. If it was a non-case activity
     // then just change the subject.
     if (in_array($params['mode'], array('move', 'file'))) {
         $caseActivity = new CRM_Case_DAO_CaseActivity();
         $caseActivity->case_id = $params['caseID'];
         $caseActivity->activity_id = $otherActivity->id;
         if ($params['mode'] == 'move' || $caseActivity->find(TRUE)) {
             $otherActivity->is_deleted = 1;
         } else {
             $otherActivity->subject = ts('(Filed on case %1)', array(1 => $params['caseID'])) . ' ' . $otherActivity->subject;
         }
         $otherActivity->activity_date_time = $actDateTime;
         $otherActivity->save();
         $caseActivity->free();
     }
     $otherActivity->free();
     $targetContacts = array();
     if (!empty($params['targetContactIds'])) {
         $targetContacts = array_unique(explode(',', $params['targetContactIds']));
     }
     $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);
     $sourceContactID = CRM_Activity_BAO_Activity::getSourceContactID($params['activityID']);
     $src_params = array('activity_id' => $mainActivityId, 'contact_id' => $sourceContactID, 'record_type_id' => $sourceID);
     CRM_Activity_BAO_ActivityContact::create($src_params);
     foreach ($targetContacts as $key => $value) {
         $targ_params = array('activity_id' => $mainActivityId, 'contact_id' => $value, 'record_type_id' => $targetID);
         CRM_Activity_BAO_ActivityContact::create($targ_params);
     }
     // typically this will be empty, since assignees on another case may be completely different
     $assigneeContacts = array();
     if (!empty($params['assigneeContactIds'])) {
         $assigneeContacts = array_unique(explode(',', $params['assigneeContactIds']));
     }
     foreach ($assigneeContacts as $key => $value) {
         $assigneeParams = array('activity_id' => $mainActivityId, 'contact_id' => $value, 'record_type_id' => $assigneeID);
         CRM_Activity_BAO_ActivityContact::create($assigneeParams);
     }
     // Attach newly created activity to case.
     $caseActivity = new CRM_Case_DAO_CaseActivity();
     $caseActivity->case_id = $params['caseID'];
     $caseActivity->activity_id = $mainActivityId;
     $caseActivity->save();
     $error_msg = $caseActivity->_lastError;
     $caseActivity->free();
     $params['mainActivityId'] = $mainActivityId;
     CRM_Activity_BAO_Activity::copyExtendedActivityData($params);
     return array('error_msg' => $error_msg, 'newId' => $mainActivity->id);
 }
 /**
  * takes an associative array and creates a contribution object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Contribute_BAO_Contribution object 
  * @access public
  * @static
  */
 static function &create(&$params, &$ids)
 {
     require_once 'CRM/Utils/Money.php';
     require_once 'CRM/Utils/Date.php';
     require_once 'CRM/Contribute/PseudoConstant.php';
     // FIXME: a cludgy hack to fix the dates to MySQL format
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     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_contribution', $contribution->id);
     }
     $session =& CRM_Core_Session::singleton();
     if (CRM_Utils_Array::value('note', $params)) {
         require_once 'CRM/Core/BAO/Note.php';
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams, CRM_Utils_Array::value('note', $ids));
     }
     // check if activity record exist for this contribution, if
     // not add activity
     require_once "CRM/Activity/DAO/Activity.php";
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find()) {
         require_once "CRM/Activity/BAO/Activity.php";
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     }
     if (CRM_Utils_Array::value('soft_credit_to', $params)) {
         $csParams = array();
         if ($id = CRM_Utils_Array::value('softID', $params)) {
             $csParams['id'] = $params['softID'];
         }
         $csParams['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ? 1 : 0;
         foreach (array('pcp_roll_nickname', 'pcp_personal_note') as $val) {
             if (CRM_Utils_Array::value($val, $params)) {
                 $csParams[$val] = $params[$val];
             }
         }
         $csParams['contribution_id'] = $contribution->id;
         $csParams['contact_id'] = $params['soft_credit_to'];
         // first stage: we register whole amount as credited to given person
         $csParams['amount'] = $contribution->total_amount;
         self::addSoftContribution($csParams);
     }
     $transaction->commit();
     // 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/Contribute/PseudoConstant.php';
         require_once 'CRM/Contact/BAO/Contact.php';
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         $contributionTypes = CRM_Contribute_PseudoConstant::contributionType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->contribution_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, null, $recentOther);
     }
     return $contribution;
 }
Exemple #25
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");
         }
     }
 }
Exemple #26
0
 static function createConference($adminID, $teacherID, $activityTypeID, $activityDateTime, $subject, $location, $statusID, $duration = 30)
 {
     require_once 'CRM/Activity/DAO/Activity.php';
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_contact_id = $adminID;
     $activity->activity_type_id = $activityTypeID;
     $activity->activity_date_time = $activityDateTime;
     $activity->status_id = $statusID;
     $activity->subject = $subject;
     $activity->duration = $duration;
     $activity->location = $location;
     $activity->save();
     require_once 'CRM/Activity/DAO/ActivityAssignment.php';
     $assignment = new CRM_Activity_DAO_ActivityAssignment();
     $assignment->activity_id = $activity->id;
     $assignment->assignee_contact_id = $teacherID;
     $assignment->save();
     return $activity->id;
 }
Exemple #27
0
 /**
  * Updates contacts affected by the option value passed.
  *
  * @param int $optionValueId
  *   The option value id.
  * @param int $action
  *   The action describing whether prefix/suffix was UPDATED or DELETED.
  *
  * @return bool
  */
 public static function updateRecords(&$optionValueId, $action)
 {
     //finding group name
     $optionValue = new CRM_Core_DAO_OptionValue();
     $optionValue->id = $optionValueId;
     $optionValue->find(TRUE);
     $optionGroup = new CRM_Core_DAO_OptionGroup();
     $optionGroup->id = $optionValue->option_group_id;
     $optionGroup->find(TRUE);
     // group name
     $gName = $optionGroup->name;
     // value
     $value = $optionValue->value;
     // get the proper group name & affected field name
     // todo: this may no longer be needed for individuals - check inputs
     $individuals = array('gender' => 'gender_id', 'individual_prefix' => 'prefix_id', 'individual_suffix' => 'suffix_id', 'communication_style' => 'communication_style_id');
     $contributions = array('payment_instrument' => 'payment_instrument_id');
     $activities = array('activity_type' => 'activity_type_id');
     $participant = array('participant_role' => 'role_id');
     $eventType = array('event_type' => 'event_type_id');
     $aclRole = array('acl_role' => 'acl_role_id');
     $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
     $fieldName = '';
     foreach ($all as $name => $id) {
         if ($gName == $name) {
             $fieldName = $id;
         }
     }
     if ($fieldName == '') {
         return TRUE;
     }
     if (array_key_exists($gName, $individuals)) {
         $contactDAO = new CRM_Contact_DAO_Contact();
         $contactDAO->{$fieldName} = $value;
         $contactDAO->find();
         while ($contactDAO->fetch()) {
             if ($action == CRM_Core_Action::DELETE) {
                 $contact = new CRM_Contact_DAO_Contact();
                 $contact->id = $contactDAO->id;
                 $contact->find(TRUE);
                 // make sure dates doesn't get reset
                 $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date);
                 $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date);
                 $contact->{$fieldName} = 'NULL';
                 $contact->save();
             }
         }
         return TRUE;
     }
     if (array_key_exists($gName, $contributions)) {
         $contribution = new CRM_Contribute_DAO_Contribution();
         $contribution->{$fieldName} = $value;
         $contribution->find();
         while ($contribution->fetch()) {
             if ($action == CRM_Core_Action::DELETE) {
                 $contribution->{$fieldName} = 'NULL';
                 $contribution->save();
             }
         }
         return TRUE;
     }
     if (array_key_exists($gName, $activities)) {
         $activity = new CRM_Activity_DAO_Activity();
         $activity->{$fieldName} = $value;
         $activity->find();
         while ($activity->fetch()) {
             $activity->delete();
         }
         return TRUE;
     }
     //delete participant role, type and event type option value
     if (array_key_exists($gName, $participant)) {
         $participantValue = new CRM_Event_DAO_Participant();
         $participantValue->{$fieldName} = $value;
         if ($participantValue->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
     //delete event type option value
     if (array_key_exists($gName, $eventType)) {
         $event = new CRM_Event_DAO_Event();
         $event->{$fieldName} = $value;
         if ($event->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
     //delete acl_role option value
     if (array_key_exists($gName, $aclRole)) {
         $entityRole = new CRM_ACL_DAO_EntityRole();
         $entityRole->{$fieldName} = $value;
         $aclDAO = new CRM_ACL_DAO_ACL();
         $aclDAO->entity_id = $value;
         if ($entityRole->find(TRUE) || $aclDAO->find(TRUE)) {
             return FALSE;
         }
         return TRUE;
     }
 }
 /**
  * takes an associative array and creates a contribution object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Contribute_BAO_Contribution object
  * @access public
  * @static
  */
 static function &create(&$params, &$ids)
 {
     // FIXME: a cludgy hack to fix the dates to MySQL format
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     if (CRM_Utils_Array::value('contribution', $ids) && !CRM_Utils_Array::value('softID', $params)) {
         if ($softID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionSoft', $ids['contribution'], 'id', 'contribution_id')) {
             $params['softID'] = $softID;
         }
     }
     $transaction = new CRM_Core_Transaction();
     // delete the soft credit record if no soft credit contact ID AND no PCP is set in the form
     if (CRM_Utils_Array::value('contribution', $ids) && (!CRM_Utils_Array::value('soft_credit_to', $params) && !CRM_Utils_Array::value('pcp_made_through_id', $params)) && CRM_Utils_Array::value('softID', $params)) {
         $softCredit = new CRM_Contribute_DAO_ContributionSoft();
         $softCredit->id = $params['softID'];
         $softCredit->delete();
     }
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
     }
     $session = CRM_Core_Session::singleton();
     if (CRM_Utils_Array::value('note', $params)) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams, CRM_Utils_Array::value('note', $ids));
     }
     // make entry in batch entity batch table
     if (CRM_Utils_Array::value('batch_id', $params)) {
         $entityParams = array('batch_id' => $params['batch_id'], 'entity_table' => 'civicrm_contribution', 'entity_id' => $contribution->id);
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'contribution_type_id');
         $retrieverequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieverequired = 1;
                 break;
             }
         }
         if ($retrieverequired == 1) {
             $contribution->find(true);
         }
         CRM_Core_BAO_Batch::addBatchEntity($entityParams);
     }
     // check if activity record exist for this contribution, if
     // not add activity
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find()) {
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     }
     // Handle soft credit and / or link to personal campaign page
     if (CRM_Utils_Array::value('soft_credit_to', $params) || CRM_Utils_Array::value('pcp_made_through_id', $params)) {
         $csParams = array();
         if ($id = CRM_Utils_Array::value('softID', $params)) {
             $csParams['id'] = $params['softID'];
         }
         $csParams['contribution_id'] = $contribution->id;
         // If pcp_made_through_id set, we define soft_credit_to contact based on selected PCP,
         // else use passed soft_credit_to
         if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
             $csParams['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ? 1 : 0;
             foreach (array('pcp_roll_nickname', 'pcp_personal_note') as $val) {
                 $csParams[$val] = $params[$val];
             }
             $csParams['pcp_id'] = CRM_Utils_Array::value('pcp_made_through_id', $params);
             $csParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $csParams['pcp_id'], 'contact_id');
         } else {
             $csParams['contact_id'] = $params['soft_credit_to'];
             $csParams['pcp_id'] = '';
         }
         // first stage: we register whole amount as credited to given person
         $csParams['amount'] = $contribution->total_amount;
         self::addSoftContribution($csParams);
     }
     $transaction->commit();
     // do not add to recent items for import, CRM-4399
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'contribution_type_id');
         $retrieverequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieverequired = 1;
                 break;
             }
         }
         if ($retrieverequired == 1) {
             $contribution->find(true);
         }
         $contributionTypes = CRM_Contribute_PseudoConstant::contributionType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->contribution_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, NULL, $recentOther);
     }
     return $contribution;
 }
Exemple #29
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;
    }
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $statusMsg = null;
         //block deleting activities which affects
         //case attributes.CRM-4543
         $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
         $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', false, false, false, $activityCondition);
         if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
             $params = array('id' => $this->_activityId);
             $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, true);
             if ($activityDelete) {
                 $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />');
             }
         } else {
             $statusMsg = ts("Selected Activity cannot be deleted.");
         }
         require_once 'CRM/Core/BAO/EntityTag.php';
         $tagParams = array('entity_table' => 'civicrm_activity', 'entity_id' => $this->_activityId);
         CRM_Core_BAO_EntityTag::del($tagParams);
         CRM_Core_Session::setStatus($statusMsg);
         return;
     }
     if ($this->_action & CRM_Core_Action::RENEW) {
         $statusMsg = null;
         $params = array('id' => $this->_activityId);
         $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
         if ($activityRestore) {
             $statusMsg = ts('The selected activity has been restored.<br />');
         }
         CRM_Core_Session::setStatus($statusMsg);
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     if ($params['source_contact_id']) {
         $params['source_contact_id'] = $params['source_contact_qid'];
     }
     //set parent id if its edit mode
     if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
         $params['parent_id'] = $parentId;
     }
     // required for status msg
     $recordStatus = 'created';
     // store the dates with proper format
     $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
     $params['activity_type_id'] = $this->_activityTypeId;
     require_once 'CRM/Case/XMLProcessor/Process.php';
     $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
     $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
     $this->assign('multiClient', $isMultiClient);
     $targetContacts = array($this->_currentlyViewedContactId);
     if (CRM_Utils_Array::value('hidden_target_contact', $params) && CRM_Utils_Array::value('target_contact_id', $params)) {
         $targetContacts = array_unique(explode(',', $params['target_contact_id']));
     }
     $params['target_contact_id'] = $targetContacts;
     // format activity custom data
     if (CRM_Utils_Array::value('hidden_custom', $params)) {
         if ($this->_activityId) {
             // unset custom fields-id from params since we want custom
             // fields to be saved for new activity.
             foreach ($params as $key => $value) {
                 $match = array();
                 if (preg_match('/^(custom_\\d+_)(\\d+)$/', $key, $match)) {
                     $params[$match[1] . '-1'] = $params[$key];
                     // for autocomplete transfer hidden value instead of label
                     if ($params[$key] && isset($params[$key . '_id'])) {
                         $params[$match[1] . '-1_id'] = $params[$key . '_id'];
                         unset($params[$key . '_id']);
                     }
                     unset($params[$key]);
                 }
             }
         }
         // build custom data getFields array
         $customFields = CRM_Core_BAO_CustomField::getFields('Activity', false, false, $this->_activityTypeId);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Activity', false, false, null, null, true));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_activityId, 'Activity');
     }
     if (CRM_Utils_Array::value('assignee_contact_id', $params)) {
         $assineeContacts = explode(',', $params['assignee_contact_id']);
         $assineeContacts = array_unique($assineeContacts);
         unset($params['assignee_contact_id']);
     } else {
         $params['assignee_contact_id'] = $assineeContacts = array();
     }
     if (isset($this->_activityId)) {
         // activity which hasn't been modified by a user yet
         if ($this->_defaults['is_auto'] == 1) {
             $params['is_auto'] = 0;
         }
         // always create a revision of an case activity. CRM-4533
         $newActParams = $params;
         // add target contact values in update mode
         if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
             $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
         }
         // record status for status msg
         $recordStatus = 'updated';
     }
     if (!isset($newActParams)) {
         // add more attachments if needed for old activity
         CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($params);
         $params['case_id'] = $this->_caseId;
         // activity create/update
         $activity = CRM_Activity_BAO_Activity::create($params);
         // call end post process, after the activity has been created/updated.
         $this->endPostProcess($params, $activity);
     } else {
         // since the params we need to set are very few, and we don't want rest of the
         // work done by bao create method , lets use dao object to make the changes
         $params = array('id' => $this->_activityId);
         $params['is_current_revision'] = 0;
         $activity = new CRM_Activity_DAO_Activity();
         $activity->copyValues($params);
         $activity->save();
     }
     // create a new version of activity if activity was found to
     // have been modified/created by user
     if (isset($newActParams)) {
         // set proper original_id
         if (CRM_Utils_Array::value('original_id', $this->_defaults)) {
             $newActParams['original_id'] = $this->_defaults['original_id'];
         } else {
             $newActParams['original_id'] = $activity->id;
         }
         //is_current_revision will be set to 1 by default.
         // add attachments if any
         CRM_Core_BAO_File::formatAttachment($newActParams, $newActParams, 'civicrm_activity');
         // call begin post process, before the activity is created/updated.
         $this->beginPostProcess($newActParams);
         $newActParams['case_id'] = $this->_caseId;
         $activity = CRM_Activity_BAO_Activity::create($newActParams);
         // call end post process, after the activity has been created/updated.
         $this->endPostProcess($newActParams, $activity);
         // copy files attached to old activity if any, to new one,
         // as long as users have not selected the 'delete attachment' option.
         if (!CRM_Utils_Array::value('is_delete_attachment', $newActParams)) {
             CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId, 'civicrm_activity', $activity->id);
         }
         // copy back params to original var
         $params = $newActParams;
     }
     if ($activity->id) {
         // add tags if exists
         $tagParams = array();
         if (!empty($params['tag'])) {
             foreach ($params['tag'] as $tag) {
                 $tagParams[$tag] = 1;
             }
         }
         //save static tags
         require_once 'CRM/Core/BAO/EntityTag.php';
         CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $activity->id);
         //save free tags
         if (isset($params['taglist']) && !empty($params['taglist'])) {
             require_once 'CRM/Core/Form/Tag.php';
             CRM_Core_Form_Tag::postProcess($params['taglist'], $activity->id, 'civicrm_activity', $this);
         }
     }
     $params['assignee_contact_id'] = $assineeContacts;
     // update existing case record if needed
     $caseParams = $params;
     $caseParams['id'] = $this->_caseId;
     if (CRM_Utils_Array::value('case_type_id', $caseParams)) {
         $caseParams['case_type_id'] = CRM_Case_BAO_Case::VALUE_SEPERATOR . $caseParams['case_type_id'] . CRM_Case_BAO_Case::VALUE_SEPERATOR;
     }
     if (CRM_Utils_Array::value('case_status_id', $caseParams)) {
         $caseParams['status_id'] = $caseParams['case_status_id'];
     }
     // unset params intended for activities only
     unset($caseParams['subject'], $caseParams['details'], $caseParams['status_id'], $caseParams['custom']);
     $case = CRM_Case_BAO_Case::create($caseParams);
     // create case activity record
     $caseParams = array('activity_id' => $activity->id, 'case_id' => $this->_caseId);
     CRM_Case_BAO_Case::processCaseActivity($caseParams);
     // create activity assignee records
     $assigneeParams = array('activity_id' => $activity->id);
     if (!CRM_Utils_Array::crmIsEmptyArray($params['assignee_contact_id'])) {
         //skip those assignee contacts which are already assigned
         //while sending a copy.CRM-4509.
         $activityAssigned = array_flip($params['assignee_contact_id']);
         $activityId = isset($this->_activityId) ? $this->_activityId : $activity->id;
         $assigneeContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activityId);
         $activityAssigned = array_diff_key($activityAssigned, $assigneeContacts);
         foreach ($params['assignee_contact_id'] as $key => $id) {
             $assigneeParams['assignee_contact_id'] = $id;
             CRM_Activity_BAO_Activity::createActivityAssignment($assigneeParams);
         }
         //modify assigne_contact as per newly assigned contact before sending copy. CRM-4509.
         $params['assignee_contact_id'] = $activityAssigned;
     }
     // Insert civicrm_log record for the activity (e.g. store the
     // created / edited by contact id and date for the activity)
     // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
     // send copy to selected contacts.
     $mailStatus = '';
     $mailToContacts = array();
     //CRM-5695
     //check for notification settings for assignee contacts
     $selectedContacts = array('contact_check');
     $config =& CRM_Core_Config::singleton();
     if ($config->activityAssigneeNotification) {
         $selectedContacts[] = 'assignee_contact_id';
     }
     foreach ($selectedContacts as $dnt => $val) {
         if (array_key_exists($val, $params) && !CRM_Utils_array::crmIsEmptyArray($params[$val])) {
             if ($val == 'contact_check') {
                 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
             } else {
                 $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames($activity->id, true, false);
                 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
             }
             //build an associative array with unique email addresses.
             foreach ($params[$val] as $id => $dnc) {
                 if (isset($id) && array_key_exists($id, $this->_relatedContacts)) {
                     //if email already exists in array then append with ', ' another role only otherwise add it to array.
                     if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
                         $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
                         $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
                     } else {
                         $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
                     }
                 }
             }
         }
     }
     if (!CRM_Utils_array::crmIsEmptyArray($mailToContacts)) {
         //include attachments while sendig a copy of activity.
         $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
         $result = CRM_Case_BAO_Case::sendActivityCopy($this->_currentlyViewedContactId, $activity->id, $mailToContacts, $attachments, $this->_caseId);
         if (empty($result)) {
             $mailStatus = '';
         }
     } else {
         $mailStatus = '';
     }
     // create follow up activity if needed
     $followupStatus = '';
     if (CRM_Utils_Array::value('followup_activity_type_id', $params)) {
         $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($activity->id, $params);
         if ($followupActivity) {
             $caseParams = array('activity_id' => $followupActivity->id, 'case_id' => $this->_caseId);
             CRM_Case_BAO_Case::processCaseActivity($caseParams);
             $followupStatus = ts("A followup activity has been scheduled.");
         }
     }
     CRM_Core_Session::setStatus(ts("'%1' activity has been %2. %3 %4", array(1 => $this->_activityTypeName, 2 => $recordStatus, 3 => $followupStatus, 4 => $mailStatus)));
 }