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(); }
/** * @param $params * @param $smarty * @return string|void */ function smarty_function_crmAPI($params, &$smarty) { if (!array_key_exists('entity', $params)) { $smarty->trigger_error("assign: missing 'entity' parameter"); return "crmAPI: missing 'entity' parameter"; } $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); $entity = $params['entity']; $action = CRM_Utils_Array::value('action', $params, 'get'); $params['sequential'] = CRM_Utils_Array::value('sequential', $params, 1); $var = CRM_Utils_Array::value('var', $params); CRM_Utils_Array::remove($params, 'entity', 'action', 'var'); $params['version'] = 3; require_once 'api/api.php'; $result = civicrm_api($entity, $action, $params); unset($errorScope); if ($result === FALSE) { $smarty->trigger_error("Unknown error"); return; } if (!empty($result['is_error'])) { $smarty->trigger_error("{crmAPI} " . $result["error_message"]); } if (!$var) { return json_encode($result); } if (!empty($params['json'])) { $smarty->assign($var, json_encode($result)); } else { $smarty->assign($var, $result); } }
/** * 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()); } }
/** * @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()); } }
/** * Set variables up before form is built. */ public function preProcess() { //Test database user privilege to create table(Temporary) CRM-4725 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $daoTestPrivilege = new CRM_Core_DAO(); $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_one(test int) ENGINE=InnoDB"); $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_two(test int) ENGINE=InnoDB"); $daoTestPrivilege->query("DROP TEMPORARY TABLE IF EXISTS import_job_permission_one, import_job_permission_two"); unset($errorScope); if ($daoTestPrivilege->_lastError) { CRM_Core_Error::fatal(ts('Database Configuration Error: Insufficient permissions. Import requires that the CiviCRM database user has permission to create temporary tables. Contact your site administrator for assistance.')); } $results = array(); $config = CRM_Core_Config::singleton(); $handler = opendir($config->uploadDir); $errorFiles = array('sqlImport.errors', 'sqlImport.conflicts', 'sqlImport.duplicates', 'sqlImport.mismatch'); // check for post max size avoid when called twice $snippet = CRM_Utils_Array::value('snippet', $_GET, 0); if (empty($snippet)) { CRM_Utils_Number::formatUnitSize(ini_get('post_max_size'), TRUE); } while ($file = readdir($handler)) { if ($file != '.' && $file != '..' && in_array($file, $errorFiles) && !is_writable($config->uploadDir . $file)) { $results[] = $file; } } closedir($handler); if (!empty($results)) { CRM_Core_Error::fatal(ts('<b>%1</b> file(s) in %2 directory are not writable. Listed file(s) might be used during the import to log the errors occurred during Import process. Contact your site administrator for assistance.', array(1 => implode(', ', $results), 2 => $config->uploadDir))); } $this->_dataSourceIsValid = FALSE; $this->_dataSource = CRM_Utils_Request::retrieve('dataSource', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'); $this->_params = $this->controller->exportValues($this->_name); if (!$this->_dataSource) { //considering dataSource as base criteria instead of hidden_dataSource. $this->_dataSource = CRM_Utils_Array::value('dataSource', $_POST, CRM_Utils_Array::value('dataSource', $this->_params)); $this->assign('showOnlyDataSourceFormPane', FALSE); } else { $this->assign('showOnlyDataSourceFormPane', TRUE); } $dataSources = $this->_getDataSources(); if ($this->_dataSource && isset($dataSources[$this->_dataSource])) { $this->_dataSourceIsValid = TRUE; $this->assign('showDataSourceFormPane', TRUE); $dataSourcePath = explode('_', $this->_dataSource); $templateFile = "CRM/Contact/Import/Form/" . $dataSourcePath[3] . ".tpl"; $this->assign('dataSourceFormTemplateFile', $templateFile); } elseif ($this->_dataSource) { throw new \CRM_Core_Exception("Invalid data source"); } }
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; } }
/** * Retrieve CiviCRM settings from the api for use in templates. * * @param $params * @param $smarty * * @return int|string|null */ function smarty_function_crmSetting($params, &$smarty) { $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); unset($params['method']); unset($params['assign']); $params['version'] = 3; require_once 'api/api.php'; $result = civicrm_api('setting', 'getvalue', $params); unset($errorScope); if ($result === FALSE) { $smarty->trigger_error("Unknown error"); return NULL; } if (empty($params['var'])) { return is_numeric($result) ? $result : json_encode($result); } if (!empty($params['json'])) { $smarty->assign($params["var"], json_encode($result)); } else { $smarty->assign($params["var"], $result); } }
/** * Singleton function used to manage this object. * * @param bool $loadFromDB * whether to load from the database. * @param bool $force * whether to force a reconstruction. * * @return CRM_Core_Config */ public static function &singleton($loadFromDB = TRUE, $force = FALSE) { if (self::$_singleton === NULL || $force) { $GLOBALS['civicrm_default_error_scope'] = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'handle')); $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'simpleHandler')); if (defined('E_DEPRECATED')) { error_reporting(error_reporting() & ~E_DEPRECATED); } self::$_singleton = new CRM_Core_Config(); \Civi\Core\Container::boot($loadFromDB); if ($loadFromDB && self::$_singleton->dsn) { $domain = \CRM_Core_BAO_Domain::getDomain(); \CRM_Core_BAO_ConfigSetting::applyLocale(\Civi::settings($domain->id), $domain->locales); unset($errorScope); CRM_Utils_Hook::config(self::$_singleton); self::$_singleton->authenticate(); // Extreme backward compat: $config binds to active domain at moment of setup. self::$_singleton->getSettings(); Civi::service('settings_manager')->useDefaults(); } } return self::$_singleton; }
/** * Ask a contact for subscription confirmation (opt-in) * * @param string $email * The email address. * * @return void */ public function send_confirm_request($email) { $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $confirm = implode($config->verpSeparator, array($localpart . 'c', $this->contact_id, $this->id, $this->hash)) . "@{$emailDomain}"; $group = new CRM_Contact_BAO_Group(); $group->id = $this->group_id; $group->find(TRUE); $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Subscribe'; $component->find(TRUE); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'To' => $email, 'Reply-To' => $confirm, 'Return-Path' => "do-not-reply@{$emailDomain}"); $url = CRM_Utils_System::url('civicrm/mailing/confirm', "reset=1&cid={$this->contact_id}&sid={$this->id}&h={$this->hash}", TRUE); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceSubscribeTokens($html, $group->title, $url, TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceSubscribeTokens($text, $group->title, $url, FALSE); // render the & entities in text mode, so that the links work $text = str_replace('&', '&', $text); $message = new Mail_mime("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 's', $this->contact_id, $this->id, $this->hash); $mailer = \Civi::service('pear_mail'); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($email, $h, $b); unset($errorScope); } }
/** * 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']); }
/** * 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); }
/** * @param bool $view * @param bool $trigger * * @return bool */ public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) { // test for create view and trigger permissions and if allowed, add the option to go multilingual // and logging // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $dao = new CRM_Core_DAO(); if ($view) { $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain'); if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) { return FALSE; } } if ($trigger) { $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END'); if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) { if ($view) { $dao->query('DROP VIEW IF EXISTS civicrm_domain_view'); } return FALSE; } $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger'); if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) { if ($view) { $dao->query('DROP VIEW IF EXISTS civicrm_domain_view'); } return FALSE; } } if ($view) { $dao->query('DROP VIEW IF EXISTS civicrm_domain_view'); if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) { return FALSE; } } return TRUE; }
/** * Send a response email informing the contact of the groups from which he. * has been unsubscribed. * * @param string $queue_id * The queue event ID. * @param array $groups * List of group IDs. * @param bool $is_domain * Is this domain-level?. * @param int $job * The job ID. */ public static function send_unsub_response($queue_id, $groups, $is_domain = FALSE, $job) { $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); $jobObject = new CRM_Mailing_BAO_MailingJob(); $jobTable = $jobObject->getTableName(); $mailingObject = new CRM_Mailing_DAO_Mailing(); $mailingTable = $mailingObject->getTableName(); $contactsObject = new CRM_Contact_DAO_Contact(); $contacts = $contactsObject->getTableName(); $emailObject = new CRM_Core_DAO_Email(); $email = $emailObject->getTableName(); $queueObject = new CRM_Mailing_Event_BAO_Queue(); $queue = $queueObject->getTableName(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $dao = new CRM_Mailing_BAO_Mailing(); $dao->query(" SELECT * FROM {$mailingTable}\n INNER JOIN {$jobTable} ON\n {$jobTable}.mailing_id = {$mailingTable}.id\n WHERE {$jobTable}.id = {$job}"); $dao->fetch(); $component = new CRM_Mailing_BAO_Component(); if ($is_domain) { $component->id = $dao->optout_id; } else { $component->id = $dao->unsubscribe_id; } $component->find(TRUE); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$contacts}.id as contact_id,\n {$email}.email as email,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); if ($groups) { foreach ($groups as $key => $value) { if (!$value) { unset($groups[$key]); } } } $message = new Mail_mime("\n"); list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email); $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceUnsubscribeTokens($html, $domain, $groups, TRUE, $eq->contact_id, $eq->hash); $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, NULL, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceUnsubscribeTokens($text, $domain, $groups, FALSE, $eq->contact_id, $eq->hash); $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, NULL, $tokens['text']); $message->setTxtBody($text); } $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); CRM_Mailing_BAO_Mailing::addMessageIdHeader($headers, 'u', $job, $queue_id, $eq->hash); $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); $mailer = \Civi::service('pear_mail'); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($eq->email, $h, $b); unset($errorScope); } }
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); }
/** * Used during case component enablement and during ugprade */ static function createCaseViews() { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $dao = new CRM_Core_DAO(); $sql = self::createCaseViewsQuery('upcoming'); $dao->query($sql); if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) { return FALSE; } // Above error doesn't get caught? $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming"); if (is_null($doublecheck)) { return FALSE; } $sql = self::createCaseViewsQuery('recent'); $dao->query($sql); if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) { return FALSE; } // Above error doesn't get caught? $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent"); if (is_null($doublecheck)) { return FALSE; } return TRUE; }
/** * This is a wrapper so you can call an api via json (it returns json too) * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} to take all the emails from individuals * works for POST & GET (POST recommended) */ public static function ajaxJson() { $requestParams = CRM_Utils_Request::exportValues(); require_once 'api/v3/utils.php'; // Why is $config undefined -- $config = CRM_Core_Config::singleton(); if (!$config->debug && (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) || $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest")) { $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().", array('IP' => $_SERVER['REMOTE_ADDR'], 'level' => 'security', 'referer' => $_SERVER['HTTP_REFERER'], 'reason' => 'CSRF suspected')); CRM_Utils_JSON::output($error); } if (empty($requestParams['entity'])) { CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity param')); } if (empty($requestParams['entity'])) { CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity entity')); } if (!empty($requestParams['json'])) { $params = json_decode($requestParams['json'], TRUE); } $entity = CRM_Utils_String::munge(CRM_Utils_Array::value('entity', $requestParams)); $action = CRM_Utils_String::munge(CRM_Utils_Array::value('action', $requestParams)); if (!is_array($params)) { CRM_Utils_JSON::output(array('is_error' => 1, 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}')); } $params['check_permissions'] = TRUE; $params['version'] = 3; $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions if (!$params['sequential']) { $params['sequential'] = 1; } // trap all fatal errors $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); $result = civicrm_api($entity, $action, $params); unset($errorScope); echo self::output($result); CRM_Utils_System::civiExit(); }
/** * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter * is an associateive array which holds the values of field needed to send an email. These are: * * from : complete from envelope * toName : name of person to send email * toEmail : email address to send to * cc : email addresses to cc * bcc : email addresses to bcc * subject : subject of the email * text : text of the message * html : html version of the message * replyTo : reply-to header in the email * attachments: an associative array of * fullPath : complete pathname to the file * mime_type: mime type of the attachment * cleanName: the user friendly name of the attachmment * * @param array $params * (by reference). * * @return bool * TRUE if a mail was sent, else FALSE. */ public static function send(&$params) { $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath(); $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $from = CRM_Utils_Array::value('from', $params); if (!$returnPath) { $returnPath = self::pluckEmailFromHeader($from); } $params['returnPath'] = $returnPath; // first call the mail alter hook CRM_Utils_Hook::alterMailParams($params); // check if any module has aborted mail sending if (!empty($params['abortMailSend']) || empty($params['toEmail'])) { return FALSE; } $textMessage = CRM_Utils_Array::value('text', $params); $htmlMessage = CRM_Utils_Array::value('html', $params); $attachments = CRM_Utils_Array::value('attachments', $params); // CRM-6224 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') { $htmlMessage = FALSE; } $headers = array(); // CRM-10699 support custom email headers if (!empty($params['headers'])) { $headers = array_merge($headers, $params['headers']); } $headers['From'] = $params['from']; $headers['To'] = self::formatRFC822Email(CRM_Utils_Array::value('toName', $params), CRM_Utils_Array::value('toEmail', $params), FALSE); $headers['Cc'] = CRM_Utils_Array::value('cc', $params); $headers['Bcc'] = CRM_Utils_Array::value('bcc', $params); $headers['Subject'] = CRM_Utils_Array::value('subject', $params); $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8'; $headers['Content-Disposition'] = 'inline'; $headers['Content-Transfer-Encoding'] = '8bit'; $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params); // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers $replyTo = CRM_Utils_Array::value('replyTo', $params, CRM_Utils_Array::value('from', $params)); if (!empty($replyTo)) { $headers['Reply-To'] = $replyTo; } $headers['Date'] = date('r'); if ($includeMessageId) { $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@{$emailDomain}>"; } if (!empty($params['autoSubmitted'])) { $headers['Auto-Submitted'] = "Auto-Generated"; } // make sure we has to have space, CRM-6977 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) { if (isset($headers[$fld])) { $headers[$fld] = str_replace('"<', '" <', $headers[$fld]); } } // quote FROM, if comma is detected AND is not already quoted. CRM-7053 if (strpos($headers['From'], ',') !== FALSE) { $from = explode(' <', $headers['From']); $headers['From'] = self::formatRFC822Email($from[0], substr(trim($from[1]), 0, -1), TRUE); } require_once 'Mail/mime.php'; $msg = new Mail_mime("\n"); if ($textMessage) { $msg->setTxtBody($textMessage); } if ($htmlMessage) { $msg->setHTMLBody($htmlMessage); } if (!empty($attachments)) { foreach ($attachments as $fileID => $attach) { $msg->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']); } } $message = self::setMimeParams($msg); $headers =& $msg->headers($headers); $to = array($params['toEmail']); $result = NULL; $mailer = \Civi::service('pear_mail'); // Mail_smtp and Mail_sendmail mailers require Bcc anc Cc emails // be included in both $to and $headers['Cc', 'Bcc'] if (get_class($mailer) != "Mail_mail") { // get emails from headers, since these are // combination of name and email addresses. if (!empty($headers['Cc'])) { $to[] = CRM_Utils_Array::value('Cc', $headers); } if (!empty($headers['Bcc'])) { $to[] = CRM_Utils_Array::value('Bcc', $headers); } } if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $result = $mailer->send($to, $headers, $message); if (is_a($result, 'PEAR_Error')) { $message = self::errorMessage($mailer, $result); // append error message in case multiple calls are being made to // this method in the course of sending a batch of messages. CRM_Core_Session::setStatus($message, ts('Mailing Error'), 'error'); return FALSE; } // CRM-10699 CRM_Utils_Hook::postEmailSend($params); return TRUE; } return FALSE; }
/** * Get an array of columns and their details like DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT for the given table. */ private function columnSpecsOf($table) { static $columnSpecs = array(), $civiDB = NULL; if (empty($columnSpecs)) { if (!$civiDB) { $dao = new CRM_Contact_DAO_Contact(); $civiDB = $dao->_database; } CRM_Core_TemporaryErrorScope::ignoreException(); // NOTE: W.r.t Performance using one query to find all details and storing in static array is much faster // than firing query for every given table. $query = "\nSELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE table_schema IN ('{$this->db}', '{$civiDB}')"; $dao = CRM_Core_DAO::executeQuery($query); if (is_a($dao, 'DB_Error')) { return array(); } while ($dao->fetch()) { if (!array_key_exists($dao->TABLE_NAME, $columnSpecs)) { $columnSpecs[$dao->TABLE_NAME] = array(); } $columnSpecs[$dao->TABLE_NAME][$dao->COLUMN_NAME] = array('COLUMN_NAME' => $dao->COLUMN_NAME, 'DATA_TYPE' => $dao->DATA_TYPE, 'IS_NULLABLE' => $dao->IS_NULLABLE, 'COLUMN_DEFAULT' => $dao->COLUMN_DEFAULT); if (($first = strpos($dao->COLUMN_TYPE, '(')) != 0) { $columnSpecs[$dao->TABLE_NAME][$dao->COLUMN_NAME]['LENGTH'] = substr($dao->COLUMN_TYPE, $first, strpos($dao->COLUMN_TYPE, ')')); } } } return $columnSpecs[$table]; }
/** * 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()); } }
/** * @param $fields * @param $mailing * @param $mailer * @param $job_date * @param $attachments * * @return bool|null * @throws Exception */ public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments) { static $smtpConnectionErrors = 0; if (!is_object($mailer) || empty($fields)) { CRM_Core_Error::fatal(); } // get the return properties $returnProperties = $mailing->getReturnProperties(); $params = $targetParams = $deliveredParams = array(); $count = 0; /** * CRM-15702: Sending bulk sms to contacts without e-mail address fails. * Solution is to skip checking for on hold */ $skipOnHold = TRUE; //do include a statement to check wether e-mail address is on hold if ($mailing->sms_provider_id) { $skipOnHold = FALSE; //do not include a statement to check wether e-mail address is on hold } foreach ($fields as $key => $field) { $params[] = $field['contact_id']; } $details = CRM_Utils_Token::getTokenDetails($params, $returnProperties, $skipOnHold, TRUE, NULL, $mailing->getFlattenedTokens(), get_class($this), $this->id); $config = CRM_Core_Config::singleton(); foreach ($fields as $key => $field) { $contactID = $field['contact_id']; if (!array_key_exists($contactID, $details[0])) { $details[0][$contactID] = array(); } /* Compose the mailing */ $recipient = $replyToEmail = NULL; $replyValue = strcmp($mailing->replyto_email, $mailing->from_email); if ($replyValue) { $replyToEmail = $mailing->replyto_email; } $message =& $mailing->compose($this->id, $field['id'], $field['hash'], $field['contact_id'], $field['email'], $recipient, FALSE, $details[0][$contactID], $attachments, FALSE, NULL, $replyToEmail); if (empty($message)) { // lets keep the message in the queue // most likely a permissions related issue with smarty templates // or a bad contact id? CRM-9833 continue; } /* Send the mailing */ $body =& $message->get(); $headers =& $message->headers(); if ($mailing->sms_provider_id) { $provider = CRM_SMS_Provider::singleton(array('mailing_id' => $mailing->id)); $body = $provider->getMessage($message, $field['contact_id'], $details[0][$contactID]); $headers = $provider->getRecipientDetails($field, $details[0][$contactID]); } // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743 $recipient = $headers['To']; $result = NULL; // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744 if ($job_date) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); } $result = $mailer->send($recipient, $headers, $body, $this->id); if ($job_date) { unset($errorScope); } if (is_a($result, 'PEAR_Error') && !$mailing->sms_provider_id) { // CRM-9191 $message = $result->getMessage(); if (strpos($message, 'Failed to write to socket') !== FALSE || strpos($message, 'Failed to set sender') !== FALSE) { // lets log this message and code $code = $result->getCode(); CRM_Core_Error::debug_log_message("SMTP Socket Error or failed to set sender error. Message: {$message}, Code: {$code}"); // these are socket write errors which most likely means smtp connection errors // lets skip them $smtpConnectionErrors++; if ($smtpConnectionErrors <= 5) { continue; } // seems like we have too many of them in a row, we should // write stuff to disk and abort the cron job $this->writeToDB($deliveredParams, $targetParams, $mailing, $job_date); CRM_Core_Error::debug_log_message("Too many SMTP Socket Errors. Exiting"); CRM_Utils_System::civiExit(); } /* Register the bounce event */ $params = array('event_queue_id' => $field['id'], 'job_id' => $this->id, 'hash' => $field['hash']); $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage())); CRM_Mailing_Event_BAO_Bounce::create($params); } elseif (is_a($result, 'PEAR_Error') && $mailing->sms_provider_id) { // Handle SMS errors: CRM-15426 $job_id = intval($this->id); $mailing_id = intval($mailing->id); CRM_Core_Error::debug_log_message("Failed to send SMS message. Vars: mailing_id: {$mailing_id}, job_id: {$job_id}. Error message follows."); CRM_Core_Error::debug_log_message($result->getMessage()); } else { /* Register the delivery event */ $deliveredParams[] = $field['id']; $targetParams[] = $field['contact_id']; $count++; if ($count % CRM_Core_DAO::BULK_MAIL_INSERT_COUNT == 0) { $this->writeToDB($deliveredParams, $targetParams, $mailing, $job_date); $count = 0; // hack to stop mailing job at run time, CRM-4246. // to avoid making too many DB calls for this rare case // lets do it when we snapshot $status = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_MailingJob', $this->id, 'status', 'id', TRUE); if ($status != 'Running') { return FALSE; } } } unset($result); // seems like a successful delivery or bounce, lets decrement error count // only if we have smtp connection errors if ($smtpConnectionErrors > 0) { $smtpConnectionErrors--; } // If we have enabled the Throttle option, this is the time to enforce it. if (isset($config->mailThrottleTime) && $config->mailThrottleTime > 0) { usleep((int) $config->mailThrottleTime); } } $result = $this->writeToDB($deliveredParams, $targetParams, $mailing, $job_date); return $result; }
/** * Process the form submission. */ public function postProcess() { // flush caches so we reload details for future requests // CRM-11967 CRM_Utils_System::flushCache(); $formValues = $this->controller->exportValues($this->_name); $buttonName = $this->controller->getButtonName(); // check if test button if ($buttonName == $this->_testButtonName) { if ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED) { CRM_Core_Session::setStatus(ts('You have selected "Disable Outbound Email". A test email can not be sent.'), ts("Email Disabled"), "error"); } elseif ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) { CRM_Core_Session::setStatus(ts('You have selected "Redirect to Database". A test email can not be sent.'), ts("Email Disabled"), "error"); } else { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID); //get the default domain email address.CRM-4250 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') { $fixUrl = CRM_Utils_System::url("civicrm/admin/domain", 'action=update&reset=1'); CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM » Communications » FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl))); } if (!$toEmail) { CRM_Core_Error::statusBounce(ts('Cannot send a test email because your user record does not have a valid email address.')); } if (!trim($toDisplayName)) { $toDisplayName = $toEmail; } $to = '"' . $toDisplayName . '"' . "<{$toEmail}>"; $from = '"' . $domainEmailName . '" <' . $domainEmailAddress . '>'; $testMailStatusMsg = ts('Sending test email. FROM: %1 TO: %2.<br />', array(1 => $domainEmailAddress, 2 => $toEmail)); $params = array(); if ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) { $subject = "Test for SMTP settings"; $message = "SMTP settings are correct."; $params['host'] = $formValues['smtpServer']; $params['port'] = $formValues['smtpPort']; if ($formValues['smtpAuth']) { $params['username'] = $formValues['smtpUsername']; $params['password'] = $formValues['smtpPassword']; $params['auth'] = TRUE; } else { $params['auth'] = FALSE; } // set the localhost value, CRM-3153, CRM-9332 $params['localhost'] = $_SERVER['SERVER_NAME']; // also set the timeout value, lets set it to 30 seconds // CRM-7510, CRM-9332 $params['timeout'] = 30; $mailerName = 'smtp'; } elseif ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) { $subject = "Test for Sendmail settings"; $message = "Sendmail settings are correct."; $params['sendmail_path'] = $formValues['sendmail_path']; $params['sendmail_args'] = $formValues['sendmail_args']; $mailerName = 'sendmail'; } elseif ($formValues['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) { $subject = "Test for PHP mail settings"; $message = "mail settings are correct."; $mailerName = 'mail'; } $headers = array('From' => $from, 'To' => $to, 'Subject' => $subject); $mailer = Mail::factory($mailerName, $params); $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $result = $mailer->send($toEmail, $headers, $message); unset($errorScope); if (!is_a($result, 'PEAR_Error')) { CRM_Core_Session::setStatus($testMailStatusMsg . ts('Your %1 settings are correct. A test email has been sent to your email address.', array(1 => strtoupper($mailerName))), ts("Mail Sent"), "success"); } else { $message = CRM_Utils_Mail::errorMessage($mailer, $result); CRM_Core_Session::setStatus($testMailStatusMsg . ts('Oops. Your %1 settings are incorrect. No test mail has been sent.', array(1 => strtoupper($mailerName))) . $message, ts("Mail Not Sent"), "error"); } } } $mailingBackend = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mailing_backend'); if (!empty($mailingBackend)) { CRM_Core_BAO_ConfigSetting::formatParams($formValues, $mailingBackend); } // if password is present, encrypt it if (!empty($formValues['smtpPassword'])) { $formValues['smtpPassword'] = CRM_Utils_Crypt::encrypt($formValues['smtpPassword']); } CRM_Core_BAO_Setting::setItem($formValues, CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mailing_backend'); }
/** * Execute external or internal URLs and return server response. * * @param string $url * Request URL. * @param bool $addCookie * Whether to provide a cookie. Should be true to access internal URLs. * * @return string * Response from URL. */ public static function getServerResponse($url, $addCookie = TRUE) { CRM_Core_TemporaryErrorScope::ignoreException(); require_once 'HTTP/Request.php'; $request = new HTTP_Request($url); if ($addCookie) { foreach ($_COOKIE as $name => $value) { $request->addCookie($name, $value); } } if (isset($_SERVER['AUTH_TYPE'])) { $request->setBasicAuth($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); } $config = CRM_Core_Config::singleton(); if ($config->userFramework == 'WordPress') { session_write_close(); } $request->sendRequest(); $response = $request->getResponseBody(); return $response; }
/** * Process the form submission. */ function postProcess() { $formValues = $this->exportValues(); $buttonName = $this->controller->getButtonName(); if ($buttonName == $this->_testButtonName) { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID); //get the default domain email address.CRM-4250 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') { $fixUrl = CRM_Utils_System::url("civicrm/admin/domain", 'action=update&reset=1'); CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM » Communications » FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl))); } if (!$toEmail) { CRM_Core_Error::statusBounce(ts('Cannot send a test email because your user record does not have a valid email address.')); } if (!trim($toDisplayName)) { $toDisplayName = $toEmail; } $testMailStatusMsg = ts('Sending test email. FROM: %1 TO: %2.<br />', array(1 => $domainEmailAddress, 2 => $toEmail)); $params = array(); $message = "SMTP settings are correct."; $params['host'] = $formValues['smtpServer']; $params['port'] = $formValues['smtpPort']; if ($formValues['smtpAuth']) { $params['username'] = $formValues['smtpUsername']; $params['password'] = $formValues['smtpPassword']; $params['auth'] = TRUE; } else { $params['auth'] = FALSE; } // set the localhost value, CRM-3153, CRM-9332 $params['localhost'] = $_SERVER['SERVER_NAME']; // also set the timeout value, lets set it to 30 seconds // CRM-7510, CRM-9332 $params['timeout'] = 30; $mailerName = 'smtp'; $headers = array('From' => '"' . $domainEmailName . '" <' . $domainEmailAddress . '>', 'To' => '"' . $toDisplayName . '"' . "<{$toEmail}>", 'Subject' => "Test for SMTP settings"); $mailer = Mail::factory($mailerName, $params); $config = CRM_Core_Config::singleton(); if (property_exists($config, 'civiVersion')) { $civiVersion = $config->civiVersion; } else { $civiVersion = CRM_Core_BAO_Domain::version(); } if (version_compare('4.5alpha1', $civiVersion) > 0) { CRM_Core_Error::ignoreException(); } else { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); } $result = $mailer->send($toEmail, $headers, $message); if (version_compare('4.5alpha1', $civiVersion) > 0) { CRM_Core_Error::setCallback(); } else { unset($errorScope); } if (!is_a($result, 'PEAR_Error')) { CRM_Core_Session::setStatus($testMailStatusMsg . ts('Your %1 settings are correct. A test email has been sent to your email address.', array(1 => strtoupper($mailerName))), ts("Mail Sent"), "success"); } else { $message = CRM_Utils_Mail::errorMessage($mailer, $result); CRM_Core_Session::setStatus($testMailStatusMsg . ts('Oops. Your %1 settings are incorrect. No test mail has been sent.', array(1 => strtoupper($mailerName))) . $message, ts("Mail Not Sent"), "error"); } } // if password is present, encrypt it if (!empty($formValues['smtpPassword'])) { $formValues['smtpPassword'] = CRM_Utils_Crypt::encrypt($formValues['smtpPassword']); } CRM_Core_BAO_Setting::setItem($formValues, CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'mandrill_smtp_settings'); }
/** * @param object $sort * @param string $cacheKey * @param int $start * @param int $end */ function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500) { $coreSearch = TRUE; // For custom searches, use the contactIDs method if (is_a($this, 'CRM_Contact_Selector_Custom')) { $sql = $this->_search->contactIDs($start, $end, $sort, TRUE); $replaceSQL = "SELECT contact_a.id as contact_id"; $coreSearch = FALSE; } else { $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, $this->_query->_includeContactIds, FALSE, TRUE, TRUE); $replaceSQL = "SELECT contact_a.id as id"; } // CRM-9096 // due to limitations in our search query writer, the above query does not work // in cases where the query is being sorted on a non-contact table // this results in a fatal error :( // see below for the gross hack of trapping the error and not filling // the prev next cache in this situation // the other alternative of running the FULL query will just be incredibly inefficient // and slow things down way too much on large data sets / complex queries $insertSQL = "\nINSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )\nSELECT DISTINCT 'civicrm_contact', contact_a.id, contact_a.id, '{$cacheKey}', contact_a.display_name\n"; $sql = str_replace($replaceSQL, $insertSQL, $sql); $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $result = CRM_Core_DAO::executeQuery($sql); unset($errorScope); if (is_a($result, 'DB_Error')) { // check if we get error during core search if ($coreSearch) { // in the case of error, try rebuilding cache using full sql which is used for search selector display // this fixes the bugs reported in CRM-13996 & CRM-14438 $this->rebuildPreNextCache($start, $end, $sort, $cacheKey); } else { // return if above query fails return; } } // also record an entry in the cache key table, so we can delete it periodically CRM_Core_BAO_Cache::setItem($cacheKey, 'CiviCRM Search PrevNextCache', $cacheKey); }
/** * 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(); }
/** * @param $config * * @return object */ public static function &dbHandle(&$config) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $db_uf = DB::connect($config->userFrameworkDSN); unset($errorScope); if (!$db_uf || DB::isError($db_uf)) { $session = CRM_Core_Session::singleton(); $session->pushUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1')); CRM_Core_Error::statusBounce(ts("Cannot connect to UF db via %1. Please check the CIVICRM_UF_DSN value in your civicrm.settings.php file", array(1 => $db_uf->getMessage()))); } $db_uf->query('/*!40101 SET NAMES utf8 */'); return $db_uf; }
/** * Singleton function used to manage this object. * * @param bool $loadFromDB * whether to load from the database. * @param bool $force * whether to force a reconstruction. * * @return CRM_Core_Config */ public static function &singleton($loadFromDB = TRUE, $force = FALSE) { if (self::$_singleton === NULL || $force) { // goto a simple error handler $GLOBALS['civicrm_default_error_scope'] = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'handle')); $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Core_Error', 'simpleHandler')); // lets ensure we set E_DEPRECATED to minimize errors // CRM-6327 if (defined('E_DEPRECATED')) { error_reporting(error_reporting() & ~E_DEPRECATED); } // first, attempt to get configuration object from cache $cache = CRM_Utils_Cache::singleton(); self::$_singleton = $cache->get('CRM_Core_Config' . CRM_Core_Config::domainID()); // if not in cache, fire off config construction if (!self::$_singleton) { self::$_singleton = new CRM_Core_Config(); self::$_singleton->_initialize($loadFromDB); //initialize variables. for gencode we cannot load from the //db since the db might not be initialized if ($loadFromDB) { // initialize stuff from the settings file self::$_singleton->setCoreVariables(); self::$_singleton->_initVariables(); // I don't think we need to do this twice // however just keeping this commented for now in 4.4 // in case we hit any issues - CRM-13064 // We can safely delete this once we release 4.4.4 // self::$_singleton->setCoreVariables(); } $cache->set('CRM_Core_Config' . CRM_Core_Config::domainID(), self::$_singleton); } else { // we retrieve the object from memcache, so we now initialize the objects self::$_singleton->_initialize($loadFromDB); // CRM-9803, NYSS-4822 // this causes various settings to be reset and hence we should // only use the config object that we retrieved from memcache } self::$_singleton->initialized = 1; if (isset(self::$_singleton->customPHPPathDir) && self::$_singleton->customPHPPathDir) { $include_path = self::$_singleton->customPHPPathDir . PATH_SEPARATOR . get_include_path(); set_include_path($include_path); } // set the callback at the very very end, to avoid an infinite loop // set the error callback unset($errorScope); // call the hook so other modules can add to the config // again doing this at the very very end CRM_Utils_Hook::config(self::$_singleton); // make sure session is always initialised $session = CRM_Core_Session::singleton(); // for logging purposes, pass the userID to the db $userID = $session->get('userID'); if ($userID) { CRM_Core_DAO::executeQuery('SET @civicrm_user_id = %1', array(1 => array($userID, 'Integer'))); } // initialize authentication source self::$_singleton->initAuthSrc(); } return self::$_singleton; }