Ejemplo n.º 1
0
 /**
  * This function is to make a copy of a Event, including
  * all the fields in the event Wizard
  *
  * @param int $id the event id to copy
  *        obj     $newEvent    object of CRM_Event_DAO_Event
  *        boolean $afterCreate call to copy after the create function
  * @param null $newEvent
  * @param bool $afterCreate
  *
  * @return void
  * @access public
  */
 static function copy($id, $newEvent = NULL, $afterCreate = FALSE)
 {
     $defaults = $eventValues = array();
     //get the require event values.
     $eventParams = array('id' => $id);
     $returnProperties = array('loc_block_id', 'is_show_location', 'default_fee_id', 'default_discount_fee_id', 'is_template');
     CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
     // since the location is sharable, lets use the same loc_block_id.
     $locBlockId = CRM_Utils_Array::value('loc_block_id', $eventValues);
     $fieldsFix = $afterCreate ? array() : array('prefix' => array('title' => ts('Copy of') . ' '));
     if (empty($eventValues['is_show_location'])) {
         $fieldsFix['prefix']['is_show_location'] = 0;
     }
     if ($newEvent && is_a($newEvent, 'CRM_Event_DAO_Event')) {
         $copyEvent = $newEvent;
     }
     if (!isset($copyEvent)) {
         $copyEvent =& CRM_Core_DAO::copyGeneric('CRM_Event_DAO_Event', array('id' => $id), array('loc_block_id' => $locBlockId ? $locBlockId : NULL), $fieldsFix);
     }
     CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_event', $id, $copyEvent->id);
     $copyUF =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id));
     $copyTellFriend =& CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id));
     $copyPCP =& CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id), array('replace' => array('target_entity_id' => $copyEvent->id)));
     if ($eventValues['is_template']) {
         $field = 'event_template';
     } else {
         $field = 'civicrm_event';
     }
     $mappingId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
     $oldData = array('entity_value' => $id, 'mapping_id' => $mappingId);
     if ($copyEvent->is_template == 1) {
         $field = 'event_template';
     } else {
         $field = 'civicrm_event';
     }
     $copyMappingId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value');
     $newData = array('entity_value' => $copyEvent->id, 'mapping_id' => $copyMappingId);
     $copyReminder =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule', $oldData, $newData);
     if (!$afterCreate) {
         //copy custom data
         $extends = array('event');
         $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] = $copyEvent->id;
                 $select = 'SELECT ' . implode(', ', $tableColumns);
                 $from = ' FROM ' . $tableName;
                 $where = " WHERE {$tableName}.entity_id = {$id}";
                 $query = $insert . $select . $from . $where;
                 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
             }
         }
     }
     $copyEvent->save();
     CRM_Utils_System::flushCache();
     if (!$afterCreate) {
         CRM_Utils_Hook::copy('Event', $copyEvent);
     }
     return $copyEvent;
 }
Ejemplo n.º 2
0
 /**
  * @param $locBlockId
  * @param null $updateLocBlockId
  *
  * @return mixed
  */
 static function copyLocBlock($locBlockId, $updateLocBlockId = NULL)
 {
     //get the location info.
     $defaults = $updateValues = array();
     $locBlock = array('id' => $locBlockId);
     CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_LocBlock', $locBlock, $defaults);
     if ($updateLocBlockId) {
         //get the location info for update.
         $copyLocationParams = array('id' => $updateLocBlockId);
         CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_LocBlock', $copyLocationParams, $updateValues);
         foreach ($updateValues as $key => $value) {
             if ($key != 'id') {
                 $copyLocationParams[$key] = 'null';
             }
         }
     }
     //copy all location blocks (email, phone, address, etc)
     foreach ($defaults as $key => $value) {
         if ($key != 'id') {
             $tbl = explode("_", $key);
             $name = ucfirst($tbl[0]);
             $updateParams = NULL;
             if ($updateId = CRM_Utils_Array::value($key, $updateValues)) {
                 $updateParams = array('id' => $updateId);
             }
             $copy = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_' . $name, array('id' => $value), $updateParams);
             $copyLocationParams[$key] = $copy->id;
         }
     }
     $copyLocation =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_LocBlock', array('id' => $locBlock['id']), $copyLocationParams);
     return $copyLocation->id;
 }
Ejemplo n.º 3
0
 /**
  * This function is to make a copy of a profile, including
  * all the fields in the profile
  *
  * @param int $id the profile id to copy
  *
  * @return void
  * @access public
  */
 static function copy($id)
 {
     $fieldsFix = array('prefix' => array('title' => ts('Copy of ')));
     $copy =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFGroup', array('id' => $id), null, $fieldsFix);
     $copyUFJoin =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('uf_group_id' => $id), array('uf_group_id' => $copy->id), null, 'entity_table');
     $copyUFField =& CRM_Core_DAO::copyGeneric('CRM_Core_BAO_UFField', array('uf_group_id' => $id), array('uf_group_id' => $copy->id));
     require_once "CRM/Utils/Weight.php";
     $maxWeight = CRM_Utils_Weight::getMax('CRM_Core_DAO_UFJoin', null, 'weight');
     //update the weight
     $query = "\nUPDATE civicrm_uf_join \nSET    weight = %1\nWHERE  uf_group_id = %2\nAND    ( entity_id IS NULL OR entity_id <= 0 )\n";
     $p = array(1 => array($maxWeight + 1, 'Integer'), 2 => array($copy->id, 'Integer'));
     CRM_Core_DAO::executeQuery($query, $p);
     if ($copy->is_reserved) {
         $query = "UPDATE civicrm_uf_group SET is_reserved = 0 WHERE id = %1";
         $params = array(1 => array($copy->id, 'Integer'));
         CRM_Core_DAO::executeQuery($query, $params);
     }
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::copy('UFGroup', $copy);
     return $copy;
 }
Ejemplo n.º 4
0
 /**
  * make a copy of a profile, including
  * all the fields in the profile
  *
  * @param int $id
  *   The profile id to copy.
  *
  * @return \CRM_Core_DAO
  */
 public static function copy($id)
 {
     $fieldsFix = array('prefix' => array('title' => ts('Copy of ')));
     $copy =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFGroup', array('id' => $id), NULL, $fieldsFix);
     if ($pos = strrpos($copy->name, "_{$id}")) {
         $copy->name = substr_replace($copy->name, '', $pos);
     }
     $copy->name = CRM_Utils_String::munge($copy->name, '_', 56) . "_{$copy->id}";
     $copy->save();
     $copyUFJoin =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('uf_group_id' => $id), array('uf_group_id' => $copy->id), NULL, 'entity_table');
     $copyUFField =& CRM_Core_DAO::copyGeneric('CRM_Core_BAO_UFField', array('uf_group_id' => $id), array('uf_group_id' => $copy->id));
     $maxWeight = CRM_Utils_Weight::getMax('CRM_Core_DAO_UFJoin', NULL, 'weight');
     //update the weight
     $query = "\nUPDATE civicrm_uf_join\nSET    weight = %1\nWHERE  uf_group_id = %2\nAND    ( entity_id IS NULL OR entity_id <= 0 )\n";
     $p = array(1 => array($maxWeight + 1, 'Integer'), 2 => array($copy->id, 'Integer'));
     CRM_Core_DAO::executeQuery($query, $p);
     if ($copy->is_reserved) {
         $query = "UPDATE civicrm_uf_group SET is_reserved = 0 WHERE id = %1";
         $params = array(1 => array($copy->id, 'Integer'));
         CRM_Core_DAO::executeQuery($query, $params);
     }
     CRM_Utils_Hook::copy('UFGroup', $copy);
     return $copy;
 }
 /**
  * make a copy of a contribution page, including
  * all the blocks in the page
  *
  * @param int $id
  *   The contribution page id to copy.
  *
  * @return CRM_Contribute_DAO_ContributionPage
  */
 public static function copy($id)
 {
     $fieldsFix = array('prefix' => array('title' => ts('Copy of') . ' '));
     $copy =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_ContributionPage', array('id' => $id), NULL, $fieldsFix);
     //copying all the blocks pertaining to the contribution page
     $copyPledgeBlock =& CRM_Core_DAO::copyGeneric('CRM_Pledge_DAO_PledgeBlock', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyMembershipBlock =& CRM_Core_DAO::copyGeneric('CRM_Member_DAO_MembershipBlock', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyUFJoin =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyWidget =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Widget', array('contribution_page_id' => $id), array('contribution_page_id' => $copy->id));
     //copy price sets
     CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_contribution_page', $id, $copy->id);
     $copyTellFriend =& CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyPersonalCampaignPages =& CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id, 'target_entity_id' => $copy->id));
     $copyPremium =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Premium', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $premiumQuery = "\nSELECT id\nFROM civicrm_premiums\nWHERE entity_table = 'civicrm_contribution_page'\n      AND entity_id ={$id}";
     $premiumDao = CRM_Core_DAO::executeQuery($premiumQuery, CRM_Core_DAO::$_nullArray);
     while ($premiumDao->fetch()) {
         if ($premiumDao->id) {
             $copyPremiumProduct =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_PremiumsProduct', array('premiums_id' => $premiumDao->id), array('premiums_id' => $copyPremium->id));
         }
     }
     $copy->save();
     CRM_Utils_Hook::copy('ContributionPage', $copy);
     return $copy;
 }
Ejemplo n.º 6
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     //format params
     $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
     $params['end_date'] = CRM_Utils_Date::processDate($params['end_date'], $params['end_date_time'], true);
     $params['has_waitlist'] = CRM_Utils_Array::value('has_waitlist', $params, false);
     $params['is_map'] = CRM_Utils_Array::value('is_map', $params, false);
     $params['is_active'] = CRM_Utils_Array::value('is_active', $params, false);
     $params['is_public'] = CRM_Utils_Array::value('is_public', $params, false);
     $params['default_role_id'] = CRM_Utils_Array::value('default_role_id', $params, false);
     $params['id'] = $this->_id;
     //new event, so lets set the created_id
     if ($this->_action & CRM_Core_Action::ADD) {
         $session =& CRM_Core_Session::singleton();
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
     }
     $customFields = CRM_Core_BAO_CustomField::getFields('Event', false, false, CRM_Utils_Array::value('event_type_id', $params));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Event');
     require_once 'CRM/Event/BAO/Event.php';
     // copy all not explicitely set $params keys from the template (if it should be sourced)
     if (CRM_Utils_Array::value('template_id', $params)) {
         $defaults = array();
         $templateParams = array('id' => $params['template_id']);
         CRM_Event_BAO_Event::retrieve($templateParams, $defaults);
         unset($defaults['id']);
         unset($defaults['default_fee_id']);
         unset($defaults['default_discount_fee_id']);
         foreach ($defaults as $key => $value) {
             if (!isset($params[$key])) {
                 $params[$key] = $value;
             }
         }
     }
     $event = CRM_Event_BAO_Event::create($params);
     // now that we have the event’s id, do some more template-based stuff
     if (CRM_Utils_Array::value('template_id', $params)) {
         // copy event fees
         $ogParams = array('name' => "civicrm_event.amount.{$event->id}");
         $defaults = array();
         require_once 'CRM/Core/BAO/OptionGroup.php';
         if (is_null(CRM_Core_BAO_OptionGroup::retrieve($ogParams, $defaults))) {
             // Copy the Main Event Fees
             CRM_Core_BAO_OptionGroup::copyValue('event', $params['template_id'], $event->id);
             // Copy the Discount option Group and Values
             require_once 'CRM/Core/BAO/Discount.php';
             $optionGroupIds = CRM_Core_BAO_Discount::getOptionGroup($params['template_id'], "civicrm_event");
             foreach ($optionGroupIds as $id) {
                 $discountSuffix = '.discount.' . CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $id, 'label');
                 CRM_Core_BAO_OptionGroup::copyValue('event', $params['template_id'], $event->id, false, $discountSuffix);
             }
         }
         // copy price sets if any
         require_once 'CRM/Price/BAO/Set.php';
         $priceSetId = CRM_Price_BAO_Set::getFor('civicrm_event', $params['template_id']);
         if ($priceSetId) {
             CRM_Price_BAO_Set::addTo('civicrm_event', $event->id, $priceSetId);
         }
         // link profiles if none linked
         $ufParams = array('entity_table' => 'civicrm_event', 'entity_id' => $event->id);
         require_once 'CRM/Core/BAO/UFJoin.php';
         if (!CRM_Core_BAO_UFJoin::findUFGroupId($ufParams)) {
             CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('entity_id' => $params['template_id'], 'entity_table' => 'civicrm_event'), array('entity_id' => $event->id));
         }
         // if no Tell-a-Friend defined, check whether there’s one for template and copy if so
         $tafParams = array('entity_table' => 'civicrm_event', 'entity_id' => $event->id);
         require_once 'CRM/Friend/BAO/Friend.php';
         if (!CRM_Friend_BAO_Friend::getValues($tafParams)) {
             $tafParams['entity_id'] = $params['template_id'];
             if (CRM_Friend_BAO_Friend::getValues($tafParams)) {
                 $tafParams['entity_id'] = $event->id;
                 CRM_Friend_BAO_Friend::addTellAFriend($tafParams);
             }
         }
     }
     $this->set('id', $event->id);
     if ($this->_action & CRM_Core_Action::ADD) {
         $urlParam = "action=update&reset=1&subPage=Location&id={$event->id}";
         // special case for 'Save and Done' consistency.
         if ($this->controller->getButtonName('submit') == "_qf_EventInfo_upload_done") {
             $urlParam = "action=update&reset=1&id={$event->id}";
             CRM_Core_Session::setStatus(ts("'%1' information has been saved.", array(1 => $this->getTitle())));
         }
         CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), $urlParam));
     }
     parent::endPostProcess();
 }
Ejemplo n.º 7
0
 /**
  * This function is to make a copy of a price set, including
  * all the fields
  *
  * @param int $id the price set id to copy
  *
  * @return the copy object 
  * @access public
  * @static
  */
 static function copy($id)
 {
     $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
     $title = ts('[Copy id %1]', array(1 => $maxId + 1));
     $fieldsFix = array('suffix' => array('title' => ' ' . $title, 'name' => '__Copy_id_' . ($maxId + 1) . '_'));
     $copy =& CRM_Core_DAO::copyGeneric('CRM_Price_DAO_Set', array('id' => $id), null, $fieldsFix);
     //copying all the blocks pertaining to the price set
     $copyPriceField =& CRM_Core_DAO::copyGeneric('CRM_Price_DAO_Field', array('price_set_id' => $id), array('price_set_id' => $copy->id));
     if (!empty($copyPriceField)) {
         $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
         //copy option group and values
         require_once "CRM/Core/BAO/OptionGroup.php";
         foreach ($price as $originalId => $copyId) {
             CRM_Core_BAO_OptionGroup::copyValue('price', $originalId, $copyId);
         }
     }
     $copy->save();
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::copy('Set', $copy);
     return $copy;
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     //format params
     $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
     $params['end_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('end_date', $params), CRM_Utils_Array::value('end_date_time', $params), TRUE);
     $params['has_waitlist'] = CRM_Utils_Array::value('has_waitlist', $params, FALSE);
     $params['is_map'] = CRM_Utils_Array::value('is_map', $params, FALSE);
     $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
     $params['is_public'] = CRM_Utils_Array::value('is_public', $params, FALSE);
     $params['is_share'] = CRM_Utils_Array::value('is_share', $params, FALSE);
     $params['default_role_id'] = CRM_Utils_Array::value('default_role_id', $params, FALSE);
     $params['id'] = $this->_id;
     $customFields = CRM_Core_BAO_CustomField::getFields('Event', FALSE, FALSE, CRM_Utils_Array::value('event_type_id', $params));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Event');
     //merge params with defaults from templates
     if (CRM_Utils_Array::value('template_id', $params)) {
         $params = array_merge(CRM_Event_BAO_Event::getTemplateDefaultValues($params['template_id']), $params);
     }
     $event = CRM_Event_BAO_Event::create($params);
     // now that we have the event’s id, do some more template-based stuff
     if (CRM_Utils_Array::value('template_id', $params)) {
         // copy price sets if any
         $priceSetId = CRM_Price_BAO_Set::getFor('civicrm_event', $params['template_id']);
         if ($priceSetId) {
             $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'is_quick_config');
             if ($isQuickConfig) {
                 $copyPriceSet =& CRM_Price_BAO_Set::copy($priceSetId);
                 $priceSetId = $copyPriceSet->id;
             }
             CRM_Price_BAO_Set::addTo('civicrm_event', $event->id, $priceSetId);
         }
         // link profiles if none linked
         $ufParams = array('entity_table' => 'civicrm_event', 'entity_id' => $event->id);
         if (!CRM_Core_BAO_UFJoin::findUFGroupId($ufParams)) {
             CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('entity_id' => $params['template_id'], 'entity_table' => 'civicrm_event'), array('entity_id' => $event->id));
         }
         // if no Tell-a-Friend defined, check whether there’s one for template and copy if so
         $tafParams = array('entity_table' => 'civicrm_event', 'entity_id' => $event->id);
         if (!CRM_Friend_BAO_Friend::getValues($tafParams)) {
             $tafParams['entity_id'] = $params['template_id'];
             if (CRM_Friend_BAO_Friend::getValues($tafParams)) {
                 $tafParams['entity_id'] = $event->id;
                 if (isset($tafParams['id'])) {
                     unset($tafParams['id']);
                 }
                 CRM_Friend_BAO_Friend::addTellAFriend($tafParams);
             }
         }
         //copy pcp settings
         CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', array('entity_id' => $params['template_id'], 'entity_table' => 'civicrm_event'), array('entity_id' => $event->id), array('replace' => array('target_entity_id' => $event->id)));
         //copy event schedule remainder
         CRM_Core_DAO::copyGeneric('CRM_Core_DAO_ActionSchedule', array('entity_value' => $params['template_id']), array('entity_value' => $event->id));
     }
     $this->set('id', $event->id);
     if ($this->_action & CRM_Core_Action::ADD) {
         $url = 'civicrm/event/manage/location';
         $urlParams = "action=update&reset=1&id={$event->id}";
         // special case for 'Save and Done' consistency.
         if ($this->controller->getButtonName('submit') == '_qf_EventInfo_upload_done') {
             $url = 'civicrm/event/manage';
             $urlParams = 'reset=1';
             CRM_Core_Session::setStatus(ts("'%1' information has been saved.", array(1 => $this->getTitle())));
         }
         CRM_Utils_System::redirect(CRM_Utils_System::url($url, $urlParams));
     }
     parent::endPostProcess();
 }
Ejemplo n.º 9
0
 /**
  * Copy a price set, including all the fields
  *
  * @param int $id
  *   The price set id to copy.
  *
  * @return CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field
  */
 public static function copy($id)
 {
     $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_price_set");
     $title = ts('[Copy id %1]', array(1 => $maxId + 1));
     $fieldsFix = array('suffix' => array('title' => ' ' . $title, 'name' => '__Copy_id_' . ($maxId + 1) . '_'));
     $copy =& CRM_Core_DAO::copyGeneric('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Set', array('id' => $id), NULL, $fieldsFix);
     //copying all the blocks pertaining to the price set
     $copyPriceField =& CRM_Core_DAO::copyGeneric('CRM_Upgrade_Snapshot_V4p2_Price_DAO_Field', array('price_set_id' => $id), array('price_set_id' => $copy->id));
     if (!empty($copyPriceField)) {
         $price = array_combine(self::getFieldIds($id), self::getFieldIds($copy->id));
         //copy option group and values
         foreach ($price as $originalId => $copyId) {
             CRM_Core_DAO::copyGeneric('CRM_Upgrade_Snapshot_V4p2_Price_DAO_FieldValue', array('price_field_id' => $originalId), array('price_field_id' => $copyId));
         }
     }
     $copy->save();
     CRM_Utils_Hook::copy('Set', $copy);
     return $copy;
 }
Ejemplo n.º 10
0
 /**
  * This function is to make a copy of a Vacancy
  *
  * @param int $id          the vacancy id to copy
  *        obj     $newVacancy    object of CRM_HRRecruitment_DAO_HRVacancy
  *        boolean $afterCreate call to copy after the create function
  * @return void
  * @access public
  */
 static function copy($id, $newVacancy = NULL, $afterCreate = FALSE)
 {
     $vacancyValues = array();
     $vacancyParams = array('id' => $id);
     $returnProperties = array('position', 'salary', 'status_id', 'is_template');
     CRM_Core_DAO::commonRetrieve('CRM_HRRecruitment_DAO_HRVacancy', $vacancyParams, $vacancyValues, $returnProperties);
     $fieldsFix = $afterCreate ? array() : array('prefix' => array('position' => ts('Copy of') . ' '));
     if ($newVacancy && is_a($newVacancy, 'CRM_HRRecruitment_DAO_HRVacancy')) {
         $copyVacancy = $newVacancy;
     }
     if (!isset($copyVacancy)) {
         $copyVacancy =& CRM_Core_DAO::copyGeneric('CRM_HRRecruitment_DAO_HRVacancy', array('id' => $id), '', $fieldsFix);
     }
     CRM_Core_DAO::copyGeneric('CRM_HRRecruitment_DAO_HRVacancyStage', array('vacancy_id' => $id), array('vacancy_id' => $copyVacancy->id));
     CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('entity_id' => $id, 'entity_table' => 'civicrm_hrvacancy'), array('entity_id' => $copyVacancy->id));
     CRM_Core_DAO::copyGeneric('CRM_HRRecruitment_DAO_HRVacancyPermission', array('vacancy_id' => $id), array('vacancy_id' => $copyVacancy->id));
     CRM_Utils_System::flushCache();
     return $copyVacancy;
 }
Ejemplo n.º 11
0
 /**
  * This function is to make a copy of a contribution page, including
  * all the blocks in the page
  *
  * @param int $id the contribution page id to copy
  *
  * @return the copy object 
  * @access public
  * @static
  */
 static function copy($id)
 {
     $fieldsFix = array('prefix' => array('title' => ts('Copy of ')));
     $copy =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_ContributionPage', array('id' => $id), null, $fieldsFix);
     //copying all the blocks pertaining to the contribution page
     $copyPledgeBlock =& CRM_Core_DAO::copyGeneric('CRM_Pledge_DAO_PledgeBlock', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyMembershipBlock =& CRM_Core_DAO::copyGeneric('CRM_Member_DAO_MembershipBlock', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyUFJoin =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyWidget =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Widget', array('contribution_page_id' => $id), array('contribution_page_id' => $copy->id));
     //copy option group and values
     require_once "CRM/Core/BAO/OptionGroup.php";
     $copy->default_amount_id = CRM_Core_BAO_OptionGroup::copyValue('contribution', $id, $copy->id, CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $id, 'default_amount_id'));
     $copyTellFriend =& CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyPersonalCampaignPages =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_PCPBlock', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $copyPremium =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Premium', array('entity_id' => $id, 'entity_table' => 'civicrm_contribution_page'), array('entity_id' => $copy->id));
     $premiumQuery = "        \nSELECT id\nFROM civicrm_premiums\nWHERE entity_table = 'civicrm_contribution_page'\n      AND entity_id ={$id}";
     $premiumDao = CRM_Core_DAO::executeQuery($premiumQuery, CRM_Core_DAO::$_nullArray);
     while ($premiumDao->fetch()) {
         if ($premiumDao->id) {
             $copyPremiumProduct =& CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_PremiumsProduct', array('premiums_id' => $premiumDao->id), array('premiums_id' => $copyPremium->id));
         }
     }
     $copy->save();
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::copy('ContributionPage', $copy);
     return $copy;
 }
Ejemplo n.º 12
0
 /**
  * This function copies the information from parent entity and creates other entities with same information.
  *
  * @param string $entityTable
  *   Entity table name .
  * @param array $fromCriteria
  *   Array of all the fields & values on which basis to copy .
  * @param array $newParams
  *   Array of all the fields & values to be copied besides the other fields .
  * @param bool $createRecurringEntity
  *   If to create a record in recurring_entity table .
  *
  *
  * @return object
  */
 public static function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE)
 {
     $daoName = self::$_tableDAOMapper[$entityTable];
     if (!$daoName) {
         CRM_Core_Error::fatal("DAO Mapper missing for {$entityTable}.");
     }
     $newObject = CRM_Core_DAO::copyGeneric($daoName, $fromCriteria, $newParams);
     if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id && $createRecurringEntity) {
         $object = new $daoName();
         foreach ($fromCriteria as $key => $value) {
             $object->{$key} = $value;
         }
         $object->find(TRUE);
         CRM_Core_BAO_RecurringEntity::quickAdd($object->id, $newObject->id, $entityTable);
     }
     return $newObject;
 }
Ejemplo n.º 13
0
 /**
  * Function to copy the option group and values
  * 
  * @param  String $component      - component page for which custom 
  *                                  option group and values need to be copied 
  * @param  int    $fromId         - component page id on which
  *                                  basis copy is to be made 
  * @param  int    $toId           - component page id to be copied onto 
  * @param  int    $defaultId      - default custom value id on the 
  *                                  component page 
  * @param  String $discountSuffix - discount suffix for the discounted
  *                                  option group
  * 
  * @return int   $id              - default custom value id for the 
  *                                 copied component page 
  * 
  * @access public
  * @static
  */
 static function copyValue($component, $fromId, $toId, $defaultId = false, $discountSuffix = null)
 {
     $page = '_page';
     if ($component == 'event') {
         //fix for CRM-3391.
         //as for event we remove 'page' from group name.
         $page = null;
     } elseif ($component == 'price') {
         $page = '_field';
     }
     $fromGroupName = 'civicrm_' . $component . $page . '.amount.' . $fromId . $discountSuffix;
     $toGroupName = 'civicrm_' . $component . $page . '.amount.' . $toId . $discountSuffix;
     $optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $fromGroupName, 'id', 'name');
     if ($optionGroupId) {
         $copyOptionGroup =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_OptionGroup', array('name' => $fromGroupName), array('name' => $toGroupName));
         $copyOptionValue =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_OptionValue', array('option_group_id' => $optionGroupId), array('option_group_id' => $copyOptionGroup->id));
         if ($discountSuffix) {
             $copyDiscount =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_Discount', array('entity_id' => $fromId, 'entity_table' => 'civicrm_' . $component, 'option_group_id' => $optionGroupId), array('entity_id' => $toId, 'option_group_id' => $copyOptionGroup->id));
         }
         if ($defaultId) {
             $query = "\nSELECT second.id default_id \nFROM civicrm_option_value first, civicrm_option_value second\nWHERE second.option_group_id =%1\nAND first.option_group_id =%2\nAND first.weight = second.weight\nAND first.id =%3\n";
             $params = array(1 => array($copyOptionGroup->id, 'Int'), 2 => array($optionGroupId, 'Int'), 3 => array($defaultId, 'Int'));
             $dao = CRM_Core_DAO::executeQuery($query, $params);
             while ($dao->fetch()) {
                 $id = $dao->default_id;
             }
             return $id;
         }
         return false;
     }
 }
Ejemplo n.º 14
0
 /**
  * This function is to make a copy of a Event, including
  * all the fields in the event Wizard
  *
  * @param int $id the event id to copy
  *
  * @return void
  * @access public
  */
 static function copy($id)
 {
     $defaults = $eventValues = array();
     //get the require event values.
     $eventParams = array('id' => $id);
     $returnProperties = array('loc_block_id', 'is_show_location', 'default_fee_id', 'default_discount_fee_id');
     CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $eventParams, $eventValues, $returnProperties);
     // since the location is sharable, lets use the same loc_block_id.
     $locBlockId = CRM_Utils_Array::value('loc_block_id', $eventValues);
     $fieldsFix = array('prefix' => array('title' => ts('Copy of') . ' '));
     if (!CRM_Utils_Array::value('is_show_location', $eventValues)) {
         $fieldsFix['prefix']['is_show_location'] = 0;
     }
     $copyEvent =& CRM_Core_DAO::copyGeneric('CRM_Event_DAO_Event', array('id' => $id), array('loc_block_id' => $locBlockId ? $locBlockId : null), $fieldsFix);
     $copyPriceSet =& CRM_Core_DAO::copyGeneric('CRM_Price_DAO_SetEntity', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id));
     $copyUF =& CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id));
     $copyTellFriend =& CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', array('entity_id' => $id, 'entity_table' => 'civicrm_event'), array('entity_id' => $copyEvent->id));
     require_once "CRM/Core/BAO/OptionGroup.php";
     //copy option Group and values
     $copyEvent->default_fee_id = CRM_Core_BAO_OptionGroup::copyValue('event', $id, $copyEvent->id, CRM_Utils_Array::value('default_fee_id', $eventValues));
     //copy discounted fee levels
     require_once 'CRM/Core/BAO/Discount.php';
     $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
     if (!empty($discount)) {
         foreach ($discount as $discountOptionGroup) {
             $name = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', $discountOptionGroup);
             $length = substr_compare($name, "civicrm_event.amount." . $id, 0);
             $discountSuffix = substr($name, $length * -1);
             $copyEvent->default_discount_fee_id = CRM_Core_BAO_OptionGroup::copyValue('event', $id, $copyEvent->id, CRM_Utils_Array::value('default_discount_fee_id', $eventValues), $discountSuffix);
         }
     }
     //copy custom data
     require_once 'CRM/Core/BAO/CustomGroup.php';
     $extends = array('event');
     $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] = $copyEvent->id;
             $select = 'SELECT ' . implode(', ', $tableColumns);
             $from = ' FROM ' . $tableName;
             $where = " WHERE {$tableName}.entity_id = {$id}";
             $query = $insert . $select . $from . $where;
             $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
         }
     }
     $copyEvent->save();
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::copy('Event', $copyEvent);
     return $copyEvent;
 }
Ejemplo n.º 15
0
 /**
  * Copy priceSet when event/contibution page is copied
  *
  * @param string $baoName
  *   BAO name.
  * @param int $id
  *   Old event/contribution page id.
  * @param int $newId
  *   Newly created event/contribution page id.
  */
 public static function copyPriceSet($baoName, $id, $newId)
 {
     $priceSetId = CRM_Price_BAO_PriceSet::getFor($baoName, $id);
     if ($priceSetId) {
         $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config');
         if ($isQuickConfig) {
             $copyPriceSet = CRM_Price_BAO_PriceSet::copy($priceSetId);
             CRM_Price_BAO_PriceSet::addTo($baoName, $newId, $copyPriceSet->id);
         } else {
             $copyPriceSet =& CRM_Core_DAO::copyGeneric('CRM_Price_DAO_PriceSetEntity', array('entity_id' => $id, 'entity_table' => $baoName), array('entity_id' => $newId));
         }
         // copy event discount
         if ($baoName == 'civicrm_event') {
             $discount = CRM_Core_BAO_Discount::getOptionGroup($id, 'civicrm_event');
             foreach ($discount as $discountId => $setId) {
                 $copyPriceSet =& CRM_Price_BAO_PriceSet::copy($setId);
                 CRM_Core_DAO::copyGeneric('CRM_Core_DAO_Discount', array('id' => $discountId), array('entity_id' => $newId, 'price_set_id' => $copyPriceSet->id));
             }
         }
     }
 }
Ejemplo n.º 16
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;
    }
Ejemplo n.º 17
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.
     *
     * @return void.
     * @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;
        }
        require_once 'CRM/Core/PseudoConstant.php';
        $activityTypes = CRM_Core_PseudoConstant::activityType(true, true, false, 'name');
        $activityStatuses = CRM_Core_PseudoConstant::activityStatus('name');
        $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;
            }
        }
        require_once 'CRM/Case/DAO/CaseContact.php';
        require_once 'CRM/Activity/DAO/Activity.php';
        require_once 'CRM/Case/DAO/CaseActivity.php';
        require_once 'CRM/Contact/DAO/Relationship.php';
        require_once 'CRM/Activity/DAO/ActivityTarget.php';
        require_once 'CRM/Activity/DAO/ActivityAssignment.php';
        require_once 'CRM/Activity/BAO/Activity.php';
        $session = CRM_Core_Session::singleton();
        $currentUserId = $session->get('userID');
        // 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;
                }
                $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();
            } else {
                if (!$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);
                //do check for merging contact,
                if ($mainActivity->source_contact_id == $otherContactId) {
                    $mainActivity->source_contact_id = $mainContactId;
                }
                $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 activites
                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 target activities.
                $otherTargetActivity = new CRM_Activity_DAO_ActivityTarget();
                $otherTargetActivity->activity_id = $otherActivityId;
                $otherTargetActivity->find();
                while ($otherTargetActivity->fetch()) {
                    $mainActivityTarget = new CRM_Activity_DAO_ActivityTarget();
                    $mainActivityTarget->activity_id = $mainActivityId;
                    $mainActivityTarget->target_contact_id = $otherTargetActivity->target_contact_id;
                    if ($mainActivityTarget->target_contact_id == $otherContactId) {
                        $mainActivityTarget->target_contact_id = $mainContactId;
                    }
                    //avoid duplicate object.
                    if (!$mainActivityTarget->find(true)) {
                        $mainActivityTarget->save();
                    }
                    $mainActivityTarget->free();
                }
                $otherTargetActivity->free();
                //migrate assignee activities.
                $otherAssigneeActivity = new CRM_Activity_DAO_ActivityAssignment();
                $otherAssigneeActivity->activity_id = $otherActivityId;
                $otherAssigneeActivity->find();
                while ($otherAssigneeActivity->fetch()) {
                    $mainAssigneeActivity = new CRM_Activity_DAO_ActivityAssignment();
                    $mainAssigneeActivity->activity_id = $mainActivityId;
                    $mainAssigneeActivity->assignee_contact_id = $otherAssigneeActivity->assignee_contact_id;
                    if ($mainAssigneeActivity->assignee_contact_id == $otherContactId) {
                        $mainAssigneeActivity->assignee_contact_id = $mainContactId;
                    }
                    //avoid duplicate object.
                    if (!$mainAssigneeActivity->find(true)) {
                        $mainAssigneeActivity->save();
                    }
                    $mainAssigneeActivity->free();
                }
                $otherAssigneeActivity->free();
            }
            //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) {
                require_once 'CRM/Contact/BAO/Contact.php';
                $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));
            } else {
                if ($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);
        }
        return $mainCaseIds;
    }