Пример #1
0
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 public function preProcess()
 {
     //Test database user privilege to create table(Temporary) CRM-4725
     CRM_Core_Error::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 TABLE IF EXISTS import_job_permission_one, import_job_permission_two");
     CRM_Core_Error::setCallback();
     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.'));
     }
     $this->_dataSourceIsValid = false;
     $this->_dataSource = CRM_Utils_Request::retrieve('dataSource', 'String', CRM_Core_DAO::$_nullObject);
     $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);
     }
     if (strpos($this->_dataSource, 'CRM_Import_DataSource_') === 0) {
         $this->_dataSourceIsValid = true;
         $this->assign('showDataSourceFormPane', true);
         $dataSourcePath = split('_', $this->_dataSource);
         $templateFile = "CRM/Import/Form/" . $dataSourcePath[3] . ".tpl";
         $this->assign('dataSourceFormTemplateFile', $templateFile);
     }
 }
Пример #2
0
 static function send($from, $toDisplayName, $toEmail, $subject, $text_message = null, $cc = null, $bcc = null, $replyTo = null, $html_message = null, $attachments = null)
 {
     require_once 'CRM/Core/BAO/MailSettings.php';
     $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
     if (!$returnPath) {
         $returnPath = self::pluckEmailFromHeader($from);
     }
     $headers = array();
     $headers['From'] = $from;
     $headers['To'] = "{$toDisplayName} <{$toEmail}>";
     $headers['Cc'] = $cc;
     $headers['Subject'] = $subject;
     $headers['Content-Type'] = $html_message ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
     $headers['Content-Disposition'] = 'inline';
     $headers['Content-Transfer-Encoding'] = '8bit';
     $headers['Return-Path'] = $returnPath;
     $headers['Reply-To'] = isset($replyTo) ? $replyTo : $from;
     $headers['Date'] = date('r');
     $to = array($toEmail);
     if ($cc) {
         $to[] = $cc;
     }
     if ($bcc) {
         $to[] = $bcc;
     }
     // we need to wrap Mail_mime because PEAR is apparently unable to fix
     // a six-year-old bug (PEAR bug #30) in Mail_mime::_encodeHeaders()
     // this fixes CRM-4631
     require_once 'CRM/Utils/Mail/FixedMailMIME.php';
     $msg = new CRM_Utils_Mail_FixedMailMIME("\n");
     if ($text_message) {
         $msg->setTxtBody($text_message);
     }
     if ($html_message) {
         $msg->setHTMLBody($html_message);
     }
     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);
     $result = null;
     $mailer =& CRM_Core_Config::getMailer();
     CRM_Core_Error::ignoreException();
     if (is_object($mailer)) {
         $result = $mailer->send($to, $headers, $message);
         CRM_Core_Error::setCallback();
         if (is_a($result, 'PEAR_Error')) {
             $message = self::errorMessage($mailer, $result);
             CRM_Core_Session::setStatus($message, false);
             return false;
         }
         return true;
     }
     return false;
 }
Пример #3
0
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 public function preProcess()
 {
     //Test database user privilege to create table(Temporary) CRM-4725
     CRM_Core_Error::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 TABLE IF EXISTS import_job_permission_one, import_job_permission_two");
     CRM_Core_Error::setCallback();
     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');
     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);
     $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);
     }
     if (strpos($this->_dataSource, 'CRM_Import_DataSource_') === 0) {
         $this->_dataSourceIsValid = true;
         $this->assign('showDataSourceFormPane', true);
         $dataSourcePath = explode('_', $this->_dataSource);
         $templateFile = "CRM/Import/Form/" . $dataSourcePath[3] . ".tpl";
         $this->assign('dataSourceFormTemplateFile', $templateFile);
     }
 }
Пример #4
0
 /**
  * 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_Error::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\nFROM   INFORMATION_SCHEMA.COLUMNS\nWHERE  table_schema IN ('{$this->db}', '{$civiDB}')";
         $dao = CRM_Core_DAO::executeQuery($query);
         CRM_Core_Error::setCallback();
         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);
         }
     }
     return $columnSpecs[$table];
 }
Пример #5
0
 /**
  * execute an unbuffered query.  This is a wrapper around new functionality
  * exposed with CRM-17748.
  *
  * @param string $query query to be executed
  *
  * @return Object CRM_Core_DAO object that points to an unbuffered result set
  * @static
  * @access public
  */
 public static function executeUnbufferedQuery($query, $params = array(), $abort = TRUE, $daoName = NULL, $freeDAO = FALSE, $i18nRewrite = TRUE, $trapException = FALSE)
 {
     $queryStr = self::composeQuery($query, $params, $abort);
     //CRM_Core_Error::debug( 'q', $queryStr );
     if (!$daoName) {
         $dao = new CRM_Core_DAO();
     } else {
         $dao = new $daoName();
     }
     if ($trapException) {
         CRM_Core_Error::ignoreException();
     }
     // set the DAO object to use an unbuffered query
     $dao->setOptions(array('result_buffering' => 0));
     $result = $dao->query($queryStr, $i18nRewrite);
     if ($trapException) {
         CRM_Core_Error::setCallback();
     }
     if (is_a($result, 'DB_Error')) {
         return $result;
     }
     // since it is unbuffered, ($dao->N==0) is true.  This blocks the standard fetch() mechanism.
     $dao->N = TRUE;
     if ($freeDAO || preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)) {
         // we typically do this for insert/update/delete stataments OR if explicitly asked to
         // free the dao
         $dao->free();
     }
     return $dao;
 }
 /**
  * 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 &raquo; Communications &raquo; 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');
 }
Пример #7
0
 static function sendReminder($contactId, $email, $messageTemplateID, $from)
 {
     require_once "CRM/Core/BAO/Domain.php";
     require_once "CRM/Utils/String.php";
     require_once "CRM/Utils/Token.php";
     $messageTemplates =& new CRM_Core_DAO_MessageTemplates();
     $messageTemplates->id = $messageTemplateID;
     $domain = CRM_Core_BAO_Domain::getDomain();
     $result = null;
     if ($messageTemplates->find(true)) {
         $body_text = $messageTemplates->msg_text;
         $body_html = $messageTemplates->msg_html;
         $body_subject = $messageTemplates->msg_subject;
         if (!$body_text) {
             $body_text = CRM_Utils_String::htmlToText($body_html);
         }
         $params = array('contact_id' => $contactId);
         require_once 'api/v2/Contact.php';
         $contact =& civicrm_contact_get($params);
         //CRM-4524
         $contact = reset($contact);
         if (!$contact || is_a($contact, 'CRM_Core_Error')) {
             return null;
         }
         $type = array('html', 'text');
         foreach ($type as $key => $value) {
             require_once 'CRM/Mailing/BAO/Mailing.php';
             $dummy_mail = new CRM_Mailing_BAO_Mailing();
             $bodyType = "body_{$value}";
             $dummy_mail->{$bodyType} = ${$bodyType};
             $tokens = $dummy_mail->getTokens();
             if (${$bodyType}) {
                 ${$bodyType} = CRM_Utils_Token::replaceDomainTokens(${$bodyType}, $domain, true, $tokens[$value]);
                 ${$bodyType} = CRM_Utils_Token::replaceContactTokens(${$bodyType}, $contact, false, $tokens[$value]);
             }
         }
         $html = $body_html;
         $text = $body_text;
         $message =& new Mail_Mime("\n");
         /* Do contact-specific token replacement in text mode, and add to the
          * message if necessary */
         if (!$html || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both') {
             // render the &amp; entities in text mode, so that the links work
             $text = str_replace('&amp;', '&', $text);
             $message->setTxtBody($text);
             unset($text);
         }
         if ($html && ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both')) {
             $message->setHTMLBody($html);
             unset($html);
         }
         $recipient = "\"{$contact['display_name']}\" <{$email}>";
         $matches = array();
         preg_match_all('/(?<!\\{|\\\\)\\{(\\w+\\.\\w+)\\}(?!\\})/', $body_subject, $matches, PREG_PATTERN_ORDER);
         $subjectToken = null;
         if ($matches[1]) {
             foreach ($matches[1] as $token) {
                 list($type, $name) = split('\\.', $token, 2);
                 if ($name) {
                     if (!isset($subjectToken['contact'])) {
                         $subjectToken['contact'] = array();
                     }
                     $subjectToken['contact'][] = $name;
                 }
             }
         }
         $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, false, $subjectToken);
         $headers = array('From' => $from, 'Subject' => $messageSubject);
         $headers['To'] = $recipient;
         $mailMimeParams = array('text_encoding' => '8bit', 'html_encoding' => '8bit', 'head_charset' => 'utf-8', 'text_charset' => 'utf-8', 'html_charset' => 'utf-8');
         $message->get($mailMimeParams);
         $message->headers($headers);
         $config =& CRM_Core_Config::singleton();
         $mailer =& $config->getMailer();
         $body = $message->get();
         $headers = $message->headers();
         CRM_Core_Error::ignoreException();
         $result = $mailer->send($recipient, $headers, $body);
         CRM_Core_Error::setCallback();
     }
     return $result;
 }
Пример #8
0
 /**
  * Execute external or internal urls and return server response
  *
  *  @param string   $url request url 
  *  @param boolean  $addCookie  should be true to access internal urls
  *
  *  @return string  $response response from url
  *  @static
  */
 static function getServerResponse($url, $addCookie = true)
 {
     CRM_Core_Error::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 == 'Standalone') {
         session_write_close();
     }
     $request->sendRequest();
     $response = $request->getResponseBody();
     CRM_Core_Error::setCallback();
     return $response;
 }
Пример #9
0
 public function deliverGroup(&$fields, &$mailing, &$mailer, &$job_date, &$attachments)
 {
     // get the return properties
     $returnProperties = $mailing->getReturnProperties();
     $params = array();
     $targetParams = array();
     foreach ($fields as $key => $field) {
         $params[] = $field['contact_id'];
     }
     $details = $mailing->getDetails($params, $returnProperties);
     foreach ($fields as $key => $field) {
         $contactID = $field['contact_id'];
         /* Compose the mailing */
         $recipient = null;
         $message =& $mailing->compose($this->id, $field['id'], $field['hash'], $field['contact_id'], $field['email'], $recipient, false, $details[0][$contactID], $attachments);
         /* Send the mailing */
         $body =& $message->get();
         $headers =& $message->headers();
         // make $recipient actually be the *encoded* header, so as not to baffle Mail_RFC822, CRM-5743
         $recipient = $headers['To'];
         $result = null;
         /* TODO: when we separate the content generator from the delivery
          * engine, maybe we should dump the messages into a table */
         // disable error reporting on real mailings (but leave error reporting for tests), CRM-5744
         if ($job_date) {
             CRM_Core_Error::ignoreException();
         }
         if (is_object($mailer)) {
             // hack to stop mailing job at run time, CRM-4246.
             $mailingJob = new CRM_Mailing_DAO_Job();
             $mailingJob->mailing_id = $mailing->id;
             if ($mailingJob->find(true)) {
                 // mailing have been canceled at run time.
                 if ($mailingJob->status == 'Canceled') {
                     return false;
                 }
             } else {
                 // mailing have been deleted at run time.
                 return false;
             }
             $mailingJob->free();
             $result = $mailer->send($recipient, $headers, $body, $this->id);
             CRM_Core_Error::setCallback();
         }
         $params = array('event_queue_id' => $field['id'], 'job_id' => $this->id, 'hash' => $field['hash']);
         if (is_a($result, 'PEAR_Error')) {
             /* Register the bounce event */
             require_once 'CRM/Mailing/BAO/BouncePattern.php';
             require_once 'CRM/Mailing/Event/BAO/Bounce.php';
             $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage()));
             CRM_Mailing_Event_BAO_Bounce::create($params);
         } else {
             /* Register the delivery event */
             CRM_Mailing_Event_BAO_Delivered::create($params);
         }
         $targetParams[] = $field['contact_id'];
         unset($result);
     }
     if (!empty($targetParams)) {
         // add activity record for every mail that is send
         $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Bulk Email', 'name');
         $activity = array('source_contact_id' => $mailing->scheduled_id, 'target_contact_id' => $targetParams, 'activity_type_id' => $activityTypeID, 'source_record_id' => $this->mailing_id, 'activity_date_time' => $job_date, 'subject' => $mailing->subject, 'status_id' => 2, 'deleteActivityTarget' => false);
         //check whether activity is already created for this mailing.
         //if yes then create only target contact record.
         $query = "\nSELECT id \nFROM   civicrm_activity\nWHERE  civicrm_activity.activity_type_id = %1\nAND    civicrm_activity.source_record_id = %2";
         $queryParams = array(1 => array($activityTypeID, 'Integer'), 2 => array($this->mailing_id, 'Integer'));
         $activityID = CRM_Core_DAO::singleValueQuery($query, $queryParams);
         if ($activityID) {
             $activity['id'] = $activityID;
         }
         require_once 'api/v2/Activity.php';
         if (is_a(civicrm_activity_create($activity, 'Email'), 'CRM_Core_Error')) {
             return false;
         }
     }
     return true;
 }
Пример #10
0
 /**
  * Function to build the form
  *
  * @return None
  * @access public
  */
 public function buildQuickForm()
 {
     $config =& CRM_Core_Config::singleton();
     $i18n =& CRM_Core_I18n::singleton();
     CRM_Utils_System::setTitle(ts('Settings - Localization'));
     $locales =& CRM_Core_I18n::languages();
     $domain =& new CRM_Core_DAO_Domain();
     $domain->find(true);
     if ($domain->locales) {
         // for multi-lingual sites, populate default language drop-down with available languages
         $lcMessages = array();
         foreach ($locales as $loc => $lang) {
             if (substr_count($domain->locales, $loc)) {
                 $lcMessages[$loc] = $lang;
             }
         }
         $this->addElement('select', 'lcMessages', ts('Default Language'), $lcMessages);
         // add language limiter and language adder
         $this->addCheckBox('languageLimit', ts('Available Languages'), array_flip($lcMessages), null, null, null, null, ' &nbsp; ');
         $this->addElement('select', 'addLanguage', ts('Add Language'), array_merge(array('' => ts('- select -')), array_diff($locales, $lcMessages)));
         // add the ability to return to single language
         $warning = ts('WARNING: This will make your CiviCRM installation a single-language one again. THIS WILL DELETE ALL DATA RELATED TO LANGUAGES OTHER THAN THE DEFAULT ONE SELECTED ABOVE (and only that language will be preserved).');
         $this->assign('warning', $warning);
         $this->addElement('checkbox', 'makeSinglelingual', ts('Return to Single Language'), null, array('onChange' => "if (this.checked) alert('{$warning}')"));
     } else {
         // for single-lingual sites, populate default language drop-down with all languages
         $this->addElement('select', 'lcMessages', ts('Default Language'), $locales);
         $warning = ts('WARNING: As of CiviCRM 3.0, this is still an experimental functionality. Enabling multiple languages irreversibly changes the schema of your database, so make sure you know what you are doing when enabling this function; making a database backup is strongly recommended.');
         $this->assign('warning', $warning);
         // test for create view and trigger permissions and if allowed, add the option to go multilingual
         CRM_Core_Error::ignoreException();
         $dao = new CRM_Core_DAO();
         $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
         $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
         $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
         $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
         CRM_Core_Error::setCallback();
         if (!$dao->_lastError) {
             $this->addElement('checkbox', 'makeMultilingual', ts('Enable Multiple Languages'), null, array('onChange' => "if (this.checked) alert('{$warning}')"));
         }
     }
     $this->addElement('select', 'lcMonetary', ts('Monetary Locale'), $locales);
     $this->addElement('text', 'moneyformat', ts('Monetary Amount Display'));
     $this->addElement('text', 'moneyvalueformat', ts('Monetary Value Display'));
     $country = array();
     CRM_Core_PseudoConstant::populate($country, 'CRM_Core_DAO_Country', true, 'name', 'is_active');
     $i18n->localizeArray($country);
     asort($country);
     $includeCountry =& $this->addElement('advmultiselect', 'countryLimit', ts('Available Countries') . ' ', $country, array('size' => 5, 'style' => 'width:150px', 'class' => 'advmultiselect'));
     $includeCountry->setButtonAttributes('add', array('value' => ts('Add >>')));
     $includeCountry->setButtonAttributes('remove', array('value' => ts('<< Remove')));
     $includeState =& $this->addElement('advmultiselect', 'provinceLimit', ts('Available States and Provinces') . ' ', $country, array('size' => 5, 'style' => 'width:150px', 'class' => 'advmultiselect'));
     $includeState->setButtonAttributes('add', array('value' => ts('Add >>')));
     $includeState->setButtonAttributes('remove', array('value' => ts('<< Remove')));
     $this->addElement('select', 'defaultContactCountry', ts('Default Country'), array('' => ts('- select -')) + $country);
     // we do this only to initialize currencySymbols, kinda hackish but works!
     $config->defaultCurrencySymbol();
     $symbol = $config->currencySymbols;
     foreach ($symbol as $key => $value) {
         $currencySymbols[$key] = "{$key}";
         if ($value) {
             $currencySymbols[$key] .= " ({$value})";
         }
     }
     $this->addElement('select', 'defaultCurrency', ts('Default Currency'), $currencySymbols);
     $this->addElement('text', 'legacyEncoding', ts('Legacy Encoding'));
     $this->addElement('text', 'customTranslateFunction', ts('Custom Translate Function'));
     $this->addElement('text', 'fieldSeparator', ts('Import / Export Field Separator'), array('size' => 2));
     $this->addFormRule(array('CRM_Admin_Form_Setting_Localization', 'formRule'));
     parent::buildQuickForm();
 }
Пример #11
0
 /**
  * Send a reponse 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
  *
  * @return void
  * @access public
  * @static
  */
 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 = $config->getMailer();
     if (is_object($mailer)) {
         CRM_Core_Error::ignoreException();
         $mailer->send($eq->email, $h, $b);
         CRM_Core_Error::setCallback();
     }
 }
Пример #12
0
 /**
  * Get an array of column names of the given table.
  */
 private function columnsOf($table)
 {
     static $columnsOf = array();
     $from = substr($table, 0, 4) == 'log_' ? "`{$this->db}`.{$table}" : $table;
     if (!isset($columnsOf[$table])) {
         CRM_Core_Error::ignoreException();
         $dao = CRM_Core_DAO::executeQuery("SHOW COLUMNS FROM {$from}");
         CRM_Core_Error::setCallback();
         if (is_a($dao, 'DB_Error')) {
             return array();
         }
         $columnsOf[$table] = array();
         while ($dao->fetch()) {
             $columnsOf[$table][] = $dao->Field;
         }
     }
     return $columnsOf[$table];
 }
Пример #13
0
 /**
  * @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);
     CRM_Core_Error::ignoreException();
     $result = CRM_Core_DAO::executeQuery($sql);
     CRM_Core_Error::setCallback();
     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);
 }
Пример #14
0
 /**
  * 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)
  * 
  * @access public
  * @return boolean true if a mail was sent, else false
  */
 static function send(&$params)
 {
     require_once 'CRM/Core/BAO/MailSettings.php';
     $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
     $from = CRM_Utils_Array::value('from', $params);
     if (!$returnPath) {
         $returnPath = self::pluckEmailFromHeader($from);
     }
     $params['returnPath'] = $returnPath;
     // first call the mail alter hook
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::alterMailParams($params);
     // check if any module has aborted mail sending
     if (CRM_Utils_Array::value('abortMailSend', $params) || !CRM_Utils_Array::value('toEmail', $params)) {
         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();
     $headers['From'] = $params['from'];
     $headers['To'] = "{$params['toName']} <{$params['toEmail']}>";
     $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);
     $headers['Reply-To'] = CRM_Utils_Array::value('replyTo', $params, $from);
     $headers['Date'] = date('r');
     if (CRM_Utils_Array::value('autoSubmitted', $params)) {
         $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) {
         $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']);
         if (substr($from[0], 0, 1) != '"' || substr($from[0], -1, 1) != '"') {
             $from[0] = str_replace('"', '\\"', $from[0]);
             $headers['From'] = "\"{$from[0]}\" <{$from[1]}";
         }
     }
     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']);
     //get emails from headers, since these are
     //combination of name and email addresses.
     if (CRM_Utils_Array::value('Cc', $headers)) {
         $to[] = CRM_Utils_Array::value('Cc', $headers);
     }
     if (CRM_Utils_Array::value('Bcc', $headers)) {
         $to[] = CRM_Utils_Array::value('Bcc', $headers);
         unset($headers['Bcc']);
     }
     $result = null;
     $mailer =& CRM_Core_Config::getMailer();
     CRM_Core_Error::ignoreException();
     if (is_object($mailer)) {
         $result = $mailer->send($to, $headers, $message);
         CRM_Core_Error::setCallback();
         if (is_a($result, 'PEAR_Error')) {
             $message = self::errorMessage($mailer, $result);
             CRM_Core_Session::setStatus($message, false);
             return false;
         }
         return true;
     }
     return false;
 }
Пример #15
0
 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 addres 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) {
             CRM_Core_Error::ignoreException();
         }
         $result = $mailer->send($recipient, $headers, $body, $this->id);
         if ($job_date) {
             CRM_Core_Error::setCallback();
         }
         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;
 }
Пример #16
0
 /**
  * Create a new forward event, create a new contact if necessary
  */
 static function &forward($job_id, $queue_id, $hash, $forward_email, $fromEmail = NULL, $comment = NULL)
 {
     $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     $successfulForward = FALSE;
     $contact_id = NULL;
     if (!$q) {
         return $successfulForward;
     }
     /* Find the email address/contact, if it exists */
     $contact = CRM_Contact_BAO_Contact::getTableName();
     $location = CRM_Core_BAO_Location::getTableName();
     $email = CRM_Core_BAO_Email::getTableName();
     $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName();
     $job = CRM_Mailing_BAO_MailingJob::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $forward = self::getTableName();
     $domain = CRM_Core_BAO_Domain::getDomain();
     $dao = new CRM_Core_Dao();
     $dao->query("\n                SELECT      {$contact}.id as contact_id,\n                            {$email}.id as email_id,\n                            {$contact}.do_not_email as do_not_email,\n                            {$queueTable}.id as queue_id\n                FROM        ({$email}, {$job} as temp_job)\n                INNER JOIN  {$contact}\n                        ON  {$email}.contact_id = {$contact}.id\n                LEFT JOIN   {$queueTable}\n                        ON  {$email}.id = {$queueTable}.email_id\n                LEFT JOIN   {$job}\n                        ON  {$queueTable}.job_id = {$job}.id\n                        AND temp_job.mailing_id = {$job}.mailing_id\n                WHERE       {$queueTable}.job_id = {$job_id}\n                    AND     {$email}.email = '" . CRM_Utils_Type::escape($forward_email, 'String') . "'");
     $dao->fetch();
     $transaction = new CRM_Core_Transaction();
     if (isset($dao->queue_id) || isset($dao->do_not_email) && $dao->do_not_email == 1) {
         /* We already sent this mailing to $forward_email, or we should
          * never email this contact.  Give up. */
         return $successfulForward;
     }
     require_once 'api/api.php';
     $contactParams = array('email' => $forward_email, 'version' => 3);
     $contactValues = civicrm_api('contact', 'get', $contactParams);
     $count = $contactValues['count'];
     if ($count == 0) {
         /* If the contact does not exist, create one. */
         $formatted = array('contact_type' => 'Individual', 'version' => 3);
         $locationType = CRM_Core_BAO_LocationType::getDefault();
         $value = array('email' => $forward_email, 'location_type_id' => $locationType->id);
         require_once 'CRM/Utils/DeprecatedUtils.php';
         _civicrm_api3_deprecated_add_formatted_param($value, $formatted);
         $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP;
         $formatted['fixAddress'] = TRUE;
         $contact = civicrm_api('contact', 'create', $formatted);
         if (civicrm_error($contact)) {
             return $successfulForward;
         }
         $contact_id = $contact['id'];
     }
     $email = new CRM_Core_DAO_Email();
     $email->email = $forward_email;
     $email->find(TRUE);
     $email_id = $email->id;
     if (!$contact_id) {
         $contact_id = $email->contact_id;
     }
     /* Create a new queue event */
     $queue_params = array('email_id' => $email_id, 'contact_id' => $contact_id, 'job_id' => $job_id);
     $queue = CRM_Mailing_Event_BAO_Queue::create($queue_params);
     $forward = new CRM_Mailing_Event_BAO_Forward();
     $forward->time_stamp = date('YmdHis');
     $forward->event_queue_id = $queue_id;
     $forward->dest_queue_id = $queue->id;
     $forward->save();
     $dao->reset();
     $dao->query("   SELECT  {$job}.mailing_id as mailing_id\n                        FROM    {$job}\n                        WHERE   {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer'));
     $dao->fetch();
     $mailing_obj = new CRM_Mailing_BAO_Mailing();
     $mailing_obj->id = $dao->mailing_id;
     $mailing_obj->find(TRUE);
     $config = CRM_Core_Config::singleton();
     $mailer = $config->getMailer();
     $recipient = NULL;
     $attachments = NULL;
     $message = $mailing_obj->compose($job_id, $queue->id, $queue->hash, $queue->contact_id, $forward_email, $recipient, FALSE, NULL, $attachments, TRUE, $fromEmail);
     //append comment if added while forwarding.
     if (count($comment)) {
         $message->_txtbody = CRM_Utils_Array::value('body_text', $comment) . $message->_txtbody;
         if (!empty($comment['body_html'])) {
             $message->_htmlbody = $comment['body_html'] . '<br />---------------Original message---------------------<br />' . $message->_htmlbody;
         }
     }
     $body = $message->get();
     $headers = $message->headers();
     $result = NULL;
     if (is_object($mailer)) {
         CRM_Core_Error::ignoreException();
         $result = $mailer->send($recipient, $headers, $body);
         CRM_Core_Error::setCallback();
     }
     $params = array('event_queue_id' => $queue->id, 'job_id' => $job_id, 'hash' => $queue->hash);
     if (is_a($result, 'PEAR_Error')) {
         /* Register the bounce event */
         $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage()));
         CRM_Mailing_Event_BAO_Bounce::create($params);
     } else {
         $successfulForward = TRUE;
         /* Register the delivery event */
         CRM_Mailing_Event_BAO_Delivered::create($params);
     }
     $transaction->commit();
     return $successfulForward;
 }
Пример #17
0
 /**
  * Send an automated response
  *
  * @param object $mailing       The mailing object
  * @param int $queue_id         The queue ID
  * @param string $replyto       Optional reply-to from the reply
  *
  * @return void
  * @access private
  * @static
  */
 private static function autoRespond(&$mailing, $queue_id, $replyto)
 {
     $config = CRM_Core_Config::singleton();
     $contacts = CRM_Contact_DAO_Contact::getTableName();
     $email = CRM_Core_DAO_Email::getTableName();
     $queue = CRM_Mailing_Event_DAO_Queue::getTableName();
     $eq = new CRM_Core_DAO();
     $eq->query("SELECT     {$contacts}.preferred_mail_format as format,\n                  {$email}.email as email,\n                  {$queue}.job_id as job_id,\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();
     $to = empty($replyto) ? $eq->email : $replyto;
     $component = new CRM_Mailing_BAO_Component();
     $component->id = $mailing->reply_id;
     $component->find(TRUE);
     $message = new Mail_Mime("\n");
     $domain = CRM_Core_BAO_Domain::getDomain();
     list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail();
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $headers = array('Subject' => $component->subject, 'To' => $to, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}");
     /* TODO: do we need reply tokens? */
     $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();
     if ($eq->format == 'HTML' || $eq->format == 'Both') {
         $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
         $html = CRM_Utils_Token::replaceMailingTokens($html, $mailing, 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::replaceMailingTokens($text, $mailing, NULL, $tokens['text']);
         $message->setTxtBody($text);
     }
     $b = CRM_Utils_Mail::setMimeParams($message);
     $h = $message->headers($headers);
     CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 'a', $eq->job_id, queue_id, $eq->hash);
     $mailer = $config->getMailer();
     if (is_object($mailer)) {
         CRM_Core_Error::ignoreException();
         $mailer->send($to, $h, $b);
         CRM_Core_Error::setCallback();
     }
 }
Пример #18
0
 /**
  * @param object $sort
  * @param string $cacheKey
  * @param int $start
  * @param int $end
  */
 function fillupPrevNextCache($sort, $cacheKey, $start = 0, $end = 500)
 {
     // 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";
     } else {
         $sql = $this->_query->searchQuery($start, $end, $sort, FALSE, FALSE, FALSE, TRUE, TRUE, NULL);
         $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 'civicrm_contact', contact_a.id, contact_a.id, '{$cacheKey}', contact_a.display_name\n";
     $sql = str_replace($replaceSQL, $insertSQL, $sql);
     CRM_Core_Error::ignoreException();
     $result = CRM_Core_DAO::executeQuery($sql);
     CRM_Core_Error::setCallback();
     if (is_a($result, 'DB_Error')) {
         // oops the above query failed, so lets just ignore it
         // and return
         // we print a sorry cant figure it out on view page
         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);
 }
Пример #19
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return void
  */
 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 &raquo; Communications &raquo; 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);
             CRM_Core_Error::ignoreException();
             $result = $mailer->send($toEmail, $headers, $message);
             CRM_Core_Error::setCallback();
             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');
 }
Пример #20
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $formValues = $this->controller->exportValues($this->_name);
     $buttonName = $this->controller->getButtonName();
     // check if test button
     if ($buttonName == $this->_testButtonName) {
         if ($formValues['outBound_option'] == 2) {
             CRM_Core_Session::setStatus(ts('You have selected "Disable Outbound Email". A test email can not be sent.'));
         } else {
             $session =& CRM_Core_Session::singleton();
             $userID = $session->get('userID');
             require_once 'CRM/Contact/BAO/Contact.php';
             list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
             //get the default domain email address.CRM-4250
             require_once 'CRM/Core/BAO/Domain.php';
             list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
             if (!$domainEmailAddress || $domainEmailAddress == '*****@*****.**') {
                 require_once 'CRM/Utils/System.php';
                 $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 &raquo; Configure &raquo; Domain Information</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));
             if ($formValues['outBound_option'] == 0) {
                 $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;
                 }
                 $mailerName = 'smtp';
             } elseif ($formValues['outBound_option'] == 1) {
                 $subject = "Test for Sendmail settings";
                 $message = "Sendmail settings are correct.";
                 $params['sendmail_path'] = $formValues['sendmail_path'];
                 $params['sendmail_args'] = $formValues['sendmail_args'];
                 $mailerName = 'sendmail';
             }
             $headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);
             $mailer =& Mail::factory($mailerName, $params);
             CRM_Core_Error::ignoreException();
             $result = $mailer->send($toEmail, $headers, $message);
             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))));
             } 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);
             }
         }
     }
     $mailingDomain =& new CRM_Core_DAO_Preferences();
     $mailingDomain->domain_id = CRM_Core_Config::domainID();
     $mailingDomain->is_domain = true;
     $mailingDomain->find(true);
     if ($mailingDomain->mailing_backend) {
         $values = unserialize($mailingDomain->mailing_backend);
         CRM_Core_BAO_Setting::formatParams($formValues, $values);
     }
     // if password is present, encrypt it
     if (!empty($formValues['smtpPassword'])) {
         require_once 'CRM/Utils/Crypt.php';
         $formValues['smtpPassword'] = CRM_Utils_Crypt::encrypt($formValues['smtpPassword']);
     }
     $mailingDomain->mailing_backend = serialize($formValues);
     $mailingDomain->save();
 }
Пример #21
0
 static function send(&$params)
 {
     require_once 'CRM/Core/BAO/MailSettings.php';
     $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
     $from = CRM_Utils_Array::value('from', $params);
     if (!$returnPath) {
         $returnPath = self::pluckEmailFromHeader($from);
     }
     $params['returnPath'] = $returnPath;
     // first call the mail alter hook
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::alterMailParams($params);
     // check if any module has aborted mail sending
     if (CRM_Utils_Array::value('abortMailSend', $params) || !CRM_Utils_Array::value('toEmail', $params)) {
         return false;
     }
     $textMessage = CRM_Utils_Array::value('text', $params);
     $htmlMessage = CRM_Utils_Array::value('html', $params);
     $attachments = CRM_Utils_Array::value('attachments', $params);
     $headers = array();
     $headers['From'] = $params['from'];
     $headers['To'] = "{$params['toName']} <{$params['toEmail']}>";
     $headers['Cc'] = CRM_Utils_Array::value('cc', $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);
     $headers['Reply-To'] = CRM_Utils_Array::value('replyTo', $params, $from);
     $headers['Date'] = date('r');
     $to = array($params['toEmail']);
     if (CRM_Utils_Array::value('cc', $params)) {
         $to[] = CRM_Utils_Array::value('cc', $params);
     }
     if (CRM_Utils_Array::value('bcc', $params)) {
         $to[] = CRM_Utils_Array::value('bcc', $params);
     }
     // we need to wrap Mail_mime because PEAR is apparently unable to fix
     // a six-year-old bug (PEAR bug #30) in Mail_mime::_encodeHeaders()
     // this fixes CRM-4631
     require_once 'CRM/Utils/Mail/FixedMailMIME.php';
     $msg = new CRM_Utils_Mail_FixedMailMIME("\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);
     $result = null;
     $mailer =& CRM_Core_Config::getMailer();
     CRM_Core_Error::ignoreException();
     if (is_object($mailer)) {
         $result = $mailer->send($to, $headers, $message);
         CRM_Core_Error::setCallback();
         if (is_a($result, 'PEAR_Error')) {
             $message = self::errorMessage($mailer, $result);
             CRM_Core_Session::setStatus($message, false);
             return false;
         }
         return true;
     }
     return false;
 }
Пример #22
0
 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
     CRM_Core_Error::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')) {
             CRM_Core_Error::setCallback();
             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')) {
             CRM_Core_Error::setCallback();
             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')) {
             CRM_Core_Error::setCallback();
             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')) {
             CRM_Core_Error::setCallback();
             return FALSE;
         }
     }
     CRM_Core_Error::setCallback();
     return TRUE;
 }
Пример #23
0
 static function checkURL($url, $addCookie = false)
 {
     CRM_Core_Error::ignoreException();
     require_once 'HTTP/Request.php';
     $params = array('method' => 'GET');
     $request = new HTTP_Request($url, $params);
     if ($addCookie) {
         foreach ($_COOKIE as $name => $value) {
             $request->addCookie($name, $value);
         }
     }
     $config =& CRM_Core_Config::singleton();
     if ($config->userFramework == 'Standalone') {
         session_write_close();
     }
     $request->sendRequest();
     $result = $request->getResponseCode() == 200 ? true : false;
     if ($config->userFramework == 'Standalone') {
         session_start();
     }
     CRM_Core_Error::setCallback();
     return $result;
 }
Пример #24
0
 static function &dbHandle(&$config)
 {
     CRM_Core_Error::ignoreException();
     $db_uf = DB::connect($config->userFrameworkDSN);
     CRM_Core_Error::setCallback();
     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;
 }
Пример #25
0
 static function checkTriggerViewPermission($view = true)
 {
     // test for create view and trigger permissions and if allowed, add the option to go multilingual
     // and logging
     CRM_Core_Error::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')) {
             CRM_Core_Error::setCallback();
             return false;
         }
     }
     $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
     if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
         CRM_Core_Error::setCallback();
         return false;
     }
     $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
     if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
         CRM_Core_Error::setCallback();
         return false;
     }
     if ($view) {
         $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
         if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
             CRM_Core_Error::setCallback();
             return false;
         }
     }
     CRM_Core_Error::setCallback();
     return true;
 }
Пример #26
0
 /**
  * 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)
  *
  * @access public
  *
  * @return boolean true if a mail was sent, else false
  */
 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 (CRM_Utils_Array::value('abortMailSend', $params) || !CRM_Utils_Array::value('toEmail', $params)) {
         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 (CRM_Utils_Array::value('headers', $params)) {
         $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, $from);
     if (!empty($replyTo)) {
         $headers['Reply-To'] = $replyTo;
     }
     $headers['Date'] = date('r');
     if ($includeMessageId) {
         $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@{$emailDomain}>";
     }
     if (CRM_Utils_Array::value('autoSubmitted', $params)) {
         $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']);
     //get emails from headers, since these are
     //combination of name and email addresses.
     if (CRM_Utils_Array::value('Cc', $headers)) {
         $to[] = CRM_Utils_Array::value('Cc', $headers);
     }
     if (CRM_Utils_Array::value('Bcc', $headers)) {
         $to[] = CRM_Utils_Array::value('Bcc', $headers);
         unset($headers['Bcc']);
     }
     $result = NULL;
     $mailer = CRM_Core_Config::getMailer();
     CRM_Core_Error::ignoreException();
     if (is_object($mailer)) {
         $result = $mailer->send($to, $headers, $message);
         CRM_Core_Error::setCallback();
         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, TRUE);
             return FALSE;
         }
         // CRM-10699
         CRM_Utils_Hook::postEmailSend($params);
         return TRUE;
     }
     return FALSE;
 }
Пример #27
0
 static function createCaseViews()
 {
     $sql = self::createCaseViewsQuery('upcoming');
     CRM_Core_Error::ignoreException();
     $dao = new CRM_Core_DAO();
     $dao->query($sql);
     if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
         CRM_Core_Error::setCallback();
         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');
     CRM_Core_Error::ignoreException();
     $dao->query($sql);
     if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
         CRM_Core_Error::setCallback();
         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;
 }
Пример #28
0
 function buildPrevNextCache($sort)
 {
     //for prev/next pagination
     $crmPID = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
     if (!$crmPID) {
         $cacheKey = "civicrm search {$this->_key}";
         CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey, 'civicrm_contact');
         $sql = $this->_query->searchQuery(0, 0, $sort, FALSE, FALSE, FALSE, FALSE, TRUE, $this->_campaignWhereClause, NULL, $this->_campaignFromClause);
         list($select, $from) = explode(' FROM ', $sql);
         $insertSQL = "\nINSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data )\nSELECT 'civicrm_contact', contact_a.id, contact_a.id, '{$cacheKey}', contact_a.display_name\nFROM {$from}\n";
         CRM_Core_Error::ignoreException();
         $result = CRM_Core_DAO::executeQuery($insertSQL);
         CRM_Core_Error::setCallback();
         if (is_a($result, 'DB_Error')) {
             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);
     }
 }
Пример #29
0
 /**
  * Ask a contact for subscription confirmation (opt-in)
  *
  * @param string $email         The email address
  *
  * @return void
  * @access public
  */
 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 &amp; entities in text mode, so that the links work
     $text = str_replace('&amp;', '&', $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 = $config->getMailer();
     if (is_object($mailer)) {
         CRM_Core_Error::ignoreException();
         $mailer->send($email, $h, $b);
         CRM_Core_Error::setCallback();
     }
 }