/**
 * Create a Event
 *
 * This API is used for creating a Event
 *
 * @param  array   $params           (reference ) input parameters
 * Allowed @params array keys are:
 * {@schema Event/Event.xml}
 *
 * @return array of newly created event property values.
 * @access public
 */
function civicrm_event_create(&$params)
{
    _civicrm_initialize();
    $errorScope = CRM_Core_TemporaryErrorScope::useException();
    try {
        civicrm_api_check_permission(__FUNCTION__, $params, TRUE);
        civicrm_verify_mandatory($params, 'CRM_Event_DAO_Event', array('start_date', 'event_type_id', 'title'));
        // Do we really want $params[id], even if we have
        // $params[event_id]? if yes then please uncomment the below line
        //$ids['event'      ] = $params['id'];
        $ids['eventTypeId'] = (int) $params['event_type_id'];
        $ids['startDate'] = $params['start_date'];
        $ids['event_id'] = CRM_Utils_Array::value('event_id', $params);
        require_once 'CRM/Event/BAO/Event.php';
        $eventBAO = CRM_Event_BAO_Event::create($params, $ids);
        if (is_a($eventBAO, 'CRM_Core_Error')) {
            return civicrm_create_error("Event is not created");
        } else {
            $event = array();
            _civicrm_object_to_array($eventBAO, $event);
            $values = array();
            $values['event_id'] = $event['id'];
            $values['is_error'] = 0;
        }
        return $values;
    } catch (Exception $e) {
        return civicrm_create_error($e->getMessage());
    }
}
 function postProcess()
 {
     $values = $this->exportValues();
     $title = str_replace("'", "''", $values['title']);
     $params = array(1 => array($title, 'String'), 2 => array($values['widget'], 'Integer'));
     if (isset($this->_id)) {
         $params += array(3 => array($this->_id, 'Integer'));
         $sql = "UPDATE civicrm_wci_embed_code SET name = %1, widget_id = %2 where id = %3";
     } else {
         $sql = "INSERT INTO civicrm_wci_embed_code (name, widget_id)VALUES (%1, %2)";
     }
     $errorScope = CRM_Core_TemporaryErrorScope::useException();
     try {
         $transaction = new CRM_Core_Transaction();
         CRM_Core_DAO::executeQuery($sql, $params);
         $transaction->commit();
         CRM_Core_Session::setStatus(ts('Embed code created successfully'), '', 'success');
         if (isset($_REQUEST['_qf_NewEmbedCode_next'])) {
             isset($this->_id) ? $embed_id = $this->_id : ($embed_id = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()'));
             CRM_Utils_System::redirect('?action=update&reset=1&id=' . $embed_id);
         } else {
             CRM_Utils_System::redirect('embed-code?reset=1');
         }
     } catch (Exception $e) {
         CRM_Core_Session::setStatus(ts('Failed to create embed code'), '', 'error');
         $transaction->rollback();
     }
     parent::postProcess();
 }
Example #3
0
 /**
  * @param string $entity
  *   type of entities to deal with
  * @param string $action
  *   create, get, delete or some special action name.
  * @param array $params
  *   array to be passed to function
  * @param null $extra
  *
  * @return array|int
  */
 public function run($entity, $action, $params, $extra = NULL)
 {
     /**
      * @var $apiProvider \Civi\API\Provider\ProviderInterface|NULL
      */
     $apiProvider = NULL;
     // TODO Define alternative calling convention makes it easier to construct $apiRequest
     // without the ambiguity of "data" vs "options"
     $apiRequest = Request::create($entity, $action, $params, $extra);
     try {
         if (!is_array($params)) {
             throw new \API_Exception('Input variable `params` is not an array', 2000);
         }
         $this->boot();
         $errorScope = \CRM_Core_TemporaryErrorScope::useException();
         list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
         $this->authorize($apiProvider, $apiRequest);
         $apiRequest = $this->prepare($apiProvider, $apiRequest);
         $result = $apiProvider->invoke($apiRequest);
         $apiResponse = $this->respond($apiProvider, $apiRequest, $result);
         return $this->formatResult($apiRequest, $apiResponse);
     } catch (\Exception $e) {
         $this->dispatcher->dispatch(Events::EXCEPTION, new ExceptionEvent($e, $apiProvider, $apiRequest));
         if ($e instanceof \PEAR_Exception) {
             $err = $this->formatPearException($e, $apiRequest);
         } elseif ($e instanceof \API_Exception) {
             $err = $this->formatApiException($e, $apiRequest);
         } else {
             $err = $this->formatException($e, $apiRequest);
         }
         return $this->formatResult($apiRequest, $err);
     }
 }
 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();
 }
 function activate()
 {
     $this->active = TRUE;
     $this->backup = array();
     foreach (array('display_errors', 'html_errors', 'xmlrpc_errors') as $key) {
         $this->backup[$key] = ini_get($key);
         ini_set($key, 0);
     }
     set_error_handler(array($this, 'onError'), $this->level);
     // FIXME make this temporary/reversible
     $this->errorScope = CRM_Core_TemporaryErrorScope::useException();
 }
/**
 * @todo Write sth
 *
 * @param  array   $params           (reference ) input parameters
 *
 * Allowed @params array keys are:
 * {@schema Contact/Contact.xml}
 * {@schema Core/Address.xml}}
 *
 * @return array (reference )        contact_id of created or updated contact
 *
 * @static void
 * @access public
 */
function civicrm_contact_create(&$params)
{
    // call update and tell it to create a new contact
    _civicrm_initialize();
    $errorScope = CRM_Core_TemporaryErrorScope::useException();
    try {
        civicrm_api_check_permission(__FUNCTION__, $params, TRUE);
        $create_new = TRUE;
        return civicrm_contact_update($params, $create_new);
    } catch (Exception $e) {
        return civicrm_create_error($e->getMessage());
    }
}
Example #7
0
 public function startTest(\PHPUnit_Framework_Test $test)
 {
     if ($this->isCiviTest($test)) {
         error_reporting(E_ALL);
         $this->errorScope = \CRM_Core_TemporaryErrorScope::useException();
     }
     if ($test instanceof HeadlessInterface) {
         $this->bootHeadless($test);
     }
     if ($test instanceof HookInterface) {
         // Note: bootHeadless() indirectly resets any hooks, which means that hook_civicrm_config
         // is unsubscribable. However, after bootHeadless(), we're free to subscribe to hooks again.
         $this->registerHooks($test);
     }
     if ($test instanceof TransactionalInterface) {
         $this->tx = new \CRM_Core_Transaction(TRUE);
         $this->tx->rollback();
     } else {
         $this->tx = NULL;
     }
 }
 /**
  * Test setValues() and getValues() methods with custom field YesNo(Boolean) Radio
  */
 public function testSetGetValuesYesNoRadio()
 {
     $contactID = $this->individualCreate();
     $customGroup = $this->customGroupCreate(array('is_multiple' => 1));
     //create Custom Field of type YesNo(Boolean) Radio
     $fields = array('custom_group_id' => $customGroup['id'], 'data_type' => 'Boolean', 'html_type' => 'Radio', 'default_value' => '');
     $customField = $this->customFieldCreate($fields);
     // Retrieve the field ID for sample custom field 'test_Boolean'
     $params = array('label' => 'test_Boolean');
     $field = array();
     //get field Id
     CRM_Core_BAO_CustomField::retrieve($params, $field);
     $fieldID = $customField['id'];
     // valid boolean value '1' for Boolean Radio
     $yesNo = '1';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $yesNo);
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     $this->assertEquals($result['is_error'], 0, 'Verify that is_error = 0 (success).');
     // Check that the YesNo radio value is stored
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['is_error'], 0, 'Verify that is_error = 0 (success).');
     $this->assertEquals($values["custom_{$fieldID}_1"], $yesNo, 'Verify that the boolean value is stored for contact ' . $contactID);
     // Now set YesNo radio to an invalid boolean value and try to reset
     $badYesNo = '20';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $badYesNo);
     CRM_Core_TemporaryErrorScope::useException();
     $message = NULL;
     try {
         CRM_Core_BAO_CustomValueTable::setValues($params);
     } catch (Exception $e) {
         $message = $e->getMessage();
     }
     $errorScope = NULL;
     // Check that an exception has been thrown
     $this->assertNotNull($message, 'Verify than an exception is thrown when bad boolean is passed');
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values["custom_{$fieldID}_1"], $yesNo, 'Verify that the date value has NOT been updated for contact ' . $contactID);
     // Cleanup
     $this->customFieldDelete($customField['id']);
     $this->customGroupDelete($customGroup['id']);
     $this->contactDelete($contactID);
 }
 /**
  *  Common setup functions for all unit tests.
  */
 protected function setUp()
 {
     $session = CRM_Core_Session::singleton();
     $session->set('userID', NULL);
     $this->errorScope = CRM_Core_TemporaryErrorScope::useException();
     // REVERT
     //  Use a temporary file for STDIN
     $GLOBALS['stdin'] = tmpfile();
     if ($GLOBALS['stdin'] === FALSE) {
         echo "Couldn't open temporary file\n";
         exit(1);
     }
     //  Get and save a connection to the database
     $this->_dbconn = $this->getConnection();
     // reload database before each test
     //        $this->_populateDB();
     // "initialize" CiviCRM to avoid problems when running single tests
     // FIXME: look at it closer in second stage
     $GLOBALS['civicrm_setting']['domain']['fatalErrorHandler'] = 'CiviUnitTestCase_fatalErrorHandler';
     $GLOBALS['civicrm_setting']['domain']['backtrace'] = 1;
     // disable any left-over test extensions
     CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
     // reset all the caches
     CRM_Utils_System::flushCache();
     // initialize the object once db is loaded
     \Civi::reset();
     $config = CRM_Core_Config::singleton(TRUE, TRUE);
     // ugh, performance
     // when running unit tests, use mockup user framework
     $this->hookClass = CRM_Utils_Hook::singleton();
     // Make sure the DB connection is setup properly
     $config->userSystem->setMySQLTimeZone();
     $env = new CRM_Utils_Check_Component_Env();
     CRM_Utils_Check::singleton()->assertValid($env->checkMysqlTime());
     // clear permissions stub to not check permissions
     $config->userPermissionClass->permissions = NULL;
     //flush component settings
     CRM_Core_Component::getEnabledComponents(TRUE);
     error_reporting(E_ALL);
     $this->_sethtmlGlobals();
 }
/**
 * Deletes an existing Tag
 *
 * @param  array  $params
 *
 * @return boolean | error  true if successfull, error otherwise
 * @access public
 */
function civicrm_tag_delete(&$params)
{
    _civicrm_initialize();
    $errorScope = CRM_Core_TemporaryErrorScope::useException();
    try {
        civicrm_verify_mandatory($params, NULL, array('tag_id'));
        $tagID = CRM_Utils_Array::value('tag_id', $params);
        require_once 'CRM/Core/BAO/Tag.php';
        return CRM_Core_BAO_Tag::del($tagID) ? civicrm_create_success() : civicrm_create_error(ts('Could not delete tag'));
    } catch (Exception $e) {
        if (CRM_Core_Error::$modeException) {
            throw $e;
        }
        return civicrm_create_error($e->getMessage());
    }
}
Example #11
0
function smarty_function_crmSQL($params, &$smarty) { 
    $is_error = 0;
    $error = "";
    $values = "";
    $sql="";

    if (!array_key_exists('sql', $params) && !array_key_exists('file', $params) && !array_key_exists('json', $params)) { 
        $smarty->trigger_error("assign: missing 'sql', 'json' OR 'file' parameter"); 
        $error = "crmAPI: missing 'sql', 'json' or 'file' parameter"; 
        $is_error = 1;
    } 

    $parameters = array();

    if(array_key_exists('json', $params)){
        $json=json_decode(file_get_contents('queries/'.$params["json"].".json", true));//file_get_contents('queries/'.$params["json"].".json", true)
        $sql=$json->{"query"};
        foreach ($json->{"params"} as $key => $value) {
            $var=intval($key);
            $name=$value->{"name"};
            $type=$value->{"type"};
            if(array_key_exists($name, $params)){
                $parameters[$var] = array($params[$name],$type);
            }
        }
    }

    else if(array_key_exists('sql', $params)){
        $sql = $params["sql"];
    }

    else if(array_key_exists('file', $params)){
        $sql = file_get_contents('queries/'.$params["file"].".sql", true);
    }

    $forbidden=array("delete ", "drop ","update ","grant ");
    foreach ($forbidden as $check) {
        if(strpos(strtolower($sql), $check)!==false){
            $smarty->trigger_error($check."command not allowed");
            $error = "crmAPI: you can not ".$check."using crmSQL";
            $is_error = 1;
            break;
        }
    }

    if (array_key_exists('debug', $params)) { 
        $smarty->trigger_error("sql:". $params["sql"]); 
    }

    try{
        if($is_error==0){
            $errorScope = CRM_Core_TemporaryErrorScope::useException();
            $dao = CRM_Core_DAO::executeQuery($sql,$parameters);
            $values = array();
            while ($dao->fetch()) {
                $values[] = $dao->toArray();
            }
        }
    }
    catch(Exception $e){
        $is_error=1;
        $error = "crmAPI: ".$e->getMessage();
        $values="";
    }

    if(array_key_exists('set', $params)){
        if($values!=""){
            //echo "console.log('string')";
            $smarty->assign($params['set'], $values);
        }
    }

    return json_encode(array("is_error"=>$is_error, "error"=>$error, "values" => $values), JSON_NUMERIC_CHECK);
}
 public function testDupesByParams()
 {
     // make dupe checks based on based on following contact sets:
     // FIRST - LAST - EMAIL
     // ---------------------------------
     // robin  - hood - robin@example.com
     // robin  - hood - hood@example.com
     // robin  - dale - robin@example.com
     // little - dale - dale@example.com
     // will   - dale - dale@example.com
     // will   - dale - will@example.com
     // will   - dale - will@example.com
     // contact data set
     // FIXME: move create params to separate function
     $params = array(array('first_name' => 'robin', 'last_name' => 'hood', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'robin', 'last_name' => 'hood', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'robin', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'little', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'will', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'will', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'), array('first_name' => 'will', 'last_name' => 'dale', 'email' => '*****@*****.**', 'contact_type' => 'Individual'));
     $count = 1;
     // TODO: This is not an API test!!
     foreach ($params as $param) {
         $param['version'] = 3;
         $contact = civicrm_api('contact', 'create', $param);
         $params = array('contact_id' => $contact['id'], 'street_address' => 'Ambachtstraat 23', 'location_type_id' => 1, 'version' => 3);
         $result = civicrm_api('address', 'create', $params);
         $contactIds[$count++] = $contact['id'];
     }
     // verify that all contacts have been created separately
     $this->assertEquals(count($contactIds), 7, 'Check for number of contacts.');
     $dao = new CRM_Dedupe_DAO_RuleGroup();
     $dao->contact_type = 'Individual';
     $dao->used = 'General';
     $dao->is_default = 1;
     $dao->find(TRUE);
     $fields = array('first_name' => 'robin', 'last_name' => 'hood', 'email' => '*****@*****.**', 'street_address' => 'Ambachtstraat 23');
     $errorScope = CRM_Core_TemporaryErrorScope::useException();
     $dedupeParams = CRM_Dedupe_Finder::formatParams($fields, 'Individual');
     $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'General');
     // Check with default Individual-General rule
     $this->assertEquals(count($ids), 2, 'Check Individual-General rule for dupesByParams().');
     // delete all created contacts
     foreach ($contactIds as $contactId) {
         Contact::delete($contactId);
     }
 }
 function postProcess()
 {
     $errorScope = CRM_Core_TemporaryErrorScope::useException();
     if (isset($this->_id)) {
         try {
             $transaction = new CRM_Core_Transaction();
             $sql = "UPDATE civicrm_wci_progress_bar SET name = %1,\n          starting_amount = %2, goal_amount = %3 where id = %4";
             CRM_Core_DAO::executeQuery($sql, array(1 => array($_REQUEST['progressbar_name'], 'String'), 2 => array($_REQUEST['starting_amount'], 'Float'), 3 => array($_REQUEST['goal_amount'], 'Float'), 4 => array($this->_id, 'Integer')));
             /** Delete existiing formula fields and add fields fresh*/
             CRM_Core_DAO::executeQuery('DELETE FROM civicrm_wci_progress_bar_formula
         WHERE progress_bar_id=%1', array(1 => array($this->_id, 'Integer')));
             $elem_added = 0;
             for ($i = 1; $elem_added < (int) $_REQUEST['contrib_count']; $i++) {
                 if (!isset($_REQUEST['contribution_page_' . (string) $i])) {
                     continue;
                 }
                 $page = 'contribution_page_' . (string) $i;
                 $type = 'financial_type_' . (string) $i;
                 $perc = 'percentage_' . (string) $i;
                 $sdate = 'contribution_start_date_' . (string) $i;
                 $edate = 'contribution_end_date_' . (string) $i;
                 $sql = "INSERT INTO civicrm_wci_progress_bar_formula\n            (contribution_page_id, financial_type_id, progress_bar_id, start_date, end_date, percentage)\n            VALUES (%1, %2, %3, %4, %5, %6)";
                 $start = NULL;
                 $end = NULL;
                 if (!empty($_REQUEST[$sdate])) {
                     $start = CRM_Utils_Date::processDate($_REQUEST[$sdate], NULL, FALSE, "Ymd");
                 }
                 if (!empty($_REQUEST[$edate])) {
                     $end = CRM_Utils_Date::processDate($_REQUEST[$edate], NULL, FALSE, "Ymd");
                 }
                 CRM_Core_DAO::executeQuery($sql, array(1 => array($_REQUEST[$page], 'Integer'), 2 => array($_REQUEST[$type], 'Integer'), 3 => array($this->_id, 'Integer'), 4 => array($start, 'Date'), 5 => array($end, 'Date'), 6 => array($_REQUEST[$perc], 'Float')));
                 $elem_added++;
             }
             $transaction->commit();
             CRM_Wci_BAO_WidgetCache::deleteWidgetCacheByProgressbar($this->_id);
             CRM_Core_Session::setStatus(ts('Progress bar created successfully'), '', 'success');
             CRM_Utils_System::redirect('progress-bar?reset=1');
         } catch (Exception $e) {
             CRM_Core_Session::setStatus(ts('Failed to create progress bar'), '', 'error');
             $transaction->rollback();
         }
     } else {
         $sql = "INSERT INTO civicrm_wci_progress_bar\n              (name, starting_amount, goal_amount) VALUES (%1, %2, %3)";
         try {
             $transaction = new CRM_Core_Transaction();
             CRM_Core_DAO::executeQuery($sql, array(1 => array($_REQUEST['progressbar_name'], 'String'), 2 => array($_REQUEST['starting_amount'], 'Float'), 3 => array($_REQUEST['goal_amount'], 'Float')));
             $progressbar_id = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()');
             for ($i = 1; $i <= (int) $_REQUEST['contrib_count']; $i++) {
                 $page = 'contribution_page_' . (string) $i;
                 $type = 'financial_type_' . (string) $i;
                 $perc = 'percentage_' . (string) $i;
                 $sdate = 'contribution_start_date_' . (string) $i;
                 $edate = 'contribution_end_date_' . (string) $i;
                 $sql = "INSERT INTO civicrm_wci_progress_bar_formula\n            (contribution_page_id, financial_type_id, progress_bar_id, start_date, end_date, percentage)\n            VALUES (%1, %2, %3, %4, %5, %6)";
                 $start = NULL;
                 $end = NULL;
                 if (!empty($_REQUEST[$sdate])) {
                     $start = CRM_Utils_Date::processDate($_REQUEST[$sdate], NULL, FALSE, "Ymd");
                 }
                 if (!empty($_REQUEST[$edate])) {
                     $end = CRM_Utils_Date::processDate($_REQUEST[$edate], NULL, FALSE, "Ymd");
                 }
                 CRM_Core_DAO::executeQuery($sql, array(1 => array($_REQUEST[$page], 'Integer'), 2 => array($_REQUEST[$type], 'Integer'), 3 => array($progressbar_id, 'Integer'), 4 => array($start, 'Date'), 5 => array($end, 'Date'), 6 => array($_REQUEST[$perc], 'Float')));
             }
             $transaction->commit();
             CRM_Utils_System::redirect('civicrm/wci/progress-bar?reset=1');
         } catch (Exception $e) {
             CRM_Core_Session::setStatus(ts('Failed to create Progress bar. ') . $e->getMessage(), '', 'error');
             $transaction->rollback();
         }
         $elem = $this->getElement('contrib_count');
         $elem->setValue('1');
     }
     parent::postProcess();
 }
Example #14
0
 /**
  * Immediately run all tasks in a queue (until either reaching the end
  * of the queue or encountering an error)
  *
  * If the runner has an onEndUrl, then this function will not return
  *
  * @return mixed
  *   TRUE if all tasks complete normally; otherwise, an array describing the
  *   failed task
  */
 public function runAll()
 {
     $taskResult = $this->formatTaskResult(TRUE);
     while ($taskResult['is_continue']) {
         // setRaiseException should't be necessary here, but there's a bug
         // somewhere which causes this setting to be lost.  Observed while
         // upgrading 4.0=>4.2.  This preference really shouldn't be a global
         // setting -- it should be more of a contextual/stack-based setting.
         // This should be appropriate because queue-runners are not used with
         // basic web pages -- they're used with CLI/REST/AJAX.
         $errorScope = CRM_Core_TemporaryErrorScope::useException();
         $taskResult = $this->runNext();
         $errorScope = NULL;
     }
     if ($taskResult['numberOfItems'] == 0) {
         $result = $this->handleEnd();
         if (!empty($result['redirect_url'])) {
             CRM_Utils_System::redirect($result['redirect_url']);
         }
         return TRUE;
     } else {
         return $taskResult;
     }
 }
function civicrm_api($entity, $action, $params, $extra = NULL)
{
    $apiWrappers = array(CRM_Core_HTMLInputCoder::singleton());
    try {
        require_once 'api/v3/utils.php';
        require_once 'api/Exception.php';
        if (!is_array($params)) {
            throw new API_Exception('Input variable `params` is not an array', 2000);
        }
        _civicrm_api3_initialize();
        $errorScope = CRM_Core_TemporaryErrorScope::useException();
        require_once 'CRM/Utils/String.php';
        require_once 'CRM/Utils/Array.php';
        $apiRequest = array();
        $apiRequest['entity'] = CRM_Utils_String::munge($entity);
        $apiRequest['action'] = CRM_Utils_String::munge($action);
        $apiRequest['version'] = civicrm_get_api_version($params);
        $apiRequest['params'] = $params;
        $apiRequest['extra'] = $extra;
        // look up function, file, is_generic
        $apiRequest += _civicrm_api_resolve($apiRequest);
        if (strtolower($action) == 'create' || strtolower($action) == 'delete') {
            $apiRequest['is_transactional'] = 1;
            $tx = new CRM_Core_Transaction();
        }
        $errorFnName = $apiRequest['version'] == 2 ? 'civicrm_create_error' : 'civicrm_api3_create_error';
        if ($apiRequest['version'] > 2) {
            _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
        }
        // we do this before we
        _civicrm_api3_swap_out_aliases($apiRequest);
        if (strtolower($action) != 'getfields') {
            if (!CRM_Utils_Array::value('id', $params)) {
                $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest), $apiRequest['params']);
            }
            //if 'id' is set then only 'version' will be checked but should still be checked for consistency
            civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest));
        }
        foreach ($apiWrappers as $apiWrapper) {
            $apiRequest = $apiWrapper->fromApiInput($apiRequest);
        }
        $function = $apiRequest['function'];
        if ($apiRequest['function'] && $apiRequest['is_generic']) {
            // Unlike normal API implementations, generic implementations require explicit
            // knowledge of the entity and action (as well as $params). Bundle up these bits
            // into a convenient data structure.
            $result = $function($apiRequest);
        } elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
            _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
            $result = isset($extra) ? $function($apiRequest['params'], $extra) : $function($apiRequest['params']);
        } else {
            return $errorFnName("API (" . $apiRequest['entity'] . "," . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
        }
        foreach ($apiWrappers as $apiWrapper) {
            $result = $apiWrapper->toApiOutput($apiRequest, $result);
        }
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            if ($result['is_error'] === 0) {
                return 1;
            } else {
                return 0;
            }
        }
        if (CRM_Utils_Array::value('format.only_id', $apiRequest['params']) && isset($result['id'])) {
            return $result['id'];
        }
        if (CRM_Utils_Array::value('is_error', $result, 0) == 0) {
            _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
        }
        if (CRM_Utils_Array::value('format.smarty', $apiRequest['params']) || CRM_Utils_Array::value('format_smarty', $apiRequest['params'])) {
            // return _civicrm_api_parse_result_through_smarty($result,$apiRequest['params']);
        }
        if (function_exists('xdebug_time_index') && CRM_Utils_Array::value('debug', $apiRequest['params']) && is_array($result)) {
            $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
            $result['xdebug']['memory'] = xdebug_memory_usage();
            $result['xdebug']['timeIndex'] = xdebug_time_index();
        }
        return $result;
    } catch (PEAR_Exception $e) {
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            return 0;
        }
        $data = array();
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
        if (CRM_Utils_Array::value('debug', $apiRequest['params'])) {
            $err['trace'] = $e->getTraceSafe();
        } else {
            $err['tip'] = "add debug=1 to your API call to have more info about the error";
        }
        if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
            $tx->rollback();
        }
        return $err;
    } catch (API_Exception $e) {
        if (!isset($apiRequest)) {
            $apiRequest = array();
        }
        if (CRM_Utils_Array::value('format.is_success', CRM_Utils_Array::value('params', $apiRequest)) == 1) {
            return 0;
        }
        $data = $e->getExtraParams();
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
        if (CRM_Utils_Array::value('debug', CRM_Utils_Array::value('params', $apiRequest))) {
            $err['trace'] = $e->getTraceAsString();
        }
        if (CRM_Utils_Array::value('is_transactional', CRM_Utils_Array::value('params', $apiRequest))) {
            $tx->rollback();
        }
        return $err;
    } catch (Exception $e) {
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            return 0;
        }
        $data = array();
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
        if (CRM_Utils_Array::value('debug', $apiRequest['params'])) {
            $err['trace'] = $e->getTraceAsString();
        }
        if (CRM_Utils_Array::value('is_transactional', $apiRequest)) {
            $tx->rollback();
        }
        return $err;
    }
}
Example #16
0
 function postProcess()
 {
     $values = $this->exportValues();
     $override = 0;
     $hide_title = 0;
     $hide_border = 0;
     $hide_pbcap = 0;
     $cust_tmpl = "";
     $cust_tmpl_col = "";
     $sql = "";
     $coma = "";
     $equals = "";
     $quote = "";
     /** If override check is checked state then only save the custom_template to the
             database. otherwise wci uses default tpl file.
         */
     if (isset($values['override'])) {
         $override = $values['override'];
         $cust_tmpl = str_replace("'", "''", $values['custom_template']);
         $cust_tmpl_col = "custom_template";
         $coma = ",";
         $equals = " = ";
         $quote = "'";
     }
     if (isset($values['hide_title'])) {
         $hide_title = $values['hide_title'];
     }
     if (isset($values['hide_border'])) {
         $hide_border = $values['hide_border'];
     }
     if (isset($values['hide_pbcap'])) {
         $hide_pbcap = $values['hide_pbcap'];
     }
     $title = str_replace("'", "''", $values['title']);
     $params = array(1 => array($title, 'String'), 2 => array($values['logo_image'], 'String'), 3 => array($values['image'], 'String'), 4 => array($values['button_title'], 'String'), 5 => array($values['button_link_to'], 'String'), 6 => array($values['progress_bar'], 'Integer'), 7 => array(str_replace("'", "''", $values['description']), 'String'), 8 => array($values['email_signup_group_id'], 'String'), 9 => array($values['size_variant'], 'String'), 10 => array($values['color_title'], 'String'), 11 => array($values['color_title_bg'], 'String'), 12 => array($values['color_bar'], 'String'), 13 => array($values['color_bar_bg'], 'String'), 14 => array($values['color_widget_bg'], 'String'), 15 => array($values['color_description'], 'String'), 16 => array($values['color_border'], 'String'), 17 => array($values['color_button'], 'String'), 18 => array($values['color_button_bg'], 'String'), 19 => array($hide_title, 'Integer'), 20 => array($hide_border, 'Integer'), 21 => array($hide_pbcap, 'Integer'), 22 => array($values['color_btn_newsletter'], 'String'), 23 => array($values['color_btn_newsletter_bg'], 'String'), 24 => array($values['newsletter_text'], 'String'), 25 => array($values['color_newsletter_text'], 'String'), 26 => array($values['style_rules'], 'String'), 27 => array($override, 'Integer'), 28 => array($values['custom_template'], 'String'), 29 => array($values['show_pb_perc'], 'Integer'));
     if (isset($this->_id)) {
         $sql = "UPDATE civicrm_wci_widget SET title = %1, logo_image =%2,\n      image = %3, button_title =%4, button_link_to =%5,\n      progress_bar_id = %6, description = %7, email_signup_group_id = %8,\n      size_variant = %9, color_title = %10, color_title_bg = %11,\n      color_progress_bar = %12, color_progress_bar_bg = %13,\n      color_widget_bg=%14, color_description=%15, color_border = %16,\n      color_button = %17, color_button_bg = %18, hide_title = %19,\n      hide_border = %20, hide_pbcap = %21, color_btn_newsletter = %22,\n      color_btn_newsletter_bg = %23, newsletter_text = %24,\n      color_newsletter_text = %25, style_rules = %26, override = %27,\n      custom_template = %28, show_pb_perc = %29 where id = %30";
         $params += array(30 => array($this->_id, 'Integer'));
     } else {
         $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      VALUES (%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13,\n      %14, %15, %16, %17, %18, %19, %20, %21, %22, %23, %24, %25, %26, %27, %28, %29)";
     }
     $errorScope = CRM_Core_TemporaryErrorScope::useException();
     try {
         $transaction = new CRM_Core_Transaction();
         CRM_Core_DAO::executeQuery("SET foreign_key_checks = 0;");
         CRM_Core_DAO::executeQuery($sql, $params);
         CRM_Core_DAO::executeQuery("SET foreign_key_checks = 1;");
         $transaction->commit();
         if (isset($this->_id)) {
             $widget_id = $this->_id;
             CRM_Wci_BAO_WidgetCache::deleteWidgetCache($widget_id);
         } else {
             $widget_id = CRM_Core_DAO::singleValueQuery('SELECT LAST_INSERT_ID()');
         }
         CRM_Core_Session::setStatus(ts('Widget created successfully'), '', 'success');
         if (isset($_REQUEST['_qf_CreateWidget_next'])) {
             CRM_Utils_System::redirect('?action=update&reset=1&id=' . $widget_id);
         } else {
             CRM_Utils_System::redirect('widget?reset=1');
         }
     } catch (Exception $e) {
         CRM_Core_Session::setStatus(ts('Failed to create widget. ') . $e->getMessage(), '', 'error');
         $transaction->rollback();
     }
     parent::postProcess();
 }
Example #17
0
 /**
  * Execute an API request.
  *
  * The request must be in canonical format. Exceptions will be propagated out.
  *
  * @param $apiRequest
  * @return array
  * @throws \API_Exception
  * @throws \Civi\API\Exception\NotImplementedException
  * @throws \Civi\API\Exception\UnauthorizedException
  */
 public function runRequest($apiRequest)
 {
     $this->boot($apiRequest);
     $errorScope = \CRM_Core_TemporaryErrorScope::useException();
     list($apiProvider, $apiRequest) = $this->resolve($apiRequest);
     $this->authorize($apiProvider, $apiRequest);
     $apiRequest = $this->prepare($apiProvider, $apiRequest);
     $result = $apiProvider->invoke($apiRequest);
     return $this->respond($apiProvider, $apiRequest, $result);
 }
Example #18
0
/**
 * @param string $entity
 *   type of entities to deal with
 * @param string $action
 *   create, get, delete or some special action name.
 * @param array $params
 *   array to be passed to function
 * @param null $extra
 *
 * @return array|int
 */
function civicrm_api($entity, $action, $params, $extra = NULL)
{
    $apiRequest = array();
    $apiRequest['entity'] = CRM_Utils_String::munge($entity);
    $apiRequest['action'] = CRM_Utils_String::munge($action);
    $apiRequest['version'] = civicrm_get_api_version($params);
    $apiRequest['params'] = $params;
    $apiRequest['extra'] = $extra;
    $apiWrappers = array(CRM_Utils_API_HTMLInputCoder::singleton(), CRM_Utils_API_NullOutputCoder::singleton(), CRM_Utils_API_ReloadOption::singleton(), CRM_Utils_API_MatchOption::singleton());
    CRM_Utils_Hook::apiWrappers($apiWrappers, $apiRequest);
    try {
        require_once 'api/v3/utils.php';
        require_once 'api/Exception.php';
        if (!is_array($params)) {
            throw new API_Exception('Input variable `params` is not an array', 2000);
        }
        _civicrm_api3_initialize();
        $errorScope = CRM_Core_TemporaryErrorScope::useException();
        // look up function, file, is_generic
        $apiRequest += _civicrm_api_resolve($apiRequest);
        if (strtolower($action) == 'create' || strtolower($action) == 'delete' || strtolower($action) == 'submit') {
            $apiRequest['is_transactional'] = 1;
            $transaction = new CRM_Core_Transaction();
        }
        // support multi-lingual requests
        if ($language = CRM_Utils_Array::value('option.language', $params)) {
            _civicrm_api_set_locale($language);
        }
        _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']);
        $fields = _civicrm_api3_api_getfields($apiRequest);
        // we do this before we
        _civicrm_api3_swap_out_aliases($apiRequest, $fields);
        if (strtolower($action) != 'getfields') {
            if (empty($apiRequest['params']['id'])) {
                $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest, $fields), $apiRequest['params']);
            }
            //if 'id' is set then only 'version' will be checked but should still be checked for consistency
            civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest, $fields));
        }
        // For input filtering, process $apiWrappers in forward order
        foreach ($apiWrappers as $apiWrapper) {
            $apiRequest = $apiWrapper->fromApiInput($apiRequest);
        }
        $function = $apiRequest['function'];
        if ($apiRequest['function'] && $apiRequest['is_generic']) {
            // Unlike normal API implementations, generic implementations require explicit
            // knowledge of the entity and action (as well as $params). Bundle up these bits
            // into a convenient data structure.
            $result = $function($apiRequest);
        } elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
            _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields);
            $result = isset($extra) ? $function($apiRequest['params'], $extra) : $function($apiRequest['params']);
        } else {
            return civicrm_api3_create_error("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)");
        }
        // For output filtering, process $apiWrappers in reverse order
        foreach (array_reverse($apiWrappers) as $apiWrapper) {
            $result = $apiWrapper->toApiOutput($apiRequest, $result);
        }
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            if ($result['is_error'] === 0) {
                return 1;
            } else {
                return 0;
            }
        }
        if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) {
            return $result['id'];
        }
        if (CRM_Utils_Array::value('is_error', $result, 0) == 0) {
            _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']);
        }
        if (function_exists('xdebug_time_index') && CRM_Utils_Array::value('debug', $apiRequest['params']) && is_array($result)) {
            $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage();
            $result['xdebug']['memory'] = xdebug_memory_usage();
            $result['xdebug']['timeIndex'] = xdebug_time_index();
        }
        return $result;
    } catch (PEAR_Exception $e) {
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            return 0;
        }
        $error = $e->getCause();
        if ($error instanceof DB_Error) {
            $data["error_code"] = DB::errorMessage($error->getCode());
            $data["sql"] = $error->getDebugInfo();
        }
        if (!empty($apiRequest['params']['debug'])) {
            if (method_exists($e, 'getUserInfo')) {
                $data['debug_info'] = $error->getUserInfo();
            }
            if (method_exists($e, 'getExtraData')) {
                $data['debug_info'] = $data + $error->getExtraData();
            }
            $data['trace'] = $e->getTraceAsString();
        } else {
            $data['tip'] = "add debug=1 to your API call to have more info about the error";
        }
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest);
        if (!empty($apiRequest['is_transactional'])) {
            $transaction->rollback();
        }
        return $err;
    } catch (API_Exception $e) {
        if (!isset($apiRequest)) {
            $apiRequest = array();
        }
        if (CRM_Utils_Array::value('format.is_success', CRM_Utils_Array::value('params', $apiRequest)) == 1) {
            return 0;
        }
        $data = $e->getExtraParams();
        $data['entity'] = CRM_Utils_Array::value('entity', $apiRequest);
        $data['action'] = CRM_Utils_Array::value('action', $apiRequest);
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
        if (CRM_Utils_Array::value('debug', CRM_Utils_Array::value('params', $apiRequest)) && empty($data['trace'])) {
            $err['trace'] = $e->getTraceAsString();
        }
        if (!empty($apiRequest['is_transactional'])) {
            $transaction->rollback();
        }
        return $err;
    } catch (Exception $e) {
        if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) {
            return 0;
        }
        $data = array();
        $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode());
        if (!empty($apiRequest['params']['debug'])) {
            $err['trace'] = $e->getTraceAsString();
        }
        if (!empty($apiRequest['is_transactional'])) {
            $transaction->rollback();
        }
        return $err;
    }
}
 /**
  *  Common setup functions for all unit tests
  */
 protected function setUp()
 {
     CRM_Utils_Hook::singleton(TRUE);
     $this->errorScope = CRM_Core_TemporaryErrorScope::useException();
     // REVERT
     //  Use a temporary file for STDIN
     $GLOBALS['stdin'] = tmpfile();
     if ($GLOBALS['stdin'] === FALSE) {
         echo "Couldn't open temporary file\n";
         exit(1);
     }
     //  Get and save a connection to the database
     $this->_dbconn = $this->getConnection();
     // reload database before each test
     //        $this->_populateDB();
     // "initialize" CiviCRM to avoid problems when running single tests
     // FIXME: look at it closer in second stage
     // initialize the object once db is loaded
     CRM_Core_Config::$_mail = NULL;
     $config = CRM_Core_Config::singleton();
     // when running unit tests, use mockup user framework
     $config->setUserFramework('UnitTests');
     // also fix the fatal error handler to throw exceptions,
     // rather than exit
     $config->fatalErrorHandler = 'CiviUnitTestCase_fatalErrorHandler';
     // enable backtrace to get meaningful errors
     $config->backtrace = 1;
     // disable any left-over test extensions
     CRM_Core_DAO::executeQuery('DELETE FROM civicrm_extension WHERE full_name LIKE "test.%"');
     // reset all the caches
     CRM_Utils_System::flushCache();
     // clear permissions stub to not check permissions
     $config = CRM_Core_Config::singleton();
     $config->userPermissionClass->permissions = NULL;
     //flush component settings
     CRM_Core_Component::getEnabledComponents(TRUE);
     if ($this->_eNoticeCompliant) {
         error_reporting(E_ALL);
     } else {
         error_reporting(E_ALL & ~E_NOTICE);
     }
     $this->_sethtmlGlobals();
 }
 /**
  * Move a custom field from $groupA to $groupB. Make sure that data records are
  * correctly matched and created.
  */
 public function testMoveField()
 {
     $countriesByName = array_flip(CRM_Core_PseudoConstant::country(FALSE, FALSE));
     $this->assertTrue($countriesByName['ANDORRA'] > 0);
     $groups = array('A' => Custom::createGroup(array('title' => 'Test_Group A', 'name' => 'test_group_a', 'extends' => array('Individual'), 'style' => 'Inline', 'is_multiple' => 0, 'is_active' => 1, 'version' => 3)), 'B' => Custom::createGroup(array('title' => 'Test_Group B', 'name' => 'test_group_b', 'extends' => array('Individual'), 'style' => 'Inline', 'is_multiple' => 0, 'is_active' => 1, 'version' => 3)));
     $fields = array('countryA' => Custom::createField(array(), array('groupId' => $groups['A']->id, 'label' => 'Country A', 'dataType' => 'Country', 'htmlType' => 'Select Country')), 'countryB' => Custom::createField(array(), array('groupId' => $groups['A']->id, 'label' => 'Country B', 'dataType' => 'Country', 'htmlType' => 'Select Country')), 'countryC' => Custom::createField(array(), array('groupId' => $groups['B']->id, 'label' => 'Country C', 'dataType' => 'Country', 'htmlType' => 'Select Country')));
     $contacts = array('alice' => Contact::createIndividual(array('first_name' => 'Alice', 'last_name' => 'Albertson', 'custom_' . $fields['countryA']->id => $countriesByName['ANDORRA'], 'custom_' . $fields['countryB']->id => $countriesByName['BARBADOS'])), 'bob' => Contact::createIndividual(array('first_name' => 'Bob', 'last_name' => 'Roberts', 'custom_' . $fields['countryA']->id => $countriesByName['AUSTRIA'], 'custom_' . $fields['countryB']->id => $countriesByName['BERMUDA'], 'custom_' . $fields['countryC']->id => $countriesByName['CHAD'])), 'carol' => Contact::createIndividual(array('first_name' => 'Carol', 'last_name' => 'Carolson', 'custom_' . $fields['countryC']->id => $countriesByName['CAMBODIA'])));
     // Move!
     CRM_Core_BAO_CustomField::moveField($fields['countryB']->id, $groups['B']->id);
     // Group[A] no longer has fields[countryB]
     $errorScope = CRM_Core_TemporaryErrorScope::useException();
     try {
         $this->assertDBQuery(1, "SELECT {$fields['countryB']->column_name} FROM {$groups['A']->table_name}");
         $this->fail('Expected exception when querying column on wrong table');
     } catch (PEAR_Exception $e) {
     }
     $errorScope = NULL;
     // Alice: Group[B] has fields[countryB], but fields[countryC] did not exist before
     $this->assertDBQuery(1, "SELECT count(*) FROM {$groups['B']->table_name}\n            WHERE entity_id = %1\n            AND {$fields['countryB']->column_name} = %3\n            AND {$fields['countryC']->column_name} is null", array(1 => array($contacts['alice'], 'Integer'), 3 => array($countriesByName['BARBADOS'], 'Integer')));
     // Bob: Group[B] has merged fields[countryB] and fields[countryC] on the same record
     $this->assertDBQuery(1, "SELECT count(*) FROM {$groups['B']->table_name}\n            WHERE entity_id = %1\n            AND {$fields['countryB']->column_name} = %3\n            AND {$fields['countryC']->column_name} = %4", array(1 => array($contacts['bob'], 'Integer'), 3 => array($countriesByName['BERMUDA'], 'Integer'), 4 => array($countriesByName['CHAD'], 'Integer')));
     // Carol: Group[B] still has fields[countryC] but did not get fields[countryB]
     $this->assertDBQuery(1, "SELECT count(*) FROM {$groups['B']->table_name}\n            WHERE entity_id = %1\n            AND {$fields['countryB']->column_name} is null\n            AND {$fields['countryC']->column_name} = %4", array(1 => array($contacts['carol'], 'Integer'), 4 => array($countriesByName['CAMBODIA'], 'Integer')));
     Custom::deleteGroup($groups['A']);
     Custom::deleteGroup($groups['B']);
 }
/**
 * Function to update relationship
 *
 * @param  array $params   Associative array of property name/value pairs to update the relationship
 *
 * @return array Array with relationship information
 *
 * @access public
 *
 */
function civicrm_relationship_update($params)
{
    try {
        _civicrm_initialize();
        $errorScope = CRM_Core_TemporaryErrorScope::useException();
        /*
         * Erik Hommel, 5 Oct 2010 : fix for CRM-6895
         * check if required field relationship_id is in the parms. As the
         * CRM_Contact_BAO_Relationship::getRelatonship throws up some issues
         * (CRM-6905) the relationship is retrieved with a direct query
         */
        civicrm_verify_mandatory($params, 'CRM_Contact_DAO_Relationship', array('relationship_id'));
        $names = array('id', 'contact_id_a', 'contact_id_b', 'relationship_type_id', 'start_date', 'end_date', 'is_active', 'description', 'is_permission_a_b', 'is_permission_b_a', 'case_id');
        $relationship_id = (int) $params['relationship_id'];
        $query = "SELECT * FROM civicrm_relationship WHERE id = {$relationship_id}";
        $daoRelations = CRM_Core_DAO::executeQuery($query);
        while ($daoRelations->fetch()) {
            foreach ($names as $name) {
                $current_values[$name] = $daoRelations->{$name};
            }
        }
        $params = array_merge($current_values, $params);
        $params['start_date'] = date("Ymd", strtotime($params['start_date']));
        $params['end_date'] = date("Ymd", strtotime($params['end_date']));
        return civicrm_relationship_create($params);
    } catch (PEAR_Exception $e) {
        return civicrm_create_error($e->getMessage());
    } catch (Exception $e) {
        return civicrm_create_error($e->getMessage());
    }
}
 /**
  * Move a custom field from $groupA to $groupB.
  *
  * Make sure that data records are correctly matched and created.
  */
 public function testMoveField()
 {
     $countriesByName = array_flip(CRM_Core_PseudoConstant::country(FALSE, FALSE));
     $this->assertTrue($countriesByName['Andorra'] > 0);
     $groups = array('A' => $this->customGroupCreate(array('title' => 'Test_Group A', 'name' => 'test_group_a', 'extends' => array('Individual'), 'style' => 'Inline', 'is_multiple' => 0, 'is_active' => 1, 'version' => 3)), 'B' => $this->customGroupCreate(array('title' => 'Test_Group B', 'name' => 'test_group_b', 'extends' => array('Individual'), 'style' => 'Inline', 'is_multiple' => 0, 'is_active' => 1, 'version' => 3)));
     $groupA = $groups['A']['values'][$groups['A']['id']];
     $groupB = $groups['B']['values'][$groups['B']['id']];
     $countryA = $this->customFieldCreate(array('custom_group_id' => $groups['A']['id'], 'label' => 'Country A', 'dataType' => 'Country', 'htmlType' => 'Select Country', 'default_value' => NULL));
     $countryB = $this->customFieldCreate(array('custom_group_id' => $groups['A']['id'], 'label' => 'Country B', 'dataType' => 'Country', 'htmlType' => 'Select Country', 'default_value' => NULL));
     $countryC = $this->customFieldCreate(array('custom_group_id' => $groups['B']['id'], 'label' => 'Country C', 'dataType' => 'Country', 'htmlType' => 'Select Country', 'default_value' => NULL));
     $fields = array('countryA' => $countryA['values'][$countryA['id']], 'countryB' => $countryB['values'][$countryB['id']], 'countryC' => $countryC['values'][$countryC['id']]);
     $contacts = array('alice' => $this->individualCreate(array('first_name' => 'Alice', 'last_name' => 'Albertson', 'custom_' . $fields['countryA']['id'] => $countriesByName['Andorra'], 'custom_' . $fields['countryB']['id'] => $countriesByName['Barbados'])), 'bob' => $this->individualCreate(array('first_name' => 'Bob', 'last_name' => 'Roberts', 'custom_' . $fields['countryA']['id'] => $countriesByName['Austria'], 'custom_' . $fields['countryB']['id'] => $countriesByName['Bermuda'], 'custom_' . $fields['countryC']['id'] => $countriesByName['Chad'])), 'carol' => $this->individualCreate(array('first_name' => 'Carol', 'last_name' => 'Carolson', 'custom_' . $fields['countryC']['id'] => $countriesByName['Cambodia'])));
     // Move!
     CRM_Core_BAO_CustomField::moveField($fields['countryB']['id'], $groupB['id']);
     // Group[A] no longer has fields[countryB]
     $errorScope = CRM_Core_TemporaryErrorScope::useException();
     try {
         $this->assertDBQuery(1, "SELECT {$fields['countryB']['column_name']} FROM " . $groupA['table_name']);
         $this->fail('Expected exception when querying column on wrong table');
     } catch (PEAR_Exception $e) {
     }
     $errorScope = NULL;
     // Alice: Group[B] has fields[countryB], but fields[countryC] did not exist before
     $this->assertDBQuery(1, "SELECT count(*) FROM {$groupB['table_name']}\n            WHERE entity_id = %1\n            AND {$fields['countryB']['column_name']} = %3\n            AND {$fields['countryC']['column_name']} is null", array(1 => array($contacts['alice'], 'Integer'), 3 => array($countriesByName['Barbados'], 'Integer')));
     // Bob: Group[B] has merged fields[countryB] and fields[countryC] on the same record
     $this->assertDBQuery(1, "SELECT count(*) FROM {$groupB['table_name']}\n            WHERE entity_id = %1\n            AND {$fields['countryB']['column_name']} = %3\n            AND {$fields['countryC']['column_name']} = %4", array(1 => array($contacts['bob'], 'Integer'), 3 => array($countriesByName['Bermuda'], 'Integer'), 4 => array($countriesByName['Chad'], 'Integer')));
     // Carol: Group[B] still has fields[countryC] but did not get fields[countryB]
     $this->assertDBQuery(1, "SELECT count(*) FROM {$groupB['table_name']}\n            WHERE entity_id = %1\n            AND {$fields['countryB']['column_name']} is null\n            AND {$fields['countryC']['column_name']} = %4", array(1 => array($contacts['carol'], 'Integer'), 4 => array($countriesByName['Cambodia'], 'Integer')));
     $this->customGroupDelete($groups['A']['id']);
     $this->customGroupDelete($groupB['id']);
 }