示例#1
0
/**
 * PriceSet.FetchSection API
 *
 * @param array $params
 * @return array API result descriptor
 * @see civicrm_api3_create_success
 * @see civicrm_api3_create_error
 * @throws API_Exception
 */
function civicrm_api3_workflow_save($params)
{
    if (!array_key_exists("data", $params) || !$params['data']) {
        throw new API_Exception('Missing parameter: data', 170);
    }
    if (!array_key_exists("wid", $params) || !$params['wid']) {
        throw new API_Exception('Missing parameter: wid', 170);
    }
    $wid = $params['wid'];
    $d = urldecode($params['data']);
    $data = parse_str($d);
    //I don't know why this is important, but it made things work.
    $try2 = parse_str($params['data']);
    //Hook in case someone wants to alter the data
    CRM_Workflow_hook::beforeSave($wid, $data);
    $transaction = new CRM_Core_Transaction();
    $dsql = "DELETE FROM civicrm_workflow_detail WHERE workflow_id = {$wid}";
    $dao =& CRM_Core_DAO::executeQuery($dsql);
    if (!empty($data)) {
        $sql = "INSERT INTO civicrm_workflow_detail ( workflow_id, entity_table, entity_id, `order`, breadcrumb, `next`, title) VALUES ";
        $i = 1;
        $vals = array();
        foreach ($data as $key => $d) {
            //$did = (strpos($id, ":")) ? 0 : $id;
            $eid = $d['entity_id'];
            $e_type = $d['entity_table'];
            $order = $d['order'];
            $breadcrumb = $d['breadcrumb'];
            $next = $d['next'];
            $title = $d['title'];
            $sql = $sql . "( %" . ($i + 0) . ", %" . ($i + 1) . ", %" . ($i + 2) . ", %" . ($i + 3) . ", %" . ($i + 4) . ", %" . ($i + 5) . ", %" . ($i + 6) . "),";
            //$vals[$i++] = array($did, 'Integer');
            $vals[$i++] = array($wid, 'Integer');
            $vals[$i++] = array($e_type, 'String');
            $vals[$i++] = array($eid, 'String');
            $vals[$i++] = array($order, 'Integer');
            $vals[$i++] = array($breadcrumb, 'String');
            $vals[$i++] = array($next, 'String');
            $vals[$i++] = array($title, 'String');
        }
        $sql = substr($sql, 0, -1);
        try {
            $dao =& CRM_Core_DAO::executeQuery($sql, $vals);
        } catch (Exception $e) {
            $transaction->rollback();
            return civicrm_api3_create_error($e . message);
        }
        //TODO: Better error checking?
        if ($dao->_lastError) {
            $transaction->rollback();
        } else {
            $transaction->commit();
            CRM_Workflow_hook::afterSave($wid, $data);
        }
    }
    $returnValues = array();
    return civicrm_api3_create_success($returnValues, $params, 'PriceSet', 'FetchSection');
}
示例#2
0
 public function endTest(\PHPUnit_Framework_Test $test, $time)
 {
     if ($test instanceof TransactionalInterface) {
         $this->tx->rollback()->commit();
         $this->tx = NULL;
     }
     if ($test instanceof HookInterface) {
         \CRM_Utils_Hook::singleton()->reset();
     }
     if ($this->isCiviTest($test)) {
         error_reporting(E_ALL & ~E_NOTICE);
         $this->errorScope = NULL;
     }
 }
function ndiciviparty_add_default_dashboard($contactid)
{
    $result = civicrm_api3('Dashboard', 'get', array('name' => "contact_per_month"));
    $exists = 0;
    $dashletid = 0;
    if ($result['count'] > 0) {
        $dashletid = $result['id'];
        $result = civicrm_api3('DashboardContact', 'get', array('contact_id' => $contactid, 'return' => array("dashboard_id", "contact_id")));
        if ($result['count'] > 0) {
            foreach ($result['values'] as $key => $value) {
                if ($value['dashboard_id'] == $dashletid) {
                    $exists = 1;
                }
            }
        }
        if ($exists != 1) {
            $tx = new CRM_Core_Transaction();
            $dashlet = array('dashboard_id' => $dashletid, 'contact_id' => $contactid, 'is_active' => 1, 'column_no' => 0, 'is_minimized' => 0, 'is_fullscreen' => 0, 'weight' => 0);
            try {
                $add = civicrm_api3('DashboardContact', 'create', $dashlet);
            } catch (CiviCRM_API3_Exception $e) {
                $tx->rollback();
                echo get_class($e) . ' -- ' . $e->getMessage() . "\n";
                echo $e->getTraceAsString() . "\n";
                print_r($e->getExtraParams());
            }
        }
        //end if exists
    }
    //end if dashlet found
}
/**
 * Add or update a link between contribution and membership
 *
 * @param  array   $params           (reference ) input parameters
 *
 * @return array (reference )        membership_payment_id of created or updated record
 * @static void
 * @access public
 */
function &civicrm_membershipcontributionlink_create(&$params)
{
    _civicrm_initialize();
    if (empty($params)) {
        return civicrm_create_error(ts('No input parameters present'));
    }
    if (!is_array($params)) {
        return civicrm_create_error(ts('Input parameters is not an array'));
    }
    if (!isset($params['contribution_id']) || !isset($params['membership_id'])) {
        return civicrm_create_error(ts('Required parameters missing'));
    }
    require_once 'CRM/Core/Transaction.php';
    $transaction = new CRM_Core_Transaction();
    require_once 'CRM/Member/DAO/MembershipPayment.php';
    $mpDAO =& new CRM_Member_DAO_MembershipPayment();
    $mpDAO->copyValues($params);
    $result = $mpDAO->save();
    if (is_a($result, 'CRM_Core_Error')) {
        $transaction->rollback();
        return civicrm_create_error($result->_errors[0]['message']);
    }
    $transaction->commit();
    _civicrm_object_to_array($mpDAO, $mpArray);
    return $mpArray;
}
 /**
  * takes an associative array and creates a price field object
  *
  * This function is invoked from within the web form layer and also from the api layer
  *
  * @param array $params (reference) an assoc array of name/value pairs
  *
  * @return object CRM_Price_DAO_PriceField object
  * @access public
  * @static
  */
 static function create(&$params)
 {
     if (empty($params['id']) && empty($params['name'])) {
         $params['name'] = strtolower(CRM_Utils_String::munge($params['label'], '_', 242));
     }
     $transaction = new CRM_Core_Transaction();
     $priceField = self::add($params);
     if (is_a($priceField, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $priceField;
     }
     $optionsIds = array();
     $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
     if ($priceField->html_type == 'Text') {
         $maxIndex = 1;
         $fieldValue = new CRM_Price_DAO_PriceFieldValue();
         $fieldValue->price_field_id = $priceField->id;
         // update previous field values( if any )
         if ($fieldValue->find(TRUE)) {
             $optionsIds['id'] = $fieldValue->id;
         }
     }
     $defaultArray = array();
     //html type would be empty in update scenario not sure what would happen ...
     if (!empty($params['html_type']) && $params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
         $tempArray = array_keys($params['default_checkbox_option']);
         foreach ($tempArray as $v) {
             if ($params['option_amount'][$v]) {
                 $defaultArray[$v] = 1;
             }
         }
     } else {
         if (!empty($params['default_option'])) {
             $defaultArray[$params['default_option']] = 1;
         }
     }
     for ($index = 1; $index <= $maxIndex; $index++) {
         if (array_key_exists('option_amount', $params) && array_key_exists($index, $params['option_amount']) && (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_label', $params)) || !empty($params['is_quick_config'])) && !CRM_Utils_System::isNull($params['option_amount'][$index])) {
             $options = array('price_field_id' => $priceField->id, 'label' => trim($params['option_label'][$index]), 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64), 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])), 'count' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_count', $params), NULL), 'max_value' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_max_value', $params), NULL), 'description' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_description', $params), NULL), 'membership_type_id' => CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_type_id', $params), NULL), 'weight' => $params['option_weight'][$index], 'is_active' => 1, 'is_default' => CRM_Utils_Array::value($params['option_weight'][$index], $defaultArray) ? $defaultArray[$params['option_weight'][$index]] : 0, 'membership_num_terms' => NULL);
             if ($options['membership_type_id']) {
                 $options['membership_num_terms'] = CRM_Utils_Array::value($index, CRM_Utils_Array::value('membership_num_terms', $params), 1);
             }
             if (CRM_Utils_Array::value($index, CRM_Utils_Array::value('option_financial_type_id', $params))) {
                 $options['financial_type_id'] = $params['option_financial_type_id'][$index];
             } elseif (!empty($params['financial_type_id'])) {
                 $options['financial_type_id'] = $params['financial_type_id'];
             }
             if ($opIds = CRM_Utils_Array::value('option_id', $params)) {
                 if ($opId = CRM_Utils_Array::value($index, $opIds)) {
                     $optionsIds['id'] = $opId;
                 } else {
                     $optionsIds['id'] = NULL;
                 }
             }
             CRM_Price_BAO_PriceFieldValue::create($options, $optionsIds);
         }
     }
     $transaction->commit();
     return $priceField;
 }
 function run()
 {
     // get the requested action
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
     // assign vars to templates
     $this->assign('action', $action);
     $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
     if ($action & CRM_Core_Action::UPDATE) {
         $controller = new CRM_Core_Controller_Simple('CRM_Wci_Form_ProgressBar', 'Edit Progressbar', CRM_Core_Action::UPDATE);
         $controller->set('id', $id);
         $controller->process();
         return $controller->run();
     } elseif ($action & CRM_Core_Action::COPY) {
         try {
             $sql = "INSERT INTO civicrm_wci_progress_bar (name, starting_amount, goal_amount)\n        SELECT concat(name, '-', (SELECT MAX(id) FROM civicrm_wci_progress_bar)),\n        starting_amount, goal_amount FROM civicrm_wci_progress_bar\n        WHERE id=%1";
             CRM_Core_DAO::executeQuery($sql, array(1 => array($id, 'Integer')));
             $new_pb_id = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()');
             $sql = "INSERT INTO civicrm_wci_progress_bar_formula\n            (contribution_page_id, financial_type_id, progress_bar_id, start_date, end_date, percentage)\n            SELECT contribution_page_id, financial_type_id, %1, start_date,\n            end_date, percentage FROM civicrm_wci_progress_bar_formula WHERE progress_bar_id=%2";
             CRM_Core_DAO::executeQuery($sql, array(1 => array($new_pb_id, 'Integer'), 2 => array($id, 'Integer')));
         } catch (Exception $e) {
             CRM_Core_Session::setStatus(ts('Failed to create Progress bar. ') . $e->getMessage(), '', 'error');
             $transaction->rollback();
         }
     } elseif ($action & CRM_Core_Action::DELETE) {
         $errorScope = CRM_Core_TemporaryErrorScope::useException();
         try {
             $transaction = new CRM_Core_Transaction();
             $sql = "DELETE FROM civicrm_wci_progress_bar_formula where progress_bar_id = %1";
             $params = array(1 => array($id, 'Integer'));
             CRM_Core_DAO::executeQuery($sql, $params);
             $sql = "DELETE FROM civicrm_wci_progress_bar where id = %1";
             $params = array(1 => array($id, 'Integer'));
             CRM_Core_DAO::executeQuery($sql, $params);
             $transaction->commit();
         } catch (Exception $e) {
             $errmgs = $e->getMessage() . ts('. Check whether progressbar is used by any widget or not');
             CRM_Core_Session::setStatus($errmgs, '', 'error');
             $transaction->rollback();
         }
     }
     // Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml
     CRM_Utils_System::setTitle(ts('Progress Bar List'));
     $query = "SELECT * FROM civicrm_wci_progress_bar";
     $params = array();
     $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Wci_DAO_ProgressBar');
     while ($dao->fetch()) {
         $con_page[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $con_page[$dao->id]);
         $action = array_sum(array_keys($this->actionLinks()));
         //build the normal action links.
         $con_page[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id));
     }
     if (isset($con_page)) {
         $this->assign('rows', $con_page);
     }
     return parent::run();
 }
示例#7
0
 /**
  * Construct a new mailingab object.
  *
  * @params array $params
  *   Form values.
  *
  * @param array $params
  * @param array $ids
  *
  * @return object
  *   $mailingab      The new mailingab object
  */
 public static function create(&$params, $ids = array())
 {
     $transaction = new CRM_Core_Transaction();
     $mailingab = self::add($params, $ids);
     if (is_a($mailingab, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $mailingab;
     }
     $transaction->commit();
     return $mailingab;
 }
 /**
  * @param array $params
  *
  * @return this|null
  */
 public static function &create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     $statusType = self::add($params);
     if (is_a($statusType, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $statusType;
     }
     $transaction->commit();
     return $statusType;
 }
示例#9
0
 /**
  * @param array $params
  *
  * @return $this
  * @throws Exception
  */
 public static function create($params)
 {
     $transaction = new CRM_Core_Transaction();
     $cart = self::add($params);
     if (is_a($cart, 'CRM_Core_Error')) {
         $transaction->rollback();
         CRM_Core_Error::fatal(ts('There was an error creating an event cart'));
     }
     $transaction->commit();
     return $cart;
 }
示例#10
0
 function run()
 {
     // get the requested action
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
     // assign vars to templates
     $this->assign('action', $action);
     $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
     if ($action & CRM_Core_Action::UPDATE) {
         $controller = new CRM_Core_Controller_Simple('CRM_Wci_Form_CreateWidget', 'Edit Widget', CRM_Core_Action::UPDATE);
         $controller->set('id', $id);
         $controller->process();
         return $controller->run();
     } elseif ($action & CRM_Core_Action::COPY) {
         try {
             $sql = "INSERT INTO civicrm_wci_widget (title, logo_image, image,\n        button_title, button_link_to, progress_bar_id, description,\n        email_signup_group_id, size_variant, color_title, color_title_bg,\n        color_progress_bar, color_progress_bar_bg, color_widget_bg, color_description, color_border,\n        color_button, color_button_bg, hide_title, hide_border, hide_pbcap,\n        color_btn_newsletter, color_btn_newsletter_bg, newsletter_text,\n        color_newsletter_text, style_rules, override, custom_template, show_pb_perc)\n        SELECT concat(title, '-', (SELECT MAX(id) FROM civicrm_wci_widget)), logo_image, image,\n        button_title, button_link_to, progress_bar_id, description,\n        email_signup_group_id, size_variant, color_title, color_title_bg,\n        color_progress_bar, color_progress_bar_bg, color_widget_bg, color_description, color_border,\n        color_button, color_button_bg, hide_title, hide_border, hide_pbcap,\n        color_btn_newsletter, color_btn_newsletter_bg, newsletter_text,\n        color_newsletter_text, style_rules, override, custom_template, show_pb_perc FROM civicrm_wci_widget WHERE id=%1";
             CRM_Core_DAO::executeQuery("SET foreign_key_checks = 0;");
             CRM_Core_DAO::executeQuery($sql, array(1 => array($id, 'Integer')));
             CRM_Core_DAO::executeQuery("SET foreign_key_checks = 1;");
         } catch (Exception $e) {
             CRM_Core_Session::setStatus(ts('Failed to create widget. ') . $e->getMessage(), '', 'error');
             $transaction->rollback();
         }
     } elseif ($action & CRM_Core_Action::DELETE) {
         try {
             $transaction = new CRM_Core_Transaction();
             $sql = "DELETE FROM civicrm_wci_widget where id = %1";
             $params = array(1 => array($id, 'Integer'));
             CRM_Core_DAO::executeQuery($sql, $params);
             $transaction->commit();
         } catch (Exception $e) {
             CRM_Core_Session::setStatus(ts('Failed to delete widget. ') . $e->getMessage(), '', 'error');
             $transaction->rollback();
         }
     }
     CRM_Utils_System::setTitle(ts('Widget List'));
     $query = "SELECT * FROM civicrm_wci_widget";
     $params = array();
     $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Wci_DAO_Widget');
     while ($dao->fetch()) {
         $wid_page[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $wid_page[$dao->id]);
         $wid_page[$dao->id]['title'] = $wid_page[$dao->id]['title'];
         $description = $wid_page[$dao->id]['description'];
         $wid_page[$dao->id]['description'] = strip_tags($description);
         $action = array_sum(array_keys($this->actionLinks()));
         //build the normal action links.
         $wid_page[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id));
     }
     if (isset($wid_page)) {
         $this->assign('rows', $wid_page);
     }
     parent::run();
 }
示例#11
0
 /**
  * @param array $params
  *
  * @return object $this|CRM_Event_Cart_BAO_EventInCart
  * @throws Exception
  */
 public static function create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     $event_in_cart = new CRM_Event_Cart_BAO_EventInCart();
     $event_in_cart->copyValues($params);
     $event_in_cart = $event_in_cart->save();
     if (is_a($event_in_cart, 'CRM_Core_Error')) {
         $transaction->rollback();
         CRM_Core_Error::fatal(ts('There was an error creating an event_in_cart'));
     }
     $transaction->commit();
     return $event_in_cart;
 }
示例#12
0
 /**
  * Delete all slots (associated bookings) for a particular resource
  */
 static function delByResource($resourceId)
 {
     $result = civicrm_api3('Slot', 'get', array('resource_id' => $resourceId, 'is_deleted' => 0));
     $slots = $result['values'];
     $transaction = new CRM_Core_Transaction();
     try {
         foreach ($slots as $slotId => $slot) {
             self::del($slotId);
         }
     } catch (Exception $e) {
         $transaction->rollback();
         CRM_Core_Error::fatal($e->getMessage());
     }
 }
/**
 * Add or update a link between contribution and membership
 *
 * @param  array   $params           (reference ) input parameters
 *
 * @return array (reference )        membership_payment_id of created or updated record
 * {@getfields MembershipPayment_create}
 * @example MembershipPaymentCreate.php
 * @access public
 */
function civicrm_api3_membership_payment_create($params)
{
    require_once 'CRM/Core/Transaction.php';
    $transaction = new CRM_Core_Transaction();
    $mpDAO = new CRM_Member_DAO_MembershipPayment();
    $mpDAO->copyValues($params);
    $result = $mpDAO->save();
    if (is_a($result, 'CRM_Core_Error')) {
        $transaction->rollback();
        return civicrm_api3_create_error($result->_errors[0]['message']);
    }
    $transaction->commit();
    _civicrm_api3_object_to_array($mpDAO, $mpArray[$mpDAO->id]);
    return civicrm_api3_create_success($mpArray, $params);
}
示例#14
0
文件: Field.php 项目: bhirsch/voipdev
 /**
  * takes an associative array and creates a price field object
  *
  * This function is invoked from within the web form layer and also from the api layer
  *
  * @param array $params (reference) an assoc array of name/value pairs
  *
  * @return object CRM_Price_DAO_Field object
  * @access public
  * @static
  */
 static function create(&$params, $ids)
 {
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $priceField =& self::add($params, $ids);
     if (is_a($priceField, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $priceField;
     }
     $options = array();
     require_once 'CRM/Price/Form/Field.php';
     $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
     if ($priceField->html_type == 'Text') {
         $maxIndex = 1;
     }
     $defaultArray = array();
     if ($params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
         $tempArray = array_keys($params['default_checkbox_option']);
         foreach ($tempArray as $v) {
             if ($params['option_value'][$v]) {
                 $defaultArray[$v] = 1;
             }
         }
     } else {
         if (CRM_Utils_Array::value('default_option', $params) && isset($params['option_value'][$params['default_option']])) {
             $defaultArray[$params['default_option']] = 1;
         }
     }
     for ($index = 1; $index <= $maxIndex; $index++) {
         if ($maxIndex == 1) {
             $description = $params['label'];
         } else {
             $description = $params['label'] . " - " . trim($params['option_label'][$index]);
         }
         if (CRM_Utils_Array::value($index, $params['option_label']) && !CRM_Utils_System::isNull($params['option_value'][$index])) {
             $options[] = array('label' => trim($params['option_label'][$index]), 'name' => CRM_Utils_Rule::cleanMoney(trim($params['option_name'][$index])), 'value' => CRM_Utils_Rule::cleanMoney(trim($params['option_value'][$index])), 'description' => $description, 'weight' => $params['option_weight'][$index], 'is_active' => 1, 'is_default' => CRM_Utils_Array::value($index, $defaultArray));
         }
     }
     if (!empty($options)) {
         $params['default_amount_id'] = null;
         $groupName = "civicrm_price_field.amount.{$priceField->id}";
         require_once 'CRM/Core/OptionGroup.php';
         CRM_Core_OptionGroup::createAssoc($groupName, $options, $params['default_amount_id']);
     }
     $transaction->commit();
     return $priceField;
 }
示例#15
0
 /**
  * takes an associative array and creates a price field object
  *
  * This function is invoked from within the web form layer and also from the api layer
  *
  * @param array $params (reference) an assoc array of name/value pairs
  *
  * @return object CRM_Price_DAO_Field object
  * @access public
  * @static
  */
 static function create(&$params, $ids)
 {
     require_once 'CRM/Core/Transaction.php';
     require_once 'CRM/Price/BAO/FieldValue.php';
     $transaction = new CRM_Core_Transaction();
     $priceField =& self::add($params, $ids);
     if (is_a($priceField, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $priceField;
     }
     $options = $optionsIds = array();
     require_once 'CRM/Price/Form/Field.php';
     $maxIndex = CRM_Price_Form_Field::NUM_OPTION;
     if ($priceField->html_type == 'Text') {
         $maxIndex = 1;
         require_once 'CRM/Price/BAO/FieldValue.php';
         $fieldValue = new CRM_Price_DAO_FieldValue();
         $fieldValue->price_field_id = $priceField->id;
         // update previous field values( if any )
         if ($fieldValue->find(true)) {
             $optionsIds['id'] = $fieldValue->id;
         }
     }
     $defaultArray = array();
     if ($params['html_type'] == 'CheckBox' && isset($params['default_checkbox_option'])) {
         $tempArray = array_keys($params['default_checkbox_option']);
         foreach ($tempArray as $v) {
             if ($params['option_amount'][$v]) {
                 $defaultArray[$v] = 1;
             }
         }
     } else {
         if (CRM_Utils_Array::value('default_option', $params) && isset($params['option_amount'][$params['default_option']])) {
             $defaultArray[$params['default_option']] = 1;
         }
     }
     for ($index = 1; $index <= $maxIndex; $index++) {
         if (CRM_Utils_Array::value($index, $params['option_label']) && !CRM_Utils_System::isNull($params['option_amount'][$index])) {
             $options = array('price_field_id' => $priceField->id, 'label' => trim($params['option_label'][$index]), 'name' => CRM_Utils_String::munge($params['option_label'][$index], '_', 64), 'amount' => CRM_Utils_Rule::cleanMoney(trim($params['option_amount'][$index])), 'count' => CRM_Utils_Array::value($index, $params['option_count'], null), 'max_value' => CRM_Utils_Array::value($index, $params['option_max_value'], null), 'description' => CRM_Utils_Array::value($index, $params['option_description'], null), 'weight' => $params['option_weight'][$index], 'is_active' => 1, 'is_default' => CRM_Utils_Array::value($index, $defaultArray));
             CRM_Price_BAO_FieldValue::add($options, $optionsIds);
         }
     }
     $transaction->commit();
     return $priceField;
 }
示例#16
0
 /**
  * takes an associative array and creates a cancellation object
  *
  * the function extract all the params it needs to initialize the create a
  * resource object. the params array could contain additional unused name/value
  * pairs
  *
  * @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_Booking_BAO_Cancellation object
  * @access public
  * @static
  */
 static function create(&$values)
 {
     $bookingID = CRM_Utils_Array::value('booking_id', $values);
     if (!$bookingID) {
         return;
     } else {
         $transaction = new CRM_Core_Transaction();
         try {
             $params = array('option_group_name' => CRM_Booking_Utils_Constants::OPTION_BOOKING_STATUS, 'name' => CRM_Booking_Utils_Constants::OPTION_VALUE_CANCELLED);
             $result = civicrm_api3('OptionValue', 'get', $params);
             $params = array();
             $params['id'] = $bookingID;
             $params['status_id'] = CRM_Utils_Array::value('value', CRM_Utils_Array::value($result['id'], $result['values']));
             $booking = CRM_Booking_BAO_Booking::create($params);
             $params = array();
             $params['booking_id'] = $bookingID;
             $percentage = CRM_Utils_Array::value('cancellation_percentage', $values);
             $bookingTotal = CRM_Utils_Array::value('booking_total', $values);
             $cancellationFee = $bookingTotal * $percentage / 100;
             $additionalCharge = CRM_Utils_Array::value('additional_charge', $values);
             if (is_numeric($additionalCharge)) {
                 $cancellationFee += $additionalCharge;
                 $params['additional_fee'] = $additionalCharge;
             }
             $params['cancellation_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('cancellation_date', $values));
             $params['comment'] = CRM_Utils_Array::value('comment', $values);
             $params['cancellation_fee'] = $cancellationFee;
             self::add($params);
             $slots = CRM_Booking_BAO_Slot::getBookingSlot($bookingID);
             foreach ($slots as $slotId => $slots) {
                 $subSlots = CRM_Booking_BAO_SubSlot::getSubSlotSlot($slotId);
                 foreach ($subSlots as $subSlotId => $subSlot) {
                     CRM_Booking_BAO_SubSlot::cancel($subSlotId);
                 }
                 CRM_Booking_BAO_Slot::cancel($slotId);
             }
             // return TRUE;
         } catch (Exception $e) {
             $transaction->rollback();
             CRM_Core_Error::fatal($e->getMessage());
         }
     }
 }
 function run()
 {
     // get the requested action
     $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
     // assign vars to templates
     $this->assign('action', $action);
     $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
     if ($action & CRM_Core_Action::UPDATE) {
         $controller = new CRM_Core_Controller_Simple('CRM_Wci_Form_NewEmbedCode', 'Edit Embed Code', CRM_Core_Action::UPDATE);
         $controller->set('id', $id);
         $controller->process();
         return $controller->run();
     } elseif ($action & CRM_Core_Action::DELETE) {
         try {
             $transaction = new CRM_Core_Transaction();
             $sql = "DELETE FROM civicrm_wci_embed_code where id = %1";
             $params = array(1 => array($id, 'Integer'));
             CRM_Core_DAO::executeQuery($sql, $params);
             $transaction->commit();
         } catch (Exception $e) {
             CRM_Core_Session::setStatus(ts('Failed to delete embed code. ') . $e->getMessage(), '', 'error');
             $transaction->rollback();
         }
     }
     CRM_Utils_System::setTitle(ts('Embed Code List'));
     $query = "SELECT * FROM civicrm_wci_embed_code";
     $params = array();
     $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Wci_DAO_EmbedCode');
     while ($dao->fetch()) {
         $emb_code[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $emb_code[$dao->id]);
         $emb_code[$dao->id]['id'] = $emb_code[$dao->id]['id'];
         $emb_code[$dao->id]['name'] = $emb_code[$dao->id]['name'];
         $action = array_sum(array_keys($this->actionLinks()));
         //build the normal action links.
         $emb_code[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id));
     }
     if (isset($emb_code)) {
         $this->assign('rows', $emb_code);
     }
     parent::run();
 }
示例#18
0
 /**
  * takes an associative array and creates a case object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  *
  * @internal param array $ids the array that holds all the db ids
  *
  * @return object CRM_Case_BAO_Case object
  * @access public
  * @static
  */
 static function &create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     if (!empty($params['id'])) {
         CRM_Utils_Hook::pre('edit', 'Case', $params['id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Case', NULL, $params);
     }
     $case = self::add($params);
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_case', $case->id);
     }
     if (is_a($case, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $case;
     }
     if (!empty($params['id'])) {
         CRM_Utils_Hook::post('edit', 'Case', $case->id, $case);
     } else {
         CRM_Utils_Hook::post('create', 'Case', $case->id, $case);
     }
     $transaction->commit();
     //we are not creating log for case
     //since case log can be tracked using log for activity.
     return $case;
 }
示例#19
0
 /**
  * Takes an associative array and creates a membership object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  * @param bool $skipRedirect
  * @param string $activityType
  *
  * @throws CRM_Core_Exception
  *
  * @return CRM_Member_BAO_Membership|CRM_Core_Error
  */
 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup')
 {
     // always calculate status if is_override/skipStatusCal is not true.
     // giving respect to is_override during import.  CRM-4012
     // To skip status calculation we should use 'skipStatusCal'.
     // eg pay later membership, membership update cron CRM-3984
     if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
         $dates = array('start_date', 'end_date', 'join_date');
         // Declare these out of courtesy as IDEs don't pick up the setting of them below.
         $start_date = $end_date = $join_date = NULL;
         foreach ($dates as $date) {
             ${$date} = $params[$date] = CRM_Utils_Date::processDate(CRM_Utils_Array::value($date, $params), NULL, TRUE, 'Ymd');
         }
         //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
         $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, FALSE);
         //CRM-3724 always skip is_admin if is_override != true.
         if (!$excludeIsAdmin && empty($params['is_override'])) {
             $excludeIsAdmin = TRUE;
         }
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($start_date, $end_date, $join_date, 'today', $excludeIsAdmin, CRM_Utils_Array::value('membership_type_id', $params), $params);
         if (empty($calcStatus)) {
             // Redirect the form in case of error
             // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
             // however since we have no idea how (if) this is triggered we can't safely move / remove it
             // NB I tried really hard to trigger this error from backoffice membership form in order to test it
             // and am convinced form validation is complete on that form WRT this error.
             $errorParams = array('message_title' => ts('No valid membership status for given dates.'), 'legacy_redirect_path' => 'civicrm/contact/view', 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member");
             throw new CRM_Core_Exception(ts("The membership cannot be saved because the status cannot be calculated for start_date: {$start_date} end_date {$end_date} join_date {$join_date} as at " . date('Y-m-d H:i:s')), 0, $errorParams);
         }
         $params['status_id'] = $calcStatus['id'];
     }
     // data cleanup only: all verifications on number of related memberships are done upstream in:
     // CRM_Member_BAO_Membership::createRelatedMemberships()
     // CRM_Contact_BAO_Relationship::relatedMemberships()
     if (isset($params['owner_membership_id'])) {
         unset($params['max_related']);
     } else {
         // if membership allows related, default max_related to value in membership_type
         if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($params['membership_type_id']);
             if (isset($membershipType['relationship_type_id'])) {
                 $params['max_related'] = CRM_Utils_Array::value('max_related', $membershipType);
             }
         }
     }
     $transaction = new CRM_Core_Transaction();
     $membership = self::add($params, $ids);
     if (is_a($membership, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $membership;
     }
     // add custom field values
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
     }
     $params['membership_id'] = $membership->id;
     if (isset($ids['membership'])) {
         $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
     }
     $params['skipLineItem'] = TRUE;
     //record contribution for this membership
     if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
         $memInfo = array_merge($params, array('membership_id' => $membership->id));
         $params['contribution'] = self::recordMembershipContribution($memInfo, $ids);
     }
     if (!empty($params['lineItems'])) {
         $params['line_item'] = $params['lineItems'];
     }
     //do cleanup line  items if membership edit the Membership type.
     if (empty($ids['contribution']) && !empty($ids['membership'])) {
         CRM_Price_BAO_LineItem::deleteLineItems($ids['membership'], 'civicrm_membership');
     }
     if (!empty($params['line_item']) && empty($ids['contribution'])) {
         CRM_Price_BAO_LineItem::processPriceSet($membership->id, $params['line_item'], CRM_Utils_Array::value('contribution', $params));
     }
     //insert payment record for this membership
     if (!empty($params['relate_contribution_id'])) {
         CRM_Member_BAO_MembershipPayment::create(array('membership_id' => $membership->id, 'membership_type_id' => $membership->membership_type_id, 'contribution_id' => $params['relate_contribution_id']));
     }
     // add activity record only during create mode and renew mode
     // also add activity if status changed CRM-3984 and CRM-2521
     if (empty($ids['membership']) || $activityType == 'Membership Renewal' || !empty($params['createActivity'])) {
         if (!empty($ids['membership'])) {
             $data = array();
             CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership', 'id', $membership->id, $data, array('contact_id', 'membership_type_id', 'source'));
             $membership->contact_id = $data[$membership->id]['contact_id'];
             $membership->membership_type_id = $data[$membership->id]['membership_type_id'];
             $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]);
         }
         // since we are going to create activity record w/
         // individual contact as a target in case of on behalf signup,
         // so get the copy of organization id, CRM-5551
         $realMembershipContactId = $membership->contact_id;
         // create activity source = individual, target = org CRM-4027
         $targetContactID = NULL;
         if (!empty($params['is_for_organization'])) {
             $targetContactID = $membership->contact_id;
             $membership->contact_id = CRM_Utils_Array::value('userId', $ids);
         }
         if (empty($membership->contact_id) && !empty($membership->owner_membership_id)) {
             $membership->contact_id = $realMembershipContactId;
         }
         if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         } elseif (empty($ids['membership'])) {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         }
         // we might created activity record w/ individual
         // contact as target so update membership object w/
         // original organization id, CRM-5551
         $membership->contact_id = $realMembershipContactId;
     }
     $transaction->commit();
     self::createRelatedMemberships($params, $membership);
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         if (empty($membership->membership_type_id)) {
             // ie in an update situation.
             $membership->find(TRUE);
         }
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id];
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         // add the recently created Membership
         CRM_Utils_Recent::add($title, $url, $membership->id, 'Membership', $membership->contact_id, NULL, $recentOther);
     }
     return $membership;
 }
示例#20
0
 /**
  * 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;
 }
示例#21
0
 /**
  * Takes an associative array and creates a participant object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return CRM_Event_BAO_Participant
  */
 public static function create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     $status = NULL;
     if (!empty($params['id'])) {
         $status = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
     }
     $participant = self::add($params);
     if (is_a($participant, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $participant;
     }
     if (!CRM_Utils_Array::value('id', $params) || isset($params['status_id']) && $params['status_id'] != $status) {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     //CRM-5403
     //for update mode
     if (self::isPrimaryParticipant($participant->id) && $status) {
         self::updateParticipantStatus($participant->id, $status, $participant->status_id);
     }
     $session = CRM_Core_Session::singleton();
     $id = $session->get('userID');
     if (!$id) {
         $id = CRM_Utils_Array::value('contact_id', $params);
     }
     // add custom field values
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_participant', $participant->id);
     }
     //process note, CRM-7634
     $noteId = NULL;
     if (!empty($params['id'])) {
         $note = CRM_Core_BAO_Note::getNote($params['id'], 'civicrm_participant');
         $noteId = key($note);
     }
     $noteValue = NULL;
     $hasNoteField = FALSE;
     foreach (array('note', 'participant_note') as $noteFld) {
         if (array_key_exists($noteFld, $params)) {
             $noteValue = $params[$noteFld];
             $hasNoteField = TRUE;
             break;
         }
     }
     if ($noteId || $noteValue) {
         if ($noteValue) {
             $noteParams = array('entity_table' => 'civicrm_participant', 'note' => $noteValue, 'entity_id' => $participant->id, 'contact_id' => $id, 'modified_date' => date('Ymd'));
             $noteIDs = array();
             if ($noteId) {
                 $noteIDs['id'] = $noteId;
             }
             CRM_Core_BAO_Note::add($noteParams, $noteIDs);
         } elseif ($noteId && $hasNoteField) {
             CRM_Core_BAO_Note::del($noteId, FALSE);
         }
     }
     // Log the information on successful add/edit of Participant data.
     $logParams = array('entity_table' => 'civicrm_participant', 'entity_id' => $participant->id, 'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id), 'modified_id' => $id, 'modified_date' => date('Ymd'));
     CRM_Core_BAO_Log::add($logParams);
     $params['participant_id'] = $participant->id;
     $transaction->commit();
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         $recentOther = array();
         if (CRM_Core_Permission::check('edit event participants')) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         }
         if (CRM_Core_Permission::check('delete in CiviEvent')) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         }
         $participantRoles = CRM_Event_PseudoConstant::participantRole();
         if ($participant->role_id) {
             $role = explode(CRM_Core_DAO::VALUE_SEPARATOR, $participant->role_id);
             foreach ($role as &$roleValue) {
                 if (isset($roleValue)) {
                     $roleValue = $participantRoles[$roleValue];
                 }
             }
             $roles = implode(', ', $role);
         }
         $roleString = empty($roles) ? '' : $roles;
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $participant->event_id, 'title');
         $title = CRM_Contact_BAO_Contact::displayName($participant->contact_id) . ' (' . $roleString . ' - ' . $eventTitle . ')';
         // add the recently created Participant
         CRM_Utils_Recent::add($title, $url, $participant->id, 'Participant', $participant->contact_id, NULL, $recentOther);
     }
     return $participant;
 }
示例#22
0
 /**
  * Process the activities.
  *
  * @param array $params
  *   Associated array of the submitted values.
  *
  * @throws CRM_Core_Exception
  *
  * @return CRM_Activity_BAO_Activity|null|object
  */
 public static function create(&$params)
 {
     // check required params
     if (!self::dataExists($params)) {
         throw new CRM_Core_Exception('Not enough data to create activity object');
     }
     $activity = new CRM_Activity_DAO_Activity();
     if (isset($params['id']) && empty($params['id'])) {
         unset($params['id']);
     }
     if (empty($params['status_id']) && empty($params['activity_status_id']) && empty($params['id'])) {
         if (isset($params['activity_date_time']) && strcmp($params['activity_date_time'], CRM_Utils_Date::processDate(date('Ymd')) == -1)) {
             $params['status_id'] = 2;
         } else {
             $params['status_id'] = 1;
         }
     }
     // Set priority to Normal for Auto-populated activities (for Cases)
     if (CRM_Utils_Array::value('priority_id', $params) === NULL && !CRM_Utils_Array::value('id', $params)) {
         $priority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
         $params['priority_id'] = array_search('Normal', $priority);
     }
     if (!empty($params['target_contact_id']) && is_array($params['target_contact_id'])) {
         $params['target_contact_id'] = array_unique($params['target_contact_id']);
     }
     if (!empty($params['assignee_contact_id']) && is_array($params['assignee_contact_id'])) {
         $params['assignee_contact_id'] = array_unique($params['assignee_contact_id']);
     }
     // CRM-9137
     if (!empty($params['id'])) {
         CRM_Utils_Hook::pre('edit', 'Activity', $activity->id, $params);
     } else {
         CRM_Utils_Hook::pre('create', 'Activity', NULL, $params);
     }
     $activity->copyValues($params);
     if (isset($params['case_id'])) {
         // CRM-8708, preserve case ID even though it's not part of the SQL model
         $activity->case_id = $params['case_id'];
     } elseif (is_numeric($activity->id)) {
         // CRM-8708, preserve case ID even though it's not part of the SQL model
         $activity->case_id = CRM_Case_BAO_Case::getCaseIdByActivityId($activity->id);
     }
     // start transaction
     $transaction = new CRM_Core_Transaction();
     $result = $activity->save();
     if (is_a($result, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $result;
     }
     $activityId = $activity->id;
     $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);
     if (isset($params['source_contact_id'])) {
         $acParams = array('activity_id' => $activityId, 'contact_id' => $params['source_contact_id'], 'record_type_id' => $sourceID);
         self::deleteActivityContact($activityId, $sourceID);
         CRM_Activity_BAO_ActivityContact::create($acParams);
     }
     // check and attach and files as needed
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_activity', $activityId);
     // attempt to save activity assignment
     $resultAssignment = NULL;
     if (!empty($params['assignee_contact_id'])) {
         $assignmentParams = array('activity_id' => $activityId);
         if (is_array($params['assignee_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
                 // first delete existing assignments if any
                 self::deleteActivityContact($activityId, $assigneeID);
             }
             $values = array();
             foreach ($params['assignee_contact_id'] as $acID) {
                 if ($acID) {
                     $values[] = "( {$activityId}, {$acID}, {$assigneeID} )";
                 }
             }
             while (!empty($values)) {
                 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
                 $str = implode(',', $input);
                 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES {$str};";
                 CRM_Core_DAO::executeQuery($sql);
             }
         } else {
             $assignmentParams['contact_id'] = $params['assignee_contact_id'];
             $assignmentParams['record_type_id'] = $assigneeID;
             if (!empty($params['id'])) {
                 $assignment = new CRM_Activity_BAO_ActivityContact();
                 $assignment->activity_id = $activityId;
                 $assignment->record_type_id = $assigneeID;
                 $assignment->find(TRUE);
                 if ($assignment->contact_id != $params['assignee_contact_id']) {
                     $assignmentParams['id'] = $assignment->id;
                     $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
                 }
             } else {
                 $resultAssignment = CRM_Activity_BAO_ActivityContact::create($assignmentParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityAssignment', $params, TRUE)) {
             self::deleteActivityContact($activityId, $assigneeID);
         }
     }
     if (is_a($resultAssignment, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $resultAssignment;
     }
     // attempt to save activity targets
     $resultTarget = NULL;
     if (!empty($params['target_contact_id'])) {
         $targetParams = array('activity_id' => $activityId);
         $resultTarget = array();
         if (is_array($params['target_contact_id'])) {
             if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
                 // first delete existing targets if any
                 self::deleteActivityContact($activityId, $targetID);
             }
             $values = array();
             foreach ($params['target_contact_id'] as $tid) {
                 if ($tid) {
                     $values[] = "( {$activityId}, {$tid},  {$targetID} )";
                 }
             }
             while (!empty($values)) {
                 $input = array_splice($values, 0, CRM_Core_DAO::BULK_INSERT_COUNT);
                 $str = implode(',', $input);
                 $sql = "INSERT IGNORE INTO civicrm_activity_contact ( activity_id, contact_id, record_type_id ) VALUES {$str};";
                 CRM_Core_DAO::executeQuery($sql);
             }
         } else {
             $targetParams['contact_id'] = $params['target_contact_id'];
             $targetParams['record_type_id'] = $targetID;
             if (!empty($params['id'])) {
                 $target = new CRM_Activity_BAO_ActivityContact();
                 $target->activity_id = $activityId;
                 $target->record_type_id = $targetID;
                 $target->find(TRUE);
                 if ($target->contact_id != $params['target_contact_id']) {
                     $targetParams['id'] = $target->id;
                     $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
                 }
             } else {
                 $resultTarget = CRM_Activity_BAO_ActivityContact::create($targetParams);
             }
         }
     } else {
         if (CRM_Utils_Array::value('deleteActivityTarget', $params, TRUE)) {
             self::deleteActivityContact($activityId, $targetID);
         }
     }
     // write to changelog before transaction is committed/rolled
     // back (and prepare status to display)
     if (!empty($params['id'])) {
         $logMsg = "Activity (id: {$result->id} ) updated with ";
     } else {
         $logMsg = "Activity created for ";
     }
     $msgs = array();
     if (isset($params['source_contact_id'])) {
         $msgs[] = "source={$params['source_contact_id']}";
     }
     if (!empty($params['target_contact_id'])) {
         if (is_array($params['target_contact_id']) && !CRM_Utils_array::crmIsEmptyArray($params['target_contact_id'])) {
             $msgs[] = "target=" . implode(',', $params['target_contact_id']);
             // take only first target
             // will be used for recently viewed display
             $t = array_slice($params['target_contact_id'], 0, 1);
             $recentContactId = $t[0];
         } elseif (isset($params['target_contact_id']) && !is_array($params['target_contact_id'])) {
             $msgs[] = "target={$params['target_contact_id']}";
             // will be used for recently viewed display
             $recentContactId = $params['target_contact_id'];
         }
     } else {
         // at worst, take source for recently viewed display
         $recentContactId = CRM_Utils_Array::value('source_contact_id', $params);
     }
     if (isset($params['assignee_contact_id'])) {
         if (is_array($params['assignee_contact_id'])) {
             $msgs[] = "assignee=" . implode(',', $params['assignee_contact_id']);
         } else {
             $msgs[] = "assignee={$params['assignee_contact_id']}";
         }
     }
     $logMsg .= implode(', ', $msgs);
     self::logActivityAction($result, $logMsg);
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_activity', $result->id);
     }
     $transaction->commit();
     if (empty($params['skipRecentView'])) {
         $recentOther = array();
         if (!empty($params['case_id'])) {
             $caseContactID = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseContact', $params['case_id'], 'contact_id', 'case_id');
             $url = CRM_Utils_System::url('civicrm/case/activity/view', "reset=1&aid={$activity->id}&cid={$caseContactID}&caseID={$params['case_id']}&context=home");
         } else {
             $q = "action=view&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home";
             if ($activity->activity_type_id != CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name')) {
                 $url = CRM_Utils_System::url('civicrm/activity', $q);
                 if ($activity->activity_type_id == CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name')) {
                     $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/pdf/add', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid={$params['source_contact_id']}&context=home");
                 } else {
                     $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/activity/add', "action=update&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
                 if (CRM_Core_Permission::check("delete activities")) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/activity/view', $q);
                 if (CRM_Core_Permission::check('delete activities')) {
                     $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/activity', "action=delete&reset=1&id={$activity->id}&atype={$activity->activity_type_id}&cid=" . CRM_Utils_Array::value('source_contact_id', $params) . "&context=home");
                 }
             }
         }
         if (!isset($activity->parent_id)) {
             $recentContactDisplay = CRM_Contact_BAO_Contact::displayName($recentContactId);
             // add the recently created Activity
             $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE);
             $activitySubject = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activity->id, 'subject');
             $title = "";
             if (isset($activitySubject)) {
                 $title = $activitySubject . ' - ';
             }
             $title = $title . $recentContactDisplay;
             if (!empty($activityTypes[$activity->activity_type_id])) {
                 $title .= ' (' . $activityTypes[$activity->activity_type_id] . ')';
             }
             CRM_Utils_Recent::add($title, $url, $activity->id, 'Activity', $recentContactId, $recentContactDisplay, $recentOther);
         }
     }
     // reset the group contact cache since smart groups might be affected due to this
     CRM_Contact_BAO_GroupContactCache::remove();
     if (!empty($params['id'])) {
         CRM_Utils_Hook::post('edit', 'Activity', $activity->id, $activity);
     } else {
         CRM_Utils_Hook::post('create', 'Activity', $activity->id, $activity);
     }
     // if the subject contains a ‘[case #…]’ string, file that activity on the related case (CRM-5916)
     $matches = array();
     if (preg_match('/\\[case #([0-9a-h]{7})\\]/', CRM_Utils_Array::value('subject', $params), $matches)) {
         $key = CRM_Core_DAO::escapeString(CIVICRM_SITE_KEY);
         $hash = $matches[1];
         $query = "SELECT id FROM civicrm_case WHERE SUBSTR(SHA1(CONCAT('{$key}', id)), 1, 7) = '{$hash}'";
         $caseParams = array('activity_id' => $activity->id, 'case_id' => CRM_Core_DAO::singleValueQuery($query));
         if ($caseParams['case_id']) {
             CRM_Case_BAO_Case::processCaseActivity($caseParams);
         } else {
             self::logActivityAction($activity, "unknown case hash encountered: {$hash}");
         }
     }
     return $result;
 }
示例#23
0
 /**
  * Process the user submitted custom data values.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     //if the delete record button is clicked
     if ($this->_deleteButtonName) {
         if (!empty($_POST[$this->_deleteButtonName]) && $this->_recordId) {
             $filterParams['id'] = $this->_customGroupId;
             $returnProperties = array('is_multiple', 'table_name');
             CRM_Core_DAO::commonRetrieve("CRM_Core_DAO_CustomGroup", $filterParams, $returnValues, $returnProperties);
             if (!empty($returnValues['is_multiple'])) {
                 if ($tableName = CRM_Utils_Array::value('table_name', $returnValues)) {
                     $sql = "DELETE FROM {$tableName} WHERE id = %1 AND entity_id = %2";
                     $sqlParams = array(1 => array($this->_recordId, 'Integer'), 2 => array($this->_id, 'Integer'));
                     CRM_Core_DAO::executeQuery($sql, $sqlParams);
                     CRM_Core_Session::setStatus(ts('Your record has been deleted.'), ts('Deleted'), 'success');
                 }
             }
             return;
         }
     }
     CRM_Utils_Hook::processProfile($this->_ufGroup['name']);
     if (!empty($params['image_URL'])) {
         CRM_Contact_BAO_Contact::processImageParams($params);
     }
     $greetingTypes = array('addressee' => 'addressee_id', 'email_greeting' => 'email_greeting_id', 'postal_greeting' => 'postal_greeting_id');
     $details = array();
     if ($this->_id) {
         $contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($this->_id, $greetingTypes);
         $details = $contactDetails[0][$this->_id];
     }
     if (!(!empty($details['addressee_id']) || !empty($details['email_greeting_id']) || CRM_Utils_Array::value('postal_greeting_id', $details))) {
         $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
         //Though Profile type is contact we need
         //Individual/Household/Organization for setting Greetings.
         if ($profileType == 'Contact') {
             $profileType = 'Individual';
             //if we editing Household/Organization.
             if ($this->_id) {
                 $profileType = CRM_Contact_BAO_Contact::getContactType($this->_id);
             }
         }
         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
         }
         foreach ($greetingTypes as $key => $value) {
             if (!array_key_exists($key, $params)) {
                 $params[$key] = CRM_Contact_BAO_Contact_Utils::defaultGreeting($profileType, $key);
             }
         }
     }
     $transaction = new CRM_Core_Transaction();
     //used to send subscribe mail to the group which user want.
     //if the profile double option in is enabled
     $mailingType = array();
     $result = NULL;
     foreach ($params as $name => $values) {
         if (substr($name, 0, 6) == 'email-') {
             $result['email'] = $values;
         }
     }
     //array of group id, subscribed by contact
     $contactGroup = array();
     if (!empty($params['group']) && CRM_Core_BAO_UFGroup::isProfileDoubleOptin()) {
         $groupSubscribed = array();
         if (!empty($result['email'])) {
             if ($this->_id) {
                 $contactGroups = new CRM_Contact_DAO_GroupContact();
                 $contactGroups->contact_id = $this->_id;
                 $contactGroups->status = 'Added';
                 $contactGroups->find();
                 $contactGroup = array();
                 while ($contactGroups->fetch()) {
                     $contactGroup[] = $contactGroups->group_id;
                     $groupSubscribed[$contactGroups->group_id] = 1;
                 }
             }
             foreach ($params['group'] as $key => $val) {
                 if (!$val) {
                     unset($params['group'][$key]);
                     continue;
                 }
                 $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $key, 'group_type', 'id');
                 $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($groupTypes, 1, -1));
                 //filter group of mailing type and unset it from params
                 if (in_array(2, $groupType)) {
                     //if group is already subscribed , ignore it
                     $groupExist = CRM_Utils_Array::key($key, $contactGroup);
                     if (!isset($groupExist)) {
                         $mailingType[] = $key;
                         unset($params['group'][$key]);
                     }
                 }
             }
         }
     }
     $addToGroupId = CRM_Utils_Array::value('add_to_group_id', $this->_ufGroup);
     if (!empty($addToGroupId)) {
         //run same check whether group is a mailing list
         $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $addToGroupId, 'group_type', 'id');
         $groupType = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($groupTypes, 1, -1));
         //filter group of mailing type and unset it from params
         if (in_array(2, $groupType) && !empty($result['email']) && CRM_Core_BAO_UFGroup::isProfileAddToGroupDoubleOptin()) {
             if (!count($contactGroup)) {
                 //array of group id, subscribed by contact
                 $contactGroup = array();
                 if ($this->_id) {
                     $contactGroups = new CRM_Contact_DAO_GroupContact();
                     $contactGroups->contact_id = $this->_id;
                     $contactGroups->status = 'Added';
                     $contactGroups->find();
                     $contactGroup = array();
                     while ($contactGroups->fetch()) {
                         $contactGroup[] = $contactGroups->group_id;
                         $groupSubscribed[$contactGroups->group_id] = 1;
                     }
                 }
             }
             //if group is already subscribed , ignore it
             $groupExist = CRM_Utils_Array::key($addToGroupId, $contactGroup);
             if (!isset($groupExist)) {
                 $mailingType[] = $addToGroupId;
                 $addToGroupId = NULL;
             }
         } else {
             // since we are directly adding contact to group lets unset it from mailing
             if ($key = array_search($addToGroupId, $mailingType)) {
                 unset($mailingType[$key]);
             }
         }
     }
     if ($this->_grid) {
         $params['group'] = $groupSubscribed;
     }
     // commenting below code, since we potentially
     // triggered maximum name field formatting cases during CRM-4430.
     // CRM-4343
     // $params['preserveDBName'] = true;
     $profileFields = $this->_fields;
     if ($this->_mode & self::MODE_EDIT && $this->_activityId && $this->_isContactActivityProfile) {
         $profileFields = $activityParams = array();
         foreach ($this->_fields as $fieldName => $field) {
             if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
                 if (isset($params[$fieldName])) {
                     $activityParams[$fieldName] = $params[$fieldName];
                 }
                 if (isset($params['activity_date_time'])) {
                     $activityParams['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
                 }
                 if (!empty($params[$fieldName]) && isset($params["{$fieldName}_id"])) {
                     $activityParams[$fieldName] = $params["{$fieldName}_id"];
                 }
             } else {
                 $profileFields[$fieldName] = $field;
             }
         }
         if (!empty($activityParams)) {
             $activityParams['version'] = 3;
             $activityParams['id'] = $this->_activityId;
             $activityParams['skipRecentView'] = TRUE;
             civicrm_api('Activity', 'create', $activityParams);
         }
     }
     if ($this->_multiRecord && $this->_recordId && $this->_multiRecordFields && $this->_recordExists) {
         $params['customRecordValues'][$this->_recordId] = array_keys($this->_multiRecordFields);
     }
     $this->_id = CRM_Contact_BAO_Contact::createProfileContact($params, $profileFields, $this->_id, $addToGroupId, $this->_gid, $this->_ctype, TRUE);
     //mailing type group
     if (!empty($mailingType)) {
         // we send in the contactID so we match the same groups and are exact, rather than relying on email
         // CRM-8710
         CRM_Mailing_Event_BAO_Subscribe::commonSubscribe($mailingType, $result, $this->_id, 'profile');
     }
     $ufGroups = array();
     if ($this->_gid) {
         $ufGroups[$this->_gid] = 1;
     } elseif ($this->_mode == self::MODE_REGISTER) {
         $ufGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup('User Registration');
     }
     foreach ($ufGroups as $gId => $val) {
         if ($notify = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify')) {
             $values = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $this->_id, NULL);
             CRM_Core_BAO_UFGroup::commonSendMail($this->_id, $values);
         }
     }
     //create CMS user (if CMS user option is selected in profile)
     if (!empty($params['cms_create_account']) && $this->_mode == self::MODE_CREATE) {
         $params['contactID'] = $this->_id;
         if (!CRM_Core_BAO_CMSUser::create($params, $this->_mail)) {
             CRM_Core_Session::setStatus(ts('Your profile is not saved and Account is not created.'), ts('Profile Error'), 'error');
             CRM_Core_Error::debug_log_message("Rolling back transaction as CMSUser Create failed in Profile_Form for contact " . $params['contactID']);
             $transaction->rollback();
             return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/profile/create', 'reset=1&gid=' . $this->_gid));
         }
     }
     $transaction->commit();
 }
示例#24
0
 /**
  * @param array $params
  *
  * @return pledge
  */
 public static function create($params)
 {
     $transaction = new CRM_Core_Transaction();
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     //calculate the scheduled date for every installment
     $now = date('Ymd') . '000000';
     $statues = $prevScheduledDate = array();
     $prevScheduledDate[1] = CRM_Utils_Date::processDate($params['scheduled_date']);
     if (CRM_Utils_Date::overdue($prevScheduledDate[1], $now)) {
         $statues[1] = array_search('Overdue', $contributionStatus);
     } else {
         $statues[1] = array_search('Pending', $contributionStatus);
     }
     for ($i = 1; $i < $params['installments']; $i++) {
         $prevScheduledDate[$i + 1] = self::calculateNextScheduledDate($params, $i);
         if (CRM_Utils_Date::overdue($prevScheduledDate[$i + 1], $now)) {
             $statues[$i + 1] = array_search('Overdue', $contributionStatus);
         } else {
             $statues[$i + 1] = array_search('Pending', $contributionStatus);
         }
     }
     if ($params['installment_amount']) {
         $params['scheduled_amount'] = $params['installment_amount'];
     } else {
         $params['scheduled_amount'] = round($params['amount'] / $params['installments'], 2);
     }
     for ($i = 1; $i <= $params['installments']; $i++) {
         // calculate the scheduled amount for every installment.
         if ($i == $params['installments']) {
             $params['scheduled_amount'] = $params['amount'] - ($i - 1) * $params['scheduled_amount'];
         }
         if (!isset($params['contribution_id']) && $params['installments'] > 1) {
             $params['status_id'] = $statues[$i];
         }
         $params['scheduled_date'] = $prevScheduledDate[$i];
         $payment = self::add($params);
         if (is_a($payment, 'CRM_Core_Error')) {
             $transaction->rollback();
             return $payment;
         }
         // we should add contribution id to only first payment record
         if (isset($params['contribution_id'])) {
             unset($params['contribution_id']);
             unset($params['actual_amount']);
         }
     }
     // update pledge status
     self::updatePledgePaymentStatus($params['pledge_id']);
     $transaction->commit();
     return $payment;
 }
示例#25
0
 /**
  * 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;
 }
示例#26
0
 /**
  * Function to delete Booking
  *
  * @param  int  $id     Id of the Resource to be deleted.
  *
  * @return boolean
  *
  * @access public
  * @static
  */
 static function del($id)
 {
     $transaction = new CRM_Core_Transaction();
     try {
         $slots = CRM_Booking_BAO_Slot::getBookingSlot($id);
         foreach ($slots as $slotId => $slots) {
             $subSlots = CRM_Booking_BAO_SubSlot::getSubSlotSlot($slotId);
             foreach ($subSlots as $subSlotId => $subSlot) {
                 CRM_Booking_BAO_SubSlot::del($subSlotId);
             }
             CRM_Booking_BAO_Slot::del($slotId);
         }
         $dao = new CRM_Booking_DAO_Booking();
         $dao->id = $id;
         $dao->is_deleted = 1;
         return $dao->save();
     } catch (Exception $e) {
         $transaction->rollback();
         CRM_Core_Error::fatal($e->getMessage());
     }
 }
 /**
  * Construct a new mailing object, along with job and mailing_group
  * objects, from the form values of the create mailing wizard.
  *
  * This function is a bit evil. It not only merges $params and saves
  * the mailing -- it also schedules the mailing and chooses the recipients.
  * Since it merges $params, it's also the only place to correctly trigger
  * multi-field validation. It should be broken up.
  *
  * In the mean time, use-cases which break under the weight of this
  * evil may find reprieve in these extra evil params:
  *
  *  - _skip_evil_bao_auto_recipients_: bool
  *  - _skip_evil_bao_auto_schedule_: bool
  *  - _evil_bao_validator_: string|callable
  *
  * </twowrongsmakesaright>
  *
  * @params array $params
  *   Form values.
  *
  * @param array $params
  * @param array $ids
  *
  * @return object
  *   $mailing      The new mailing object
  * @throws \Exception
  */
 public static function create(&$params, $ids = array())
 {
     // WTH $ids
     if (empty($ids) && isset($params['id'])) {
         $ids['mailing_id'] = $ids['id'] = $params['id'];
     }
     // CRM-12430
     // Do the below only for an insert
     // for an update, we should not set the defaults
     if (!isset($ids['id']) && !isset($ids['mailing_id'])) {
         // Retrieve domain email and name for default sender
         $domain = civicrm_api('Domain', 'getsingle', array('version' => 3, 'current_domain' => 1, 'sequential' => 1));
         if (isset($domain['from_email'])) {
             $domain_email = $domain['from_email'];
             $domain_name = $domain['from_name'];
         } else {
             $domain_email = '*****@*****.**';
             $domain_name = 'EXAMPLE.ORG';
         }
         if (!isset($params['created_id'])) {
             $session =& CRM_Core_Session::singleton();
             $params['created_id'] = $session->get('userID');
         }
         $defaults = array('override_verp' => TRUE, 'forward_replies' => FALSE, 'open_tracking' => TRUE, 'url_tracking' => TRUE, 'visibility' => 'Public Pages', 'replyto_email' => $domain_email, 'header_id' => CRM_Mailing_PseudoConstant::defaultComponent('header_id', ''), 'footer_id' => CRM_Mailing_PseudoConstant::defaultComponent('footer_id', ''), 'from_email' => $domain_email, 'from_name' => $domain_name, 'msg_template_id' => NULL, 'created_id' => $params['created_id'], 'approver_id' => NULL, 'auto_responder' => 0, 'created_date' => date('YmdHis'), 'scheduled_date' => NULL, 'approval_date' => NULL);
         // Get the default from email address, if not provided.
         if (empty($defaults['from_email'])) {
             $defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
             foreach ($defaultAddress as $id => $value) {
                 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
                     $defaults['from_email'] = $match[2];
                     $defaults['from_name'] = $match[1];
                 }
             }
         }
         $params = array_merge($defaults, $params);
     }
     /**
      * Could check and warn for the following cases:
      *
      * - groups OR mailings should be populated.
      * - body html OR body text should be populated.
      */
     $transaction = new CRM_Core_Transaction();
     $mailing = self::add($params, $ids);
     if (is_a($mailing, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $mailing;
     }
     // update mailings with hash values
     CRM_Contact_BAO_Contact_Utils::generateChecksum($mailing->id, NULL, NULL, NULL, 'mailing', 16);
     $groupTableName = CRM_Contact_BAO_Group::getTableName();
     $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName();
     /* Create the mailing group record */
     $mg = new CRM_Mailing_DAO_MailingGroup();
     $groupTypes = array('include' => 'Include', 'exclude' => 'Exclude', 'base' => 'Base');
     foreach (array('groups', 'mailings') as $entity) {
         foreach (array('include', 'exclude', 'base') as $type) {
             if (isset($params[$entity][$type])) {
                 self::replaceGroups($mailing->id, $groupTypes[$type], $entity, $params[$entity][$type]);
             }
         }
     }
     if (!empty($params['search_id']) && !empty($params['group_id'])) {
         $mg->reset();
         $mg->mailing_id = $mailing->id;
         $mg->entity_table = $groupTableName;
         $mg->entity_id = $params['group_id'];
         $mg->search_id = $params['search_id'];
         $mg->search_args = $params['search_args'];
         $mg->group_type = 'Include';
         $mg->save();
     }
     // check and attach and files as needed
     CRM_Core_BAO_File::processAttachment($params, 'civicrm_mailing', $mailing->id);
     // If we're going to autosend, then check validity before saving.
     if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && !empty($params['_evil_bao_validator_'])) {
         $cb = Civi\Core\Resolver::singleton()->get($params['_evil_bao_validator_']);
         $errors = call_user_func($cb, $mailing);
         if (!empty($errors)) {
             $fields = implode(',', array_keys($errors));
             throw new CRM_Core_Exception("Mailing cannot be sent. There are missing or invalid fields ({$fields}).", 'cannot-send', $errors);
         }
     }
     $transaction->commit();
     // Create parent job if not yet created.
     // Condition on the existence of a scheduled date.
     if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && empty($params['_skip_evil_bao_auto_schedule_'])) {
         $job = new CRM_Mailing_BAO_MailingJob();
         $job->mailing_id = $mailing->id;
         $job->status = 'Scheduled';
         $job->is_test = 0;
         if (!$job->find(TRUE)) {
             $job->scheduled_date = $params['scheduled_date'];
             $job->save();
         }
         // Populate the recipients.
         if (empty($params['_skip_evil_bao_auto_recipients_'])) {
             self::getRecipients($job->id, $mailing->id, TRUE, $mailing->dedupe_email);
         }
     }
     return $mailing;
 }
示例#28
0
 /**
  * Perform a series of operations within smaller transactions.
  *
  * @param string $nesting
  *   'reuse-tx'|'nest-tx' how to construct transaction.
  * @param array $callbacks
  *   See createContactWithTransaction.
  * @param array $existsByOffset
  *   See assertContactsMix.
  * @param string $outcome
  *   'rollback'|'implicit-commit'|'explicit-commit' how to finish transaction.
  * @return void
  */
 public function runBatch($nesting, $callbacks, $existsByOffset, $outcome)
 {
     if ($nesting != 'reuse-tx' && $nesting != 'nest-tx') {
         throw new RuntimeException('Bad test data: nesting=' . $nesting);
     }
     if ($outcome != 'rollback' && $outcome != 'implicit-commit' && $outcome != 'explicit-commit') {
         throw new RuntimeException('Bad test data: outcome=' . $nesting);
     }
     $tx = new CRM_Core_Transaction($nesting === 'reuse-tx');
     $generalOffset = count($this->cids);
     foreach ($callbacks as $callback) {
         list($cbNesting, $cbInsert, $cbOutcome) = $callback;
         $this->createContactWithTransaction($cbNesting, $cbInsert, $cbOutcome);
     }
     $this->assertContactsExistByOffset($existsByOffset, $generalOffset);
     if ($outcome == 'rollback') {
         $tx->rollback();
     } elseif ($outcome == 'explicit-commit') {
         $tx->commit();
     }
     // else: implicit-commit
 }
示例#29
0
 /**
  * Create instance.
  * takes an associative array and creates a instance object and does any related work like permissioning, adding to dashboard etc.
  *
  * This function is invoked from within the web form layer and also from the api layer
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return CRM_Report_BAO_ReportInstance
  */
 public static function &create(&$params)
 {
     if (isset($params['report_header'])) {
         $params['header'] = CRM_Utils_Array::value('report_header', $params);
     }
     if (isset($params['report_footer'])) {
         $params['footer'] = CRM_Utils_Array::value('report_footer', $params);
     }
     // build navigation parameters
     if (!empty($params['is_navigation'])) {
         if (!array_key_exists('navigation', $params)) {
             $params['navigation'] = array();
         }
         $navigationParams =& $params['navigation'];
         $navigationParams['permission'] = array();
         $navigationParams['label'] = $params['title'];
         $navigationParams['name'] = $params['title'];
         $navigationParams['current_parent_id'] = CRM_Utils_Array::value('parent_id', $navigationParams);
         $navigationParams['parent_id'] = CRM_Utils_Array::value('parent_id', $params);
         $navigationParams['is_active'] = 1;
         if ($permission = CRM_Utils_Array::value('permission', $params)) {
             $navigationParams['permission'][] = $permission;
         }
         // unset the navigation related elements, not used in report form values
         unset($params['parent_id']);
         unset($params['is_navigation']);
     }
     // add to dashboard
     $dashletParams = array();
     if (!empty($params['addToDashboard'])) {
         $dashletParams = array('label' => $params['title'], 'is_active' => 1);
         if ($permission = CRM_Utils_Array::value('permission', $params)) {
             $dashletParams['permission'][] = $permission;
         }
     }
     $transaction = new CRM_Core_Transaction();
     $instance = self::add($params);
     if (is_a($instance, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $instance;
     }
     // add / update navigation as required
     if (!empty($navigationParams)) {
         if (empty($params['id']) && empty($params['instance_id']) && !empty($navigationParams['id'])) {
             unset($navigationParams['id']);
         }
         $navigationParams['url'] = "civicrm/report/instance/{$instance->id}?reset=1";
         $navigation = CRM_Core_BAO_Navigation::add($navigationParams);
         if (!empty($navigationParams['is_active'])) {
             //set the navigation id in report instance table
             CRM_Core_DAO::setFieldValue('CRM_Report_DAO_ReportInstance', $instance->id, 'navigation_id', $navigation->id);
         } else {
             // has been removed from the navigation bar
             CRM_Core_DAO::setFieldValue('CRM_Report_DAO_ReportInstance', $instance->id, 'navigation_id', 'NULL');
         }
         //reset navigation
         CRM_Core_BAO_Navigation::resetNavigation();
     }
     // add to dashlet
     if (!empty($dashletParams)) {
         $section = 2;
         $chart = '';
         if (!empty($params['charts'])) {
             $section = 1;
             $chart = "&charts=" . $params['charts'];
         }
         $limitResult = NULL;
         if (!empty($params['row_count'])) {
             $limitResult = '&rowCount=' . $params['row_count'];
         }
         $dashletParams['name'] = "report/{$instance->id}";
         $dashletParams['url'] = "civicrm/report/instance/{$instance->id}?reset=1&section={$section}&snippet=5{$chart}&context=dashlet" . $limitResult;
         $dashletParams['fullscreen_url'] = "civicrm/report/instance/{$instance->id}?reset=1&section={$section}&snippet=5{$chart}&context=dashletFullscreen" . $limitResult;
         $dashletParams['instanceURL'] = "civicrm/report/instance/{$instance->id}";
         CRM_Core_BAO_Dashboard::addDashlet($dashletParams);
     }
     $transaction->commit();
     return $instance;
 }
示例#30
0
/**
 * HRJobContract implementation of the "delete" contract action.
 *
 * Deletes whole contract with its all revisions and entities.
 *
 * @param string $entity entity name
 * @param array $params params from civicrm_api, including 'jobcontract_id'
 * @return array|int
 */
function _civicrm_hrjobcontract_api3_deletecontractpermanently($params)
{
    $entityNames = array('HRJobDetails', 'HRJobHealth', 'HRJobHour', 'HRJobLeave', 'HRJobPay', 'HRJobPension', 'HRJobRole');
    $transaction = new CRM_Core_Transaction();
    try {
        if (empty($params['id'])) {
            throw new Exception("Cannot permanently delete Job Contract: please specify id value.");
        }
        $contract = civicrm_api('HRJobContract', 'get', $params);
        if (empty($contract['id'])) {
            throw new Exception("Cannot find Job Contract with given id (" . $params['id'] . ").");
        }
        $revisions = civicrm_api('HRJobContractRevision', 'get', array('sequential' => 1, 'options' => array('limit' => 0), 'version' => 3, 'jobcontract_id' => $params['id']));
        foreach ($revisions['values'] as $revision) {
            foreach ($entityNames as $entityName) {
                $tableName = _civicrm_get_table_name($entityName);
                $entities = civicrm_api3($entityName, 'get', array('sequential' => 1, 'options' => array('limit' => 0), 'version' => 3, 'jobcontract_revision_id' => (int) $revision[$tableName . '_revision_id']));
                if (!empty($entities['values'])) {
                    foreach ($entities['values'] as $entity) {
                        civicrm_api3($entityName, 'delete', array('version' => 3, 'id' => $entity['id']));
                    }
                }
            }
            civicrm_api3('HRJobContractRevision', 'delete', array('version' => 3, 'id' => $revision['id']));
        }
        civicrm_api3('HRJobContract', 'delete', array('version' => 3, 'id' => $contract['id']));
        return 1;
    } catch (PEAR_Exception $e) {
        $transaction->rollback();
        return civicrm_api3_create_error($e->getMessage());
    } catch (Exception $e) {
        $transaction->rollback();
        return civicrm_api3_create_error($e->getMessage());
    }
}