Ejemplo n.º 1
0
 function _encodeHeaders($input, $params = array())
 {
     require_once 'CRM/Utils/Rule.php';
     $emailValues = array();
     foreach ($input as $fieldName => $fieldValue) {
         $fieldNames = $emails = array();
         $hasValue = false;
         //multiple email w/ comma separate.
         $fieldValues = explode(',', $fieldValue);
         foreach ($fieldValues as $index => $value) {
             $value = trim($value);
             //might be case we have only email address.
             if (CRM_Utils_Rule::email($value)) {
                 $hasValue = true;
                 $emails[$index] = $value;
                 $fieldNames[$index] = 'FIXME_HACK_FOR_NO_NAME';
             } else {
                 $matches = array();
                 if (preg_match('/^(.*)<([^<]*)>$/', $value, $matches)) {
                     $hasValue = true;
                     $emails[$index] = $matches[2];
                     $fieldNames[$index] = trim($matches[1]);
                 }
             }
         }
         //get formatted values back in input
         if ($hasValue) {
             $input[$fieldName] = implode(',', $fieldNames);
             $emailValues[$fieldName] = implode(',', $emails);
         }
     }
     // encode the email-less headers
     $input = parent::_encodeHeaders($input, $params);
     // add emails back to headers, quoting these headers along the way
     foreach ($emailValues as $fieldName => $value) {
         $emails = explode(',', $value);
         $fieldNames = explode(',', $input[$fieldName]);
         foreach ($fieldNames as $index => &$name) {
             $name = str_replace('\\', '\\\\', $name);
             $name = str_replace('"', '\\"', $name);
             // CRM-5640 -if the name was actually doubly-quoted,
             // strip these(the next line will add them back);
             if (substr($name, 0, 2) == '\\"' && substr($name, -2) == '\\"') {
                 $name = substr($name, 2, -2);
             }
         }
         //combine fieldNames and emails.
         $mergeValues = array();
         foreach ($emails as $index => $email) {
             if ($fieldNames[$index] == 'FIXME_HACK_FOR_NO_NAME') {
                 $mergeValues[] = $email;
             } else {
                 $mergeValues[] = "\"{$fieldNames[$index]}\" <{$email}>";
             }
         }
         //finally get values in.
         $input[$fieldName] = implode(',', $mergeValues);
     }
     return $input;
 }
Ejemplo n.º 2
0
 /**
  * Map civicrm Array to Accounts package field names.
  *
  * @param array $contact
  *          Contact Array as returned from API
  * @param $accountsID
  *
  * @return array|bool
  *   Contact Object/ array as expected by accounts package
  */
 protected function mapToAccounts($contact, $accountsID)
 {
     $new_contact = array("Name" => $contact['display_name'] . " - " . $contact['contact_id'], "FirstName" => $contact['first_name'], "LastName" => $contact['last_name'], "EmailAddress" => CRM_Utils_Rule::email($contact['email']) ? $contact['email'] : '', "ContactNumber" => $contact['contact_id'], "Addresses" => array("Address" => array(array("AddressType" => 'POBOX', "AddressLine1" => $contact['street_address'], "City" => $contact['city'], "PostalCode" => $contact['postal_code']))), "Phones" => array("Phone" => array("PhoneType" => 'DEFAULT', "PhoneNumber" => $contact['phone'])));
     if (!empty($accountsID)) {
         $new_contact['ContactID'] = $accountsID;
     }
     $proceed = TRUE;
     CRM_Accountsync_Hook::accountPushAlterMapped('contact', $contact, $proceed, $new_contact);
     $new_contact = array($new_contact);
     if (!$proceed) {
         return FALSE;
     }
     return $new_contact;
 }
Ejemplo n.º 3
0
 /**
  * global form rule
  *
  * @param array $fields  the input form values
  * @param array $files   the uploaded files if any
  * @param array $options additional user data
  *
  * @return true if no errors, else array of errors
  * @access public
  * @static
  */
 static function formRule($fields, $files, $options)
 {
     $errors = array();
     // if is_email_receipt is set, the receipt message must be non-empty
     if (!empty($fields['is_email_receipt'])) {
         //added for CRM-1348
         $email = trim(CRM_Utils_Array::value('receipt_from_email', $fields));
         if (empty($email) || !CRM_Utils_Rule::email($email)) {
             $errors['receipt_from_email'] = ts('A valid Receipt From Email address must be specified if Email Receipt to Contributor is enabled');
         }
     }
     return $errors;
 }
Ejemplo n.º 4
0
 /**
  * function to check if an error in Core( non-custom fields ) field
  *
  * @param String   $errorMessage   A string containing all the error-fields.
  *
  * @access public
  */
 function isErrorInCoreData($params, &$errorMessage)
 {
     require_once 'CRM/Core/OptionGroup.php';
     foreach ($params as $key => $value) {
         if ($value) {
             $session =& CRM_Core_Session::singleton();
             $dateType = $session->get("dateTypes");
             switch ($key) {
                 case 'birth_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             self::addToErrorMsg(ts('Birth Date'), $errorMessage);
                         }
                     } else {
                         self::addToErrorMsg(ts('Birth-Date'), $errorMessage);
                     }
                     break;
                 case 'deceased_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             self::addToErrorMsg(ts('Deceased Date'), $errorMessage);
                         }
                     } else {
                         self::addToErrorMsg(ts('Deceased Date'), $errorMessage);
                     }
                     break;
                 case 'is_deceased':
                     if (CRM_Utils_String::strtoboolstr($value) === false) {
                         self::addToErrorMsg(ts('Is Deceased'), $errorMessage);
                     }
                     break;
                 case 'gender':
                     if (!self::checkGender($value)) {
                         self::addToErrorMsg(ts('Gender'), $errorMessage);
                     }
                     break;
                 case 'preferred_communication_method':
                     $preffComm = array();
                     $preffComm = explode(',', $value);
                     foreach ($preffComm as $v) {
                         if (!self::in_value(trim($v), CRM_Core_PseudoConstant::pcm())) {
                             self::addToErrorMsg(ts('Preferred Communication Method'), $errorMessage);
                         }
                     }
                     break;
                 case 'preferred_mail_format':
                     if (!array_key_exists(strtolower($value), array_change_key_case(CRM_Core_SelectValues::pmf(), CASE_LOWER))) {
                         self::addToErrorMsg(ts('Preferred Mail Format'), $errorMessage);
                     }
                     break;
                 case 'individual_prefix':
                     if (!self::in_value($value, CRM_Core_PseudoConstant::individualPrefix())) {
                         self::addToErrorMsg(ts('Individual Prefix'), $errorMessage);
                     }
                     break;
                 case 'individual_suffix':
                     if (!self::in_value($value, CRM_Core_PseudoConstant::individualSuffix())) {
                         self::addToErrorMsg(ts('Individual Suffix'), $errorMessage);
                     }
                     break;
                 case 'state_province':
                     if (!empty($value)) {
                         foreach ($value as $stateValue) {
                             if ($stateValue['state_province']) {
                                 if (self::in_value($stateValue['state_province'], CRM_Core_PseudoConstant::stateProvinceAbbreviation()) || self::in_value($stateValue['state_province'], CRM_Core_PseudoConstant::stateProvince())) {
                                     continue;
                                 } else {
                                     self::addToErrorMsg(ts('State / Province'), $errorMessage);
                                 }
                             }
                         }
                     }
                     break;
                 case 'country':
                     if (!empty($value)) {
                         foreach ($value as $stateValue) {
                             if ($stateValue['country']) {
                                 CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', true, 'name', 'is_active');
                                 CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', true, 'iso_code');
                                 $config =& CRM_Core_Config::singleton();
                                 $limitCodes = $config->countryLimit();
                                 //If no country is selected in
                                 //localization then take all countries
                                 if (empty($limitCodes)) {
                                     $limitCodes = $countryIsoCodes;
                                 }
                                 if (self::in_value($stateValue['country'], $limitCodes) || self::in_value($stateValue['country'], CRM_Core_PseudoConstant::country())) {
                                     continue;
                                 } else {
                                     if (self::in_value($stateValue['country'], $countryIsoCodes) || self::in_value($stateValue['country'], $countryNames)) {
                                         self::addToErrorMsg(ts('Country input value is in table but not "available": "This Country is valid but is NOT in the list of Available Countries currently configured for your site. This can be viewed and modifed from Global Settings >> Localization." '), $errorMessage);
                                     } else {
                                         self::addToErrorMsg(ts('Country input value not in country table: "The Country value appears to be invalid. It does not match any value in CiviCRM table of countries."'), $errorMessage);
                                     }
                                 }
                             }
                         }
                     }
                     break;
                 case 'geo_code_1':
                     if (!empty($value)) {
                         foreach ($value as $codeValue) {
                             if ($codeValue['geo_code_1']) {
                                 if (CRM_Utils_Rule::numeric($codeValue['geo_code_1'])) {
                                     continue;
                                 } else {
                                     self::addToErrorMsg(ts('Geo code 1'), $errorMessage);
                                 }
                             }
                         }
                     }
                     break;
                 case 'geo_code_2':
                     if (!empty($value)) {
                         foreach ($value as $codeValue) {
                             if ($codeValue['geo_code_2']) {
                                 if (CRM_Utils_Rule::numeric($codeValue['geo_code_2'])) {
                                     continue;
                                 } else {
                                     self::addToErrorMsg(ts('Geo code 2'), $errorMessage);
                                 }
                             }
                         }
                     }
                     break;
                     //check for any error in email/postal greeting, addressee,
                     //custom email/postal greeting, custom addressee, CRM-4575
                 //check for any error in email/postal greeting, addressee,
                 //custom email/postal greeting, custom addressee, CRM-4575
                 case 'email_greeting':
                     $emailGreetingFilter = array('contact_type' => $this->_contactType, 'greeting_type' => 'email_greeting');
                     if (!self::in_value($value, CRM_Core_PseudoConstant::greeting($emailGreetingFilter))) {
                         self::addToErrorMsg(ts('Email Greeting must be one of the configured format options. Check Administer >> Option Lists >> Email Greetings for valid values'), $errorMessage);
                     }
                     break;
                 case 'postal_greeting':
                     $postalGreetingFilter = array('contact_type' => $this->_contactType, 'greeting_type' => 'postal_greeting');
                     if (!self::in_value($value, CRM_Core_PseudoConstant::greeting($postalGreetingFilter))) {
                         self::addToErrorMsg(ts('Postal Greeting must be one of the configured format options. Check Administer >> Option Lists >> Postal Greetings for valid values'), $errorMessage);
                     }
                     break;
                 case 'addressee':
                     $addresseeFilter = array('contact_type' => $this->_contactType, 'greeting_type' => 'addressee');
                     if (!self::in_value($value, CRM_Core_PseudoConstant::greeting($addresseeFilter))) {
                         self::addToErrorMsg(ts('Addressee must be one of the configured format options. Check Administer >> Option Lists >> Addressee for valid values'), $errorMessage);
                     }
                     break;
                 case 'email_greeting_custom':
                     if (array_key_exists('email_greeting', $params)) {
                         $emailGreetingLabel = key(CRM_Core_OptionGroup::values('email_greeting', true, null, null, 'AND v.name = "Customized"'));
                         if (CRM_Utils_Array::value('email_greeting', $params) != $emailGreetingLabel) {
                             self::addToErrorMsg(ts('Email Greeting - Custom'), $errorMessage);
                         }
                     }
                     break;
                 case 'postal_greeting_custom':
                     if (array_key_exists('postal_greeting', $params)) {
                         $postalGreetingLabel = key(CRM_Core_OptionGroup::values('postal_greeting', true, null, null, 'AND v.name = "Customized"'));
                         if (CRM_Utils_Array::value('postal_greeting', $params) != $postalGreetingLabel) {
                             self::addToErrorMsg(ts('Postal Greeting - Custom'), $errorMessage);
                         }
                     }
                     break;
                 case 'addressee_custom':
                     if (array_key_exists('addressee', $params)) {
                         $addresseeLabel = key(CRM_Core_OptionGroup::values('addressee', true, null, null, 'AND v.name = "Customized"'));
                         if (CRM_Utils_Array::value('addressee', $params) != $addresseeLabel) {
                             self::addToErrorMsg(ts('Addressee - Custom'), $errorMessage);
                         }
                     }
                     break;
                 case 'home_URL':
                     if (CRM_Utils_Rule::url($value) === false) {
                         self::addToErrorMsg(ts('Website'), $errorMessage);
                     }
                     break;
                 case 'do_not_email':
                 case 'do_not_phone':
                 case 'do_not_mail':
                 case 'do_not_sms':
                 case 'do_not_trade':
                     if (CRM_Utils_Rule::boolean($value) == false) {
                         $key = ucwords(str_replace("_", " ", $key));
                         self::addToErrorMsg($key, $errorMessage);
                     }
                     break;
                 case 'email':
                     if (is_array($value)) {
                         foreach ($value as $values) {
                             if (CRM_Utils_Array::value('email', $values) && !CRM_Utils_Rule::email($values['email'])) {
                                 self::addToErrorMsg($key, $errorMessage);
                                 break;
                             }
                         }
                     }
                     break;
                 default:
                     if (is_array($params[$key]) && isset($params[$key]["contact_type"])) {
                         //check for any relationship data ,FIX ME
                         self::isErrorInCoreData($params[$key], $errorMessage);
                     }
             }
         }
     }
 }
Ejemplo n.º 5
0
 /**
  * get the html for the form that represents this particular group
  *
  * @param int     $userID    the user id that we are actually editing
  * @param string  $title     the title of the group we are interested in
  * @param int     $action    the action of the form
  * @param boolean $register  is this the registration form
  * @param boolean $reset     should we reset the form?
  * @param int     $profileID do we have the profile ID?
  *
  * @return string       the html for the form on success, otherwise empty string
  * @static
  * @access public
  */
 static function getEditHTML($userID, $title, $action = null, $register = false, $reset = false, $profileID = null, $doNotProcess = false, $ctype = null)
 {
     require_once "CRM/Core/Controller/Simple.php";
     $session =& CRM_Core_Session::singleton();
     if ($register) {
         $controller =& new CRM_Core_Controller_Simple('CRM_Profile_Form_Dynamic', ts('Dynamic Form Creator'), $action);
         if ($reset || $doNotProcess) {
             // hack to make sure we do not process this form
             $oldQFDefault = CRM_Utils_Array::value('_qf_default', $_POST);
             unset($_POST['_qf_default']);
             unset($_REQUEST['_qf_default']);
             if ($reset) {
                 $controller->reset();
             }
         }
         $controller->set('id', $userID);
         $controller->set('register', 1);
         $controller->set('skipPermission', 1);
         $controller->set('ctype', $ctype);
         $controller->process();
         if ($doNotProcess) {
             $controller->validate();
         }
         $controller->setEmbedded(true);
         //CRM-5839 - though we want to process form, get the control back.
         $controller->setSkipRedirection($doNotProcess ? false : true);
         $controller->run();
         // we are done processing so restore the POST/REQUEST vars
         if (($reset || $doNotProcess) && $oldQFDefault) {
             $_POST['_qf_default'] = $_REQUEST['_qf_default'] = $oldQFDefault;
         }
         $template =& CRM_Core_Smarty::singleton();
         return trim($template->fetch('CRM/Profile/Form/Dynamic.tpl'));
     } else {
         if (!$profileID) {
             // make sure we have a valid group
             $group =& new CRM_Core_DAO_UFGroup();
             $group->title = $title;
             if ($group->find(true)) {
                 $profileID = $group->id;
             }
         }
         if ($profileID) {
             // make sure profileID and ctype match if ctype exists
             if ($ctype) {
                 require_once 'CRM/Core/BAO/UFField.php';
                 $profileType = CRM_Core_BAO_UFField::getProfileType($profileID);
                 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                     $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
                 }
                 if ($profileType != 'Contact' && $profileType != $ctype) {
                     return null;
                 }
             }
             $controller =& new CRM_Core_Controller_Simple('CRM_Profile_Form_Dynamic', ts('Dynamic Form Creator'), $action);
             if ($reset) {
                 $controller->reset();
             }
             $controller->set('gid', $profileID);
             $controller->set('id', $userID);
             $controller->set('register', 0);
             $controller->set('skipPermission', 1);
             if ($ctype) {
                 $controller->set('ctype', $ctype);
             }
             $controller->process();
             $controller->setEmbedded(true);
             //CRM-5846 - give the control back to drupal.
             $controller->setSkipRedirection($doNotProcess ? false : true);
             $controller->run();
             $template =& CRM_Core_Smarty::singleton();
             $templateFile = "CRM/Profile/Form/{$profileID}/Dynamic.tpl";
             if (!$template->template_exists($templateFile)) {
                 $templateFile = "CRM/Profile/Form/Dynamic.tpl";
             }
             return trim($template->fetch($templateFile));
         } else {
             require_once 'CRM/Contact/BAO/Contact/Location.php';
             $userEmail = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
             // if post not empty then only proceed
             if (!empty($_POST)) {
                 // get the new email
                 $config =& CRM_Core_Config::singleton();
                 $email = CRM_Utils_Array::value('mail', $_POST);
                 if (CRM_Utils_Rule::email($email) && $email != $userEmail[1]) {
                     require_once 'CRM/Core/BAO/UFMatch.php';
                     CRM_Core_BAO_UFMatch::updateContactEmail($userID, $email);
                 }
             }
         }
     }
     return '';
 }
Ejemplo n.º 6
0
 /**
  * Get the html for the form that represents this particular group.
  *
  * @param int $userID
  *   The user id that we are actually editing.
  * @param string $title
  *   The title of the group we are interested in.
  * @param int $action
  *   The action of the form.
  * @param bool $register
  *   Is this the registration form.
  * @param bool $reset
  *   Should we reset the form?.
  * @param int $profileID
  *   Do we have the profile ID?.
  *
  * @param bool $doNotProcess
  * @param null $ctype
  *
  * @return string
  *   the html for the form on success, otherwise empty string
  */
 public static function getEditHTML($userID, $title, $action = NULL, $register = FALSE, $reset = FALSE, $profileID = NULL, $doNotProcess = FALSE, $ctype = NULL)
 {
     if ($register) {
         $controller = new CRM_Core_Controller_Simple('CRM_Profile_Form_Dynamic', ts('Dynamic Form Creator'), $action);
         if ($reset || $doNotProcess) {
             // hack to make sure we do not process this form
             $oldQFDefault = CRM_Utils_Array::value('_qf_default', $_POST);
             unset($_POST['_qf_default']);
             unset($_REQUEST['_qf_default']);
             if ($reset) {
                 $controller->reset();
             }
         }
         $controller->set('id', $userID);
         $controller->set('register', 1);
         $controller->set('skipPermission', 1);
         $controller->set('ctype', $ctype);
         $controller->process();
         if ($doNotProcess || !empty($_POST)) {
             $controller->validate();
         }
         $controller->setEmbedded(TRUE);
         //CRM-5839 - though we want to process form, get the control back.
         $controller->setSkipRedirection($doNotProcess ? FALSE : TRUE);
         $controller->run();
         // we are done processing so restore the POST/REQUEST vars
         if (($reset || $doNotProcess) && $oldQFDefault) {
             $_POST['_qf_default'] = $_REQUEST['_qf_default'] = $oldQFDefault;
         }
         $template = CRM_Core_Smarty::singleton();
         // Hide CRM error messages if they are displayed using drupal form_set_error.
         if (!empty($_POST)) {
             $template->assign('suppressForm', TRUE);
         }
         return trim($template->fetch('CRM/Profile/Form/Dynamic.tpl'));
     } else {
         if (!$profileID) {
             // make sure we have a valid group
             $group = new CRM_Core_DAO_UFGroup();
             $group->title = $title;
             if ($group->find(TRUE)) {
                 $profileID = $group->id;
             }
         }
         if ($profileID) {
             // make sure profileID and ctype match if ctype exists
             if ($ctype) {
                 $profileType = CRM_Core_BAO_UFField::getProfileType($profileID);
                 if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                     $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
                 }
                 if ($profileType != 'Contact' && $profileType != $ctype) {
                     return NULL;
                 }
             }
             $controller = new CRM_Core_Controller_Simple('CRM_Profile_Form_Dynamic', ts('Dynamic Form Creator'), $action);
             if ($reset) {
                 $controller->reset();
             }
             $controller->set('gid', $profileID);
             $controller->set('id', $userID);
             $controller->set('register', 0);
             $controller->set('skipPermission', 1);
             if ($ctype) {
                 $controller->set('ctype', $ctype);
             }
             $controller->process();
             $controller->setEmbedded(TRUE);
             //CRM-5846 - give the control back to drupal.
             $controller->setSkipRedirection($doNotProcess ? FALSE : TRUE);
             $controller->run();
             $template = CRM_Core_Smarty::singleton();
             // Hide CRM error messages if they are displayed using drupal form_set_error.
             if (!empty($_POST) && CRM_Core_Config::singleton()->userFramework == 'Drupal') {
                 if (arg(0) == 'user' || arg(0) == 'admin' && arg(1) == 'people') {
                     $template->assign('suppressForm', TRUE);
                 }
             }
             $templateFile = "CRM/Profile/Form/{$profileID}/Dynamic.tpl";
             if (!$template->template_exists($templateFile)) {
                 $templateFile = 'CRM/Profile/Form/Dynamic.tpl';
             }
             return trim($template->fetch($templateFile));
         } else {
             $userEmail = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
             // if post not empty then only proceed
             if (!empty($_POST)) {
                 // get the new email
                 $config = CRM_Core_Config::singleton();
                 $email = CRM_Utils_Array::value('mail', $_POST);
                 if (CRM_Utils_Rule::email($email) && $email != $userEmail[1]) {
                     CRM_Core_BAO_UFMatch::updateContactEmail($userID, $email);
                 }
             }
         }
     }
     return '';
 }
Ejemplo n.º 7
0
 /**
  * Synchronize the object with the UF Match entry. Can be called stand-alone from
  * the drupalUsers script
  *
  * @param Object  $user    the drupal user object
  * @param string  $userKey the id of the user from the uf object
  * @param string  $uniqId    the OpenID of the user
  * @param string  $uf      the name of the user framework
  * @param integer $status  returns the status if user created or already exits (used for CMS sync)
  *
  * @return the ufmatch object that was found or created
  * @access public
  * @static
  */
 static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $status = null, $ctype = null)
 {
     // validate that uniqId is a valid url. it will either be
     // an OpenID (which should always be a valid url) or a
     // http://uf_username/ construction (so that it can
     // be used as an OpenID in the future)
     require_once 'CRM/Utils/Rule.php';
     if ($uf == 'Standalone') {
         if (!CRM_Utils_Rule::url($uniqId)) {
             return $status ? null : false;
         }
     } else {
         if (!CRM_Utils_Rule::email($uniqId)) {
             return $status ? null : false;
         }
     }
     $newContact = false;
     // make sure that a contact id exists for this user id
     $ufmatch =& new CRM_Core_DAO_UFMatch();
     if (CRM_Core_DAO::checkFieldExists('civicrm_uf_match', 'domain_id')) {
         // FIXME: if() condition check was required especially for upgrade cases (2.2.x -> 3.0.x),
         // where folks if happen to logout, would encounter a column not found fatal error
         $ufmatch->domain_id = CRM_Core_Config::domainID();
     }
     $ufmatch->uf_id = $userKey;
     if (!$ufmatch->find(true)) {
         require_once 'CRM/Core/Transaction.php';
         $transaction = new CRM_Core_Transaction();
         if (!empty($_POST)) {
             $params = $_POST;
             $params['email'] = $uniqId;
             require_once 'CRM/Dedupe/Finder.php';
             $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
             $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
             if (!empty($ids)) {
                 $dao = new CRM_Core_DAO();
                 $dao->contact_id = $ids[0];
             }
         } else {
             require_once 'CRM/Contact/BAO/Contact.php';
             if ($uf == 'Standalone') {
                 $dao =& CRM_Contact_BAO_Contact::matchContactOnOpenId($uniqId, $ctype);
             } else {
                 $dao =& CRM_Contact_BAO_Contact::matchContactOnEmail($uniqId, $ctype);
             }
         }
         if ($dao) {
             //print "Found contact with uniqId $uniqId<br/>";
             $ufmatch->contact_id = $dao->contact_id;
             $ufmatch->uf_name = $uniqId;
         } else {
             if ($uf == 'Drupal') {
                 $mail = 'mail';
             } else {
                 $mail = 'email';
             }
             if (is_Object($user)) {
                 $params = array('email-Primary' => $user->{$mail});
             }
             if ($ctype == 'Organization') {
                 $params['organization_name'] = $uniqId;
             } else {
                 if ($ctype == 'Household') {
                     $params['household_name'] = $uniqId;
                 }
             }
             if (!$ctype) {
                 $ctype = "Individual";
             }
             $params['contact_type'] = $ctype;
             // extract first / middle / last name
             // for joomla
             if ($uf == 'Joomla' && $user->name) {
                 require_once 'CRM/Utils/String.php';
                 CRM_Utils_String::extractName($user->name, $params);
             }
             if ($uf == 'Standalone') {
                 $params['openid-Primary'] = $uniqId;
                 //need to delete below code once profile is
                 //exposed on signup page
                 if (!empty($user->first_name) || !empty($user->last_name)) {
                     $params['first_name'] = $user->first_name;
                     $params['last_name'] = $user->last_name;
                 } elseif (!empty($user->name)) {
                     require_once 'CRM/Utils/String.php';
                     CRM_Utils_String::extractName($user->name, $params);
                 }
             }
             $contactId = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray);
             $ufmatch->contact_id = $contactId;
             $ufmatch->uf_name = $uniqId;
         }
         $ufmatch->save();
         $ufmatch->free();
         $newContact = true;
         $transaction->commit();
     }
     if ($status) {
         return $newContact;
     } else {
         return $ufmatch;
     }
 }
Ejemplo n.º 8
0
 /**
  * handle the values in summary mode
  *
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function summary(&$values)
 {
     $response = $this->setActiveFieldValues($values);
     $errorMessage = null;
     $errorRequired = false;
     switch ($this->_contactType) {
         case 'Individual':
             if ($this->_firstNameIndex < 0 && $this->_lastNameIndex < 0) {
                 $errorRequired = true;
                 $errorMessage = ts('Missing required fields:') . ' ' . ts('First Name') . ' ' . ts('and') . ' ' . ts('Last Name');
             } else {
                 $errorRequired = !CRM_Utils_Array::value($this->_firstNameIndex, $values) && !CRM_Utils_Array::value($this->_lastNameIndex, $values);
             }
             break;
         case 'Household':
             if ($this->_householdNameIndex < 0) {
                 $errorRequired = true;
                 $errorMessage = ts('Missing required fields:') . ' ' . ts('Household Name');
             } else {
                 $errorRequired = !CRM_Utils_Array::value($this->_householdNameIndex, $values);
             }
             break;
         case 'Organization':
             if ($this->_organizationNameIndex < 0) {
                 $errorRequired = true;
                 $errorMessage = ts('Missing required fields:') . ' ' . ts('Organization Name');
             } else {
                 $errorRequired = !CRM_Utils_Array::value($this->_organizationNameIndex, $values);
             }
             break;
     }
     $statusFieldName = $this->_statusFieldName;
     if ($this->_emailIndex >= 0) {
         /* If we don't have the required fields, bail */
         if ($this->_contactType == 'Individual' && !$this->_updateWithId) {
             if ($errorRequired && !CRM_Utils_Array::value($this->_emailIndex, $values)) {
                 if ($errorMessage) {
                     $errorMessage .= ' ' . ts('OR') . ' ' . ts('Email Address');
                 } else {
                     $errorMessage = ts('Missing required field:') . ' ' . ts('Email Address');
                 }
                 array_unshift($values, $errorMessage);
                 $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::ERROR;
             }
         }
         $email = CRM_Utils_Array::value($this->_emailIndex, $values);
         if ($email) {
             /* If the email address isn't valid, bail */
             if (!CRM_Utils_Rule::email($email)) {
                 $errorMessage = ts('Invalid Email address');
                 array_unshift($values, $errorMessage);
                 $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
                 $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
                 return CRM_Import_Parser::ERROR;
             }
             /* otherwise, count it and move on */
             $this->_allEmails[$email] = $this->_lineCount;
         }
     } else {
         if ($errorRequired && !$this->_updateWithId) {
             if ($errorMessage) {
                 $errorMessage .= ' ' . ts('OR') . ' ' . ts('Email Address');
             } else {
                 $errorMessage = ts('Missing required field:') . ' ' . ts('Email Address');
             }
             array_unshift($values, $errorMessage);
             $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             return CRM_Import_Parser::ERROR;
         }
     }
     //check for duplicate external Identifier
     $externalID = CRM_Utils_Array::value($this->_externalIdentifierIndex, $values);
     if ($externalID) {
         /* If it's a dupe,external Identifier  */
         if ($externalDupe = CRM_Utils_Array::value($externalID, $this->_allExternalIdentifiers)) {
             $errorMessage = ts('External Identifier conflicts with record %1', array(1 => $externalDupe));
             array_unshift($values, $errorMessage);
             $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage);
             $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
             return CRM_Import_Parser::ERROR;
         }
         //otherwise, count it and move on
         $this->_allExternalIdentifiers[$externalID] = $this->_lineCount;
     }
     //Checking error in custom data
     $params =& $this->getActiveFieldParams();
     $params['contact_type'] = $this->_contactType;
     //date-format part ends
     $errorMessage = null;
     //checking error in custom data
     $this->isErrorInCustomData($params, $errorMessage);
     //checking error in core data
     $this->isErrorInCoreData($params, $errorMessage);
     if ($errorMessage) {
         $tempMsg = "Invalid value for field(s) : {$errorMessage}";
         // put the error message in the import record in the DB
         $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $tempMsg);
         $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
         array_unshift($values, $tempMsg);
         $errorMessage = null;
         return CRM_Import_Parser::ERROR;
     }
     //if user correcting errors by walking back
     //need to reset status ERROR msg to null
     //now currently we are having valid data.
     $importRecordParams = array($statusFieldName => 'NEW');
     $this->updateImportRecord($values[count($values) - 1], $importRecordParams);
     return CRM_Import_Parser::VALID;
 }
Ejemplo n.º 9
0
 /**  
  * global form rule  
  *  
  * @param array $fields the input form values  
  * @param array $files  the uploaded files if any  
  * @param array $self   current form object. 
  *  
  * @return array array of errors / empty array.   
  * @access public  
  * @static  
  */
 static function formRule(&$fields, &$files, $self)
 {
     $errors = array();
     if ($self->_gName == 'from_email_address') {
         require_once 'CRM/Utils/Mail.php';
         $formEmail = CRM_Utils_Mail::pluckEmailFromHeader($fields['label']);
         if (!CRM_Utils_Rule::email($formEmail)) {
             $errors['label'] = ts('Please enter the valid email address.');
         }
         $formName = explode('"', $fields['label']);
         if (!CRM_Utils_Array::value(1, $formName) || count($formName) != 3) {
             $errors['label'] = ts('Please follow the proper format for From Email Address');
         }
     }
     return $errors;
 }
Ejemplo n.º 10
0
 /**
  * Form rule to send out a test mailing.
  *
  * @param array $params     Array of the form values
  * @param array $files      Any files posted to the form
  * @param array $self       an current this object
  *
  * @return boolean          true on succesful SMTP handoff
  * @access public
  */
 static function &testMail($testParams, $files, $self)
 {
     $error = NULL;
     $urlString = 'civicrm/mailing/send';
     $urlParams = "_qf_Test_display=true&qfKey={$testParams['qfKey']}";
     $ssID = $self->get('ssID');
     if ($ssID && $self->_searchBasedMailing) {
         if ($self->_action == CRM_Core_Action::BASIC) {
             $fragment = 'search';
         } elseif ($self->_action == CRM_Core_Action::PROFILE) {
             $fragment = 'search/builder';
         } elseif ($self->_action == CRM_Core_Action::ADVANCED) {
             $fragment = 'search/advanced';
         } else {
             $fragment = 'search/custom';
         }
         $urlString = 'civicrm/contact/' . $fragment;
     }
     $emails = NULL;
     if (CRM_Utils_Array::value('sendtest', $testParams)) {
         if (!($testParams['test_group'] || $testParams['test_email'])) {
             CRM_Core_Session::setStatus(ts('Your did not provided any email address or selected any group. No test mail is sent.'));
             $error = TRUE;
         }
         if ($testParams['test_email']) {
             $emailAdd = explode(',', $testParams['test_email']);
             foreach ($emailAdd as $key => $value) {
                 $email = trim($value);
                 $testParams['emails'][] = $email;
                 $emails .= $emails ? ",'{$email}'" : "'{$email}'";
                 if (!CRM_Utils_Rule::email($email)) {
                     CRM_Core_Session::setStatus(ts('Please enter valid email addresses only.'));
                     $error = TRUE;
                 }
             }
         }
         if ($error) {
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
             return $error;
         }
     }
     if (CRM_Utils_Array::value('_qf_Test_submit', $testParams)) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         if ($ssID && $self->_searchBasedMailing) {
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("Your mailing has been saved. You can continue later by clicking the 'Continue' action to resume working on it.<br /> From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             CRM_Core_Session::setStatus($status);
             //replace user context to search.
             $context = $self->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}&qfKey={$testParams['qfKey']}";
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
         } else {
             $status = ts("Your mailing has been saved. Click the 'Continue' action to resume working on it.");
             CRM_Core_Session::setStatus($status);
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (CRM_Mailing_Info::workflowEnabled()) {
         if (!CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings')) {
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (CRM_Utils_Array::value('_qf_Import_refresh', $_POST) || CRM_Utils_Array::value('_qf_Test_next', $testParams) || !CRM_Utils_Array::value('sendtest', $testParams)) {
         $error = TRUE;
         return $error;
     }
     $job = new CRM_Mailing_BAO_Job();
     $job->mailing_id = $self->get('mailing_id');
     $job->is_test = TRUE;
     $job->save();
     $newEmails = NULL;
     $session = CRM_Core_Session::singleton();
     if (!empty($testParams['emails'])) {
         $query = "\n                      SELECT id, contact_id, email  \n                      FROM civicrm_email  \n                      WHERE civicrm_email.email IN ({$emails})";
         $dao = CRM_Core_DAO::executeQuery($query);
         $emailDetail = array();
         // fetch contact_id and email id for all existing emails
         while ($dao->fetch()) {
             $emailDetail[$dao->email] = array('contact_id' => $dao->contact_id, 'email_id' => $dao->id);
         }
         $dao->free();
         foreach ($testParams['emails'] as $key => $email) {
             $email = trim($email);
             $contactId = $emailId = NULL;
             if (array_key_exists($email, $emailDetail)) {
                 $emailId = $emailDetail[$email]['email_id'];
                 $contactId = $emailDetail[$email]['contact_id'];
             }
             if (!$contactId) {
                 //create new contact.
                 $params = array('contact_type' => 'Individual', 'email' => array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => 1)));
                 $contact = CRM_Contact_BAO_Contact::create($params);
                 $emailId = $contact->email[0]->id;
                 $contactId = $contact->id;
                 $contact->free();
             }
             $params = array('job_id' => $job->id, 'email_id' => $emailId, 'contact_id' => $contactId);
             CRM_Mailing_Event_BAO_Queue::create($params);
         }
     }
     $testParams['job_id'] = $job->id;
     $isComplete = FALSE;
     while (!$isComplete) {
         $isComplete = CRM_Mailing_BAO_Job::runJobs($testParams);
     }
     if (CRM_Utils_Array::value('sendtest', $testParams)) {
         $status = ts('Your test message has been sent.');
         if (CRM_Mailing_Info::workflowEnabled()) {
             if (CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings') || CRM_Core_Permission::check('access CiviMail')) {
                 $status .= ts(" Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
             }
         } else {
             $status .= ts(" Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
         }
         CRM_Core_Session::setStatus($status);
         $url = CRM_Utils_System::url($urlString, $urlParams);
         CRM_Utils_System::redirect($url);
     }
     $error = TRUE;
     return $error;
 }
Ejemplo n.º 11
0
 function emailList($list, $checkDomain = false)
 {
     $emails = explode(',', $list);
     foreach ($emails as $email) {
         $email = trim($email);
         if (!CRM_Utils_Rule::email($email, $checkDomain)) {
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 12
0
 /**
  * global form rule
  *
  * @param array $fields the input form values
  * @param array $files  the uploaded files if any
  * @param array $self   current form object.
  *
  * @return array array of errors / empty array.
  * @access public
  * @static
  */
 static function formRule($fields, $files, $self)
 {
     $errors = array();
     if ($self->_gName == 'case_status' && !CRM_Utils_Array::value('grouping', $fields)) {
         $errors['grouping'] = ts('Status class is a required field');
     }
     if (in_array($self->_gName, array('email_greeting', 'postal_greeting', 'addressee')) && !CRM_Utils_Array::value('is_reserved', $self->_defaultValues)) {
         $label = $fields['label'];
         $condition = " AND v.label = '{$label}' ";
         $values = CRM_Core_OptionGroup::values($self->_gName, FALSE, FALSE, FALSE, $condition, 'filter');
         $checkContactOptions = TRUE;
         if ($self->_id && $self->_defaultValues['contactOptions'] == $fields['contactOptions']) {
             $checkContactOptions = FALSE;
         }
         if ($checkContactOptions && in_array($fields['contactOptions'], $values)) {
             $errors['label'] = ts('This Label already exists in the database for the selected contact type.');
         }
     }
     if ($self->_gName == 'from_email_address') {
         $formEmail = CRM_Utils_Mail::pluckEmailFromHeader($fields['label']);
         if (!CRM_Utils_Rule::email($formEmail)) {
             $errors['label'] = ts('Please enter the valid email address.');
         }
         $formName = explode('"', $fields['label']);
         if (!CRM_Utils_Array::value(1, $formName) || count($formName) != 3) {
             $errors['label'] = ts('Please follow the proper format for From Email Address');
         }
     }
     return $errors;
 }
 /**
  * handler for dl requests
  */
 static function processDl()
 {
     $config = self::getConfig();
     global $http_return_code;
     /* run this puppy through premailer */
     // DS: not sure why we need premailer as it always sends out mobile (inline) layout.
     // Lets disable it till we figure out why we need it.
     //$premailer = Premailer::html( $_POST[ "html" ], true, "hpricot", $config['BASE_URL'] );
     //$html = $premailer[ "html" ];
     $html = $_POST["html"];
     /* create static versions of resized images */
     $matches = [];
     $num_full_pattern_matches = preg_match_all('#<img.*?src="([^"]*?\\/[^/]*\\.[^"]+)#i', $html, $matches);
     for ($i = 0; $i < $num_full_pattern_matches; $i++) {
         if (preg_match('#/img/(\\?|&amp;)src=#i', $matches[1][$i])) {
             $src_matches = [];
             if (preg_match('#/img/(\\?|&amp;)src=(.*)&amp;method=(.*)&amp;params=(.*)#i', $matches[1][$i], $src_matches) !== FALSE) {
                 $file_name = urldecode($src_matches[2]);
                 $file_name = substr($file_name, strlen($config['BASE_URL']));
                 $method = urldecode($src_matches[3]);
                 $params = urldecode($src_matches[4]);
                 $params = explode(",", $params);
                 $width = (int) $params[0];
                 $height = (int) $params[1];
                 $static_file_name = $method . "_" . $width . "x" . $height . "_" . $file_name;
                 $html = str_ireplace($matches[1][$i], $config['BASE_URL'] . $config['STATIC_URL'] . rawurlencode($static_file_name), $html);
                 //Changed to rawurlencode because space gets into + in the image file name if it has space
                 $image = self::resizeImage($file_name, $method, $width, $height);
                 $image->writeImage($config['BASE_DIR'] . $config['STATIC_DIR'] . $static_file_name);
             }
         }
     }
     /* perform the requested action */
     switch (CRM_Utils_Type::escape($_POST['action'], 'String')) {
         case "download":
             // download
             header("Content-Type: application/force-download");
             header("Content-Disposition: attachment; filename=\"" . $_POST["filename"] . "\"");
             header("Content-Length: " . strlen($html));
             echo $html;
             break;
         case "save":
             $result = array();
             $msgTplId = NULL;
             $hashKey = CRM_Utils_Type::escape($_POST['key'], 'String');
             if (!$hashKey) {
                 CRM_Core_Session::setStatus(ts('Mosaico hask key not found...'));
                 return FALSE;
             }
             $mosTpl = new CRM_Mosaico_DAO_MessageTemplate();
             $mosTpl->hash_key = $hashKey;
             if ($mosTpl->find(TRUE)) {
                 $msgTplId = $mosTpl->msg_tpl_id;
             }
             $name = "Mosaico Template " . date('d-m-Y H:i:s');
             if (CRM_Utils_Type::escape($_POST['name'], 'String')) {
                 $name = $_POST['name'];
             }
             // save to message templates
             $messageTemplate = array('msg_html' => $html, 'is_active' => TRUE);
             $messageTemplate['msg_title'] = $messageTemplate['msg_subject'];
             if ($msgTplId) {
                 $messageTemplate['id'] = $msgTplId;
             }
             $messageTemplate['msg_title'] = $messageTemplate['msg_subject'] = $name;
             $msgTpl = CRM_Core_BAO_MessageTemplate::add($messageTemplate);
             $mosaicoTemplate = array('msg_tpl_id' => $msgTpl->id, 'hash_key' => $hashKey, 'name' => $name, 'html' => $_POST['html'], 'metadata' => $_POST['metadata'], 'template' => $_POST['template']);
             $mosTpl = new CRM_Mosaico_DAO_MessageTemplate();
             $mosTpl->msg_tpl_id = $msgTpl->id;
             $mosTpl->hash_key = $hashKey;
             $mosTpl->find(TRUE);
             $mosTpl->copyValues($mosaicoTemplate);
             $mosTpl->save();
             if ($mosTpl->id) {
                 $result['id'] = $mosTpl->id;
             }
             CRM_Utils_JSON::output($result);
             break;
         case "email":
             $result = array();
             if (!CRM_Utils_Rule::email($_POST['rcpt'])) {
                 CRM_Core_Session::setStatus('Recipient Email address not found');
                 return FALSE;
             }
             $to = $_POST['rcpt'];
             $subject = CRM_Utils_Type::escape($_POST['subject'], 'String');
             list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
             $mailParams = array('from' => $domainEmailAddress, 'toName' => 'Test Recipient', 'toEmail' => $to, 'subject' => $subject, 'html' => $html);
             $sent = FALSE;
             if (CRM_Utils_Mail::send($mailParams)) {
                 $result['sent'] = TRUE;
                 CRM_Utils_JSON::output($result);
             } else {
                 CRM_Utils_JSON::output($result);
                 return FALSE;
             }
             break;
     }
     CRM_Utils_System::civiExit();
 }
Ejemplo n.º 14
0
 /**
  * Synchronize the object with the UF Match entry. Can be called stand-alone from
  * the drupalUsers script
  *
  * @param Object $user
  *   The drupal user object.
  * @param string $userKey
  *   The id of the user from the uf object.
  * @param string $uniqId
  *   The OpenID of the user.
  * @param string $uf
  *   The name of the user framework.
  * @param int $status
  *   Returns the status if user created or already exits (used for CMS sync).
  * @param string $ctype
  *   contact type
  * @param bool $isLogin
  *
  * @return CRM_Core_DAO_UFMatch|bool
  */
 public static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $status = NULL, $ctype = NULL, $isLogin = FALSE)
 {
     $config = CRM_Core_Config::singleton();
     if (!CRM_Utils_Rule::email($uniqId)) {
         $retVal = $status ? NULL : FALSE;
         return $retVal;
     }
     $newContact = FALSE;
     // make sure that a contact id exists for this user id
     $ufmatch = new CRM_Core_DAO_UFMatch();
     $ufmatch->domain_id = CRM_Core_Config::domainID();
     $ufmatch->uf_id = $userKey;
     if (!$ufmatch->find(TRUE)) {
         $transaction = new CRM_Core_Transaction();
         $dao = NULL;
         if (!empty($_POST) && !$isLogin) {
             $params = $_POST;
             $params['email'] = $uniqId;
             $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
             $dedupeParams['check_permission'] = FALSE;
             $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
             if (!empty($ids) && Civi::settings()->get('uniq_email_per_site')) {
                 // restrict dupeIds to ones that belong to current domain/site.
                 $siteContacts = CRM_Core_BAO_Domain::getContactList();
                 foreach ($ids as $index => $dupeId) {
                     if (!in_array($dupeId, $siteContacts)) {
                         unset($ids[$index]);
                     }
                 }
                 // re-index the array
                 $ids = array_values($ids);
             }
             if (!empty($ids)) {
                 $dao = new CRM_Core_DAO();
                 $dao->contact_id = $ids[0];
             }
         } else {
             $dao = CRM_Contact_BAO_Contact::matchContactOnEmail($uniqId, $ctype);
         }
         $found = FALSE;
         if ($dao) {
             // ensure there does not exists a contact_id / uf_id pair
             // in the DB. This might be due to multiple emails per contact
             // CRM-9091
             $sql = "\nSELECT id\nFROM   civicrm_uf_match\nWHERE  contact_id = %1\nAND    domain_id = %2\n";
             $params = array(1 => array($dao->contact_id, 'Integer'), 2 => array(CRM_Core_Config::domainID(), 'Integer'));
             $conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
             if (!$conflict) {
                 $found = TRUE;
                 $ufmatch->contact_id = $dao->contact_id;
                 $ufmatch->uf_name = $uniqId;
             }
         }
         if (!$found) {
             if ($config->userSystem->is_drupal) {
                 $mail = 'mail';
             } elseif ($uf == 'WordPress') {
                 $mail = 'user_email';
             } else {
                 $mail = 'email';
             }
             if (is_object($user)) {
                 $params = array('email-Primary' => $user->{$mail});
             }
             if ($ctype == 'Organization') {
                 $params['organization_name'] = $uniqId;
             } elseif ($ctype == 'Household') {
                 $params['household_name'] = $uniqId;
             }
             if (!$ctype) {
                 $ctype = "Individual";
             }
             $params['contact_type'] = $ctype;
             // extract first / middle / last name
             // for joomla
             if ($uf == 'Joomla' && $user->name) {
                 CRM_Utils_String::extractName($user->name, $params);
             }
             if ($uf == 'WordPress') {
                 if ($user->first_name) {
                     $params['first_name'] = $user->first_name;
                 }
                 if ($user->last_name) {
                     $params['last_name'] = $user->last_name;
                 }
             }
             $contactId = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray);
             $ufmatch->contact_id = $contactId;
             $ufmatch->uf_name = $uniqId;
         }
         // check that there are not two CMS IDs matching the same CiviCRM contact - this happens when a civicrm
         // user has two e-mails and there is a cms match for each of them
         // the gets rid of the nasty fata error but still reports the error
         $sql = "\nSELECT uf_id\nFROM   civicrm_uf_match\nWHERE  ( contact_id = %1\nOR     uf_name      = %2\nOR     uf_id        = %3 )\nAND    domain_id    = %4\n";
         $params = array(1 => array($ufmatch->contact_id, 'Integer'), 2 => array($ufmatch->uf_name, 'String'), 3 => array($ufmatch->uf_id, 'Integer'), 4 => array($ufmatch->domain_id, 'Integer'));
         $conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
         if (!$conflict) {
             $ufmatch = CRM_Core_BAO_UFMatch::create((array) $ufmatch);
             $ufmatch->free();
             $newContact = TRUE;
             $transaction->commit();
         } else {
             $msg = ts("Contact ID %1 is a match for %2 user %3 but has already been matched to %4", array(1 => $ufmatch->contact_id, 2 => $uf, 3 => $ufmatch->uf_id, 4 => $conflict));
             unset($conflict);
         }
     }
     if ($status) {
         return $newContact;
     } else {
         return $ufmatch;
     }
 }
Ejemplo n.º 15
0
 /**
  * handle the values in summary mode
  *
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function summary(&$values)
 {
     $response = $this->setActiveFieldValues($values);
     $errorRequired = false;
     switch ($this->_contactType) {
         case 'Individual':
             if ($this->_firstNameIndex < 0 || $this->_lastNameIndex < 0) {
                 $errorRequired = true;
             } else {
                 $errorRequired = !CRM_Utils_Array::value($this->_firstNameIndex, $values) && !CRM_Utils_Array::value($this->_lastNameIndex, $values);
             }
             break;
         case 'Household':
             if ($this->_householdNameIndex < 0) {
                 $errorRequired = true;
             } else {
                 $errorRequired = !CRM_Utils_Array::value($this->_householdNameIndex, $values);
             }
             break;
         case 'Organization':
             if ($this->_organizationNameIndex < 0) {
                 $errorRequired = true;
             } else {
                 $errorRequired = !CRM_Utils_Array::value($this->_organizationNameIndex, $values);
             }
             break;
     }
     if ($this->_emailIndex >= 0) {
         /* If we don't have the required fields, bail */
         if ($this->_contactType == 'Individual' && !$this->_updateWithId) {
             if ($errorRequired && !CRM_Utils_Array::value($this->_emailIndex, $values)) {
                 array_unshift($values, ts('Missing required fields'));
                 return CRM_IMPORT_PARSER_ERROR;
             }
         }
         $email = CRM_Utils_Array::value($this->_emailIndex, $values);
         if ($email) {
             /* If the email address isn't valid, bail */
             if (!CRM_Utils_Rule::email($email)) {
                 array_unshift($values, ts('Invalid Email address'));
                 return CRM_IMPORT_PARSER_ERROR;
             }
             /* If it's a dupe, bail */
             if ($dupe = CRM_Utils_Array::value($email, $this->_allEmails)) {
                 array_unshift($values, ts('Email address conflicts with record %1', array(1 => $dupe)));
                 return CRM_IMPORT_PARSER_CONFLICT;
             }
             /* otherwise, count it and move on */
             $this->_allEmails[$email] = $this->_lineCount;
         }
     } else {
         if ($errorRequired && !$this->_updateWithId) {
             array_unshift($values, ts('Missing required fields'));
             return CRM_IMPORT_PARSER_ERROR;
         }
     }
     //checking error in custom data
     $params =& $this->getActiveFieldParams();
     $params['contact_type'] = $this->_contactType;
     //date-format part
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateType");
     $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type']);
     foreach ($params as $key => $val) {
         if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
             if ($customFields[$customFieldID][2] == 'Date') {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             }
         }
         if ($key == 'birth_date') {
             if ($val) {
                 CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
             }
         }
     }
     //date-format part ends
     $errorMessage = null;
     //checking error in custom data
     $this->isErrorInCustomData($params, $errorMessage);
     //checking error in core data
     $this->isErrorInCoreData($params, $errorMessage);
     if ($errorMessage) {
         $tempMsg = "Invalid value for field(s) : {$errorMessage}";
         array_unshift($values, $tempMsg);
         $errorMessage = null;
         return CRM_IMPORT_PARSER_ERROR;
     }
     return CRM_IMPORT_PARSER_VALID;
 }
Ejemplo n.º 16
0
 /**
  * get the html for the form that represents this particular group
  *
  * @param int     $userID    the user id that we are actually editing
  * @param string  $title     the title of the group we are interested in
  * @param int     $action    the action of the form
  * @param boolean $register  is this the registration form
  * @param boolean $reset     should we reset the form?
  * @param int     $profileID do we have the profile ID?
  *
  * @return string       the html for the form on success, otherwise empty string
  * @static
  * @access public
  */
 function getEditHTML($userID, $title, $action = null, $register = false, $reset = false, $profileID = null)
 {
     $session =& CRM_Core_Session::singleton();
     if ($register) {
         $controller =& new CRM_Core_Controller_Simple('CRM_Profile_Form_Dynamic', ts('Dynamic Form Creator'), $action);
         if ($reset) {
             // hack to make sure we do not process this form
             $oldQFDefault = $_POST['_qf_default'];
             unset($_POST['_qf_default']);
             unset($_REQUEST['_qf_default']);
             $controller->reset();
         }
         $controller->set('id', $userID);
         $controller->set('register', 1);
         $controller->process();
         $controller->setEmbedded(true);
         $controller->run();
         // we are done processing so restore the POST/REQUEST vars
         if ($reset) {
             $_POST['_qf_default'] = $_REQUEST['_qf_default'] = $oldQFDefault;
         }
         $template =& CRM_Core_Smarty::singleton();
         return trim($template->fetch('CRM/Profile/Form/Dynamic.tpl'));
     } else {
         if (!$profileID) {
             // make sure we have a valid group
             $group =& new CRM_Core_DAO_UFGroup();
             $group->title = $title;
             $group->domain_id = CRM_Core_Config::domainID();
             if ($group->find(true)) {
                 $profileID = $group->id;
             }
         }
         if ($profileID) {
             require_once 'CRM/Core/Controller/Simple.php';
             $controller =& new CRM_Core_Controller_Simple('CRM_Profile_Form_Dynamic', ts('Dynamic Form Creator'), $action);
             if ($reset) {
                 $controller->reset();
             }
             $controller->set('gid', $profileID);
             $controller->set('id', $userID);
             $controller->set('register', 0);
             $controller->process();
             $controller->setEmbedded(true);
             $controller->run();
             $template =& CRM_Core_Smarty::singleton();
             return trim($template->fetch('CRM/Profile/Form/Dynamic.tpl'));
         } else {
             // fix for CRM 701
             require_once 'CRM/Contact/BAO/Contact.php';
             $userEmail = CRM_Contact_BAO_Contact::getEmailDetails($userID);
             // if post not empty then only proceed
             if (!empty($_POST)) {
                 if (CRM_Utils_Rule::email($_POST['edit']['mail']) && $_POST['edit']['mail'] != $userEmail[1]) {
                     require_once 'CRM/Core/BAO/UFMatch.php';
                     CRM_Core_BAO_UFMatch::updateContactEmail($userID, $_POST['edit']['mail']);
                 }
             }
         }
     }
     return '';
 }
Ejemplo n.º 17
0
 /**
  * Synchronize the object with the UF Match entry. Can be called stand-alone from
  * the drupalUsers script
  *
  * @param Object  $user    the drupal user object
  * @param string  $userKey the id of the user from the uf object
  * @param string  $uniqId    the OpenID of the user
  * @param string  $uf      the name of the user framework
  * @param integer $status  returns the status if user created or already exits (used for CMS sync)
  *
  * @return the ufmatch object that was found or created
  * @access public
  * @static
  */
 static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $status = null, $ctype = null, $isLogin = false)
 {
     // validate that uniqId is a valid url. it will either be
     // an OpenID (which should always be a valid url) or a
     // http://uf_username/ construction (so that it can
     // be used as an OpenID in the future)
     require_once 'CRM/Utils/Rule.php';
     if ($uf == 'Standalone') {
         if (!CRM_Utils_Rule::url($uniqId)) {
             return $status ? null : false;
         }
     } else {
         if (!CRM_Utils_Rule::email($uniqId)) {
             return $status ? null : false;
         }
     }
     $newContact = false;
     // make sure that a contact id exists for this user id
     $ufmatch =& new CRM_Core_DAO_UFMatch();
     if (CRM_Core_DAO::checkFieldExists('civicrm_uf_match', 'domain_id')) {
         // FIXME: if() condition check was required especially for upgrade cases (2.2.x -> 3.0.x),
         // where folks if happen to logout, would encounter a column not found fatal error
         $ufmatch->domain_id = CRM_Core_Config::domainID();
     }
     $ufmatch->uf_id = $userKey;
     if (!$ufmatch->find(true)) {
         require_once 'CRM/Core/Transaction.php';
         $transaction = new CRM_Core_Transaction();
         if (!empty($_POST) && !$isLogin) {
             $params = $_POST;
             $params['email'] = $uniqId;
             require_once 'CRM/Dedupe/Finder.php';
             $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
             $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual');
             if (!empty($ids) && defined('CIVICRM_UNIQ_EMAIL_PER_SITE') && CIVICRM_UNIQ_EMAIL_PER_SITE) {
                 // restrict dupeIds to ones that belong to current domain/site.
                 require_once 'CRM/Core/BAO/Domain.php';
                 $siteContacts = CRM_Core_BAO_Domain::getContactList();
                 foreach ($ids as $index => $dupeId) {
                     if (!in_array($dupeId, $siteContacts)) {
                         unset($ids[$index]);
                     }
                 }
                 $ids = array_values($ids);
                 //re-index the array
             }
             if (!empty($ids)) {
                 $dao = new CRM_Core_DAO();
                 $dao->contact_id = $ids[0];
             }
         } else {
             require_once 'CRM/Contact/BAO/Contact.php';
             if ($uf == 'Standalone') {
                 $dao =& CRM_Contact_BAO_Contact::matchContactOnOpenId($uniqId, $ctype);
             } else {
                 $dao =& CRM_Contact_BAO_Contact::matchContactOnEmail($uniqId, $ctype);
             }
         }
         if ($dao) {
             //print "Found contact with uniqId $uniqId<br/>";
             $ufmatch->contact_id = $dao->contact_id;
             $ufmatch->uf_name = $uniqId;
         } else {
             if ($uf == 'Drupal') {
                 $mail = 'mail';
             } else {
                 $mail = 'email';
             }
             if (is_Object($user)) {
                 $params = array('email-Primary' => $user->{$mail});
             }
             if ($ctype == 'Organization') {
                 $params['organization_name'] = $uniqId;
             } else {
                 if ($ctype == 'Household') {
                     $params['household_name'] = $uniqId;
                 }
             }
             if (!$ctype) {
                 $ctype = "Individual";
             }
             $params['contact_type'] = $ctype;
             // extract first / middle / last name
             // for joomla
             if ($uf == 'Joomla' && $user->name) {
                 require_once 'CRM/Utils/String.php';
                 CRM_Utils_String::extractName($user->name, $params);
             }
             if ($uf == 'Standalone') {
                 $params['openid-Primary'] = $uniqId;
                 //need to delete below code once profile is
                 //exposed on signup page
                 if (!empty($user->first_name) || !empty($user->last_name)) {
                     $params['first_name'] = $user->first_name;
                     $params['last_name'] = $user->last_name;
                 } elseif (!empty($user->name)) {
                     require_once 'CRM/Utils/String.php';
                     CRM_Utils_String::extractName($user->name, $params);
                 }
             }
             $contactId = CRM_Contact_BAO_Contact::createProfileContact($params, CRM_Core_DAO::$_nullArray);
             $ufmatch->contact_id = $contactId;
             $ufmatch->uf_name = $uniqId;
         }
         // check that there are not two CMS IDs matching the same CiviCRM contact - this happens when a civicrm
         // user has two e-mails and there is a cms match for each of them
         // the gets rid of the nasty fata error but still reports the error
         $sql = "\nSELECT uf_id\nFROM   civicrm_uf_match\nWHERE  ( contact_id = %1\nOR     uf_name      = %2\nOR     uf_id        = %3 )\nAND    domain_id    = %4\n";
         $params = array(1 => array($ufmatch->contact_id, 'Integer'), 2 => array($ufmatch->uf_name, 'String'), 3 => array($ufmatch->uf_id, 'Integer'), 4 => array($ufmatch->domain_id, 'Integer'));
         require_once 'CRM/Core/DAO.php';
         $conflict = CRM_Core_DAO::singleValueQuery($sql, $params);
         if (!$conflict) {
             $ufmatch->save();
             $ufmatch->free();
             $newContact = true;
             $transaction->commit();
         } else {
             $msg = ts("Contact ID %1 is a match for %2 user %3 but has already been matched to %4", array(1 => $ufmatch->contact_id, 2 => $uf, 3 => $ufmatch->uf_id, 4 => $conflict));
             unset($conflict);
         }
     }
     if ($status) {
         return $newContact;
     } else {
         return $ufmatch;
     }
 }
Ejemplo n.º 18
0
/**
 * Validate a formatted contact parameter list.
 *
 * @param array $params
 *   Structured parameter list (as in crm_format_params).
 *
 * @return bool|CRM_Core_Error
 */
function _civicrm_api3_deprecated_validate_formatted_contact(&$params)
{
    // Look for offending email addresses
    if (array_key_exists('email', $params)) {
        foreach ($params['email'] as $count => $values) {
            if (!is_array($values)) {
                continue;
            }
            if ($email = CRM_Utils_Array::value('email', $values)) {
                // validate each email
                if (!CRM_Utils_Rule::email($email)) {
                    return civicrm_api3_create_error('No valid email address');
                }
                // check for loc type id.
                if (empty($values['location_type_id'])) {
                    return civicrm_api3_create_error('Location Type Id missing.');
                }
            }
        }
    }
    // Validate custom data fields
    if (array_key_exists('custom', $params) && is_array($params['custom'])) {
        foreach ($params['custom'] as $key => $custom) {
            if (is_array($custom)) {
                foreach ($custom as $fieldId => $value) {
                    $valid = CRM_Core_BAO_CustomValue::typecheck(CRM_Utils_Array::value('type', $value), CRM_Utils_Array::value('value', $value));
                    if (!$valid && $value['is_required']) {
                        return civicrm_api3_create_error('Invalid value for custom field \'' . CRM_Utils_Array::value('name', $custom) . '\'');
                    }
                    if (CRM_Utils_Array::value('type', $custom) == 'Date') {
                        $params['custom'][$key][$fieldId]['value'] = str_replace('-', '', $params['custom'][$key][$fieldId]['value']);
                    }
                }
            }
        }
    }
    return civicrm_api3_create_success(TRUE);
}
Ejemplo n.º 19
0
 /**
  * Check whether profile (name, email) is complete
  *
  * return $contact_id
  */
 public static function checkProfileComplete($fields, &$errors, $self)
 {
     $email = '';
     foreach ($fields as $fieldname => $fieldvalue) {
         if (substr($fieldname, 0, 5) == 'email' && $fieldvalue) {
             $email = $fieldvalue;
         }
     }
     if (!$email && !(CRM_Utils_Array::value('first_name', $fields) && CRM_Utils_Array::value('last_name', $fields))) {
         $defaults = $params = array('id' => $eventId);
         CRM_Event_BAO_Event::retrieve($params, $defaults);
         $message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
         $errors['_qf_default'] = $message;
     }
     $contact = CRM_Contact_BAO_Contact::matchContactOnEmail($email, "");
     $contact_id = empty($contact->contact_id) ? NULL : $contact->contact_id;
     if (!CRM_Utils_Rule::email($fields['email'])) {
         $errors['email'] = ts('Enter valid email address.');
     }
     if (empty($errors) && empty($contact_id)) {
         $params = array('email-Primary' => CRM_Utils_Array::value('email', $fields, NULL), 'first_name' => CRM_Utils_Array::value('first_name', $fields, NULL), 'last_name' => CRM_Utils_Array::value('last_name', $fields, NULL), 'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, FALSE));
         //create new contact for this name/email pair
         //if new contact, no need to check for contact already registered
         $contact_id = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contact_id);
     }
     return $contact_id;
 }
Ejemplo n.º 20
0
 /**
  * Global form rule.
  *
  * @param array $fields
  *   The input form values.
  * @param array $files
  *   The uploaded files if any.
  * @param array $self
  *   Current form object.
  *
  * @return array
  *   array of errors / empty array.
  */
 public static function formRule($fields, $files, $self)
 {
     $errors = array();
     if ($self->_gName == 'case_status' && empty($fields['grouping'])) {
         $errors['grouping'] = ts('Status class is a required field');
     }
     if (in_array($self->_gName, array('email_greeting', 'postal_greeting', 'addressee')) && empty($self->_defaultValues['is_reserved'])) {
         $label = $fields['label'];
         $condition = " AND v.label = '{$label}' ";
         $values = CRM_Core_OptionGroup::values($self->_gName, FALSE, FALSE, FALSE, $condition, 'filter');
         $checkContactOptions = TRUE;
         if ($self->_id && $self->_defaultValues['contactOptions'] == $fields['contactOptions']) {
             $checkContactOptions = FALSE;
         }
         if ($checkContactOptions && in_array($fields['contactOptions'], $values)) {
             $errors['label'] = ts('This Label already exists in the database for the selected contact type.');
         }
     }
     if ($self->_gName == 'from_email_address') {
         $formEmail = CRM_Utils_Mail::pluckEmailFromHeader($fields['label']);
         if (!CRM_Utils_Rule::email($formEmail)) {
             $errors['label'] = ts('Please enter a valid email address.');
         }
         $formName = explode('"', $fields['label']);
         if (empty($formName[1]) || count($formName) != 3) {
             $errors['label'] = ts('Please follow the proper format for From Email Address');
         }
     }
     $dataType = self::getOptionGroupDataType($self->_gName);
     if ($dataType && $self->_gName !== 'activity_type') {
         $validate = CRM_Utils_Type::validate($fields['value'], $dataType, FALSE);
         if (!$validate) {
             CRM_Core_Session::setStatus(ts('Data Type of the value field for this option value does not match ' . $dataType), ts('Value field Data Type mismatch'));
         }
     }
     return $errors;
 }
Ejemplo n.º 21
0
/**
 * Validate a formatted contact parameter list.
 *
 * @param array $params  Structured parameter list (as in crm_format_params)
 *
 * @return bool|CRM_Core_Error
 * @access public
 */
function _crm_validate_formatted_contact(&$params)
{
    /* Look for offending email addresses */
    if (is_array($params['location'])) {
        $badEmail = true;
        $emails = 0;
        foreach ($params['location'] as $loc) {
            if (is_array($loc['email'])) {
                $emails++;
                foreach ($loc['email'] as $email) {
                    if (CRM_Utils_Rule::email($email['email'])) {
                        $badEmail = false;
                    }
                }
            }
        }
        if ($emails && $badEmail) {
            return _crm_error('No valid email address');
        }
    }
    /* Validate custom data fields */
    if (is_array($params['custom'])) {
        foreach ($params['custom'] as $key => $custom) {
            if (is_array($custom)) {
                $valid = CRM_Core_BAO_CustomValue::typecheck($custom['type'], $custom['value']);
                if (!$valid) {
                    return _crm_error('Invalid value for custom field \'' . $custom['name'] . '\'');
                }
                if ($custom['type'] == 'Date') {
                    $params['custom'][$key]['value'] = str_replace('-', '', $params['custom'][$key]['value']);
                }
            }
        }
    }
    return true;
}
Ejemplo n.º 22
0
 /**
  * Form rule to send out a test mailing.
  *
  * @param aray $testParams
  * @param array $files
  *   Any files posted to the form.
  * @param array $self
  *   An current this object.
  *
  * @return bool
  *   true on successful SMTP handoff
  */
 public static function testMail($testParams, $files, $self)
 {
     $error = NULL;
     $urlString = 'civicrm/mailing/send';
     $urlParams = "_qf_Test_display=true&qfKey={$testParams['qfKey']}";
     $ssID = $self->get('ssID');
     if ($ssID && $self->_searchBasedMailing) {
         if ($self->_action == CRM_Core_Action::BASIC) {
             $fragment = 'search';
         } elseif ($self->_action == CRM_Core_Action::PROFILE) {
             $fragment = 'search/builder';
         } elseif ($self->_action == CRM_Core_Action::ADVANCED) {
             $fragment = 'search/advanced';
         } else {
             $fragment = 'search/custom';
         }
         $urlString = 'civicrm/contact/' . $fragment;
     }
     $emails = NULL;
     if (!empty($testParams['sendtest'])) {
         if (!($testParams['test_group'] || $testParams['test_email'])) {
             CRM_Core_Session::setStatus(ts('You did not provide an email address or select a group.'), ts('Test not sent.'), 'error');
             $error = TRUE;
         }
         if ($testParams['test_email']) {
             $emailAdd = explode(',', $testParams['test_email']);
             foreach ($emailAdd as $key => $value) {
                 $email = trim($value);
                 $testParams['emails'][] = $email;
                 $emails .= ($emails ? ',' : '') . "'" . CRM_Core_DAO::escapeString($email) . "'";
                 if (!CRM_Utils_Rule::email($email)) {
                     CRM_Core_Session::setStatus(ts('Please enter a valid email address.'), ts('Test not sent.'), 'error');
                     $error = TRUE;
                 }
             }
         }
         if ($error) {
             $url = CRM_Utils_System::url($urlString, $urlParams);
             CRM_Utils_System::redirect($url);
             return $error;
         }
     }
     if (!empty($testParams['_qf_Test_submit'])) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         if ($ssID && $self->_searchBasedMailing) {
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("You can continue later by clicking the 'Continue' action to resume working on it.<br />From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             //replace user context to search.
             $context = $self->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}&qfKey={$testParams['qfKey']}";
             $url = CRM_Utils_System::url($urlString, $urlParams);
         } else {
             $status = ts("Click the 'Continue' action to resume working on it.");
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
         }
         CRM_Core_Session::setStatus($status, ts('Mailing Saved'), 'success');
         CRM_Utils_System::redirect($url);
     }
     if (CRM_Mailing_Info::workflowEnabled()) {
         if (!CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings')) {
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (!empty($testParams['_qf_Test_next']) && $self->get('count') <= 0) {
         return array('_qf_default' => ts("You can not schedule or send this mailing because there are currently no recipients selected. Click 'Previous' to return to the Select Recipients step, OR click 'Save & Continue Later'."));
     }
     if (!empty($_POST['_qf_Import_refresh']) || !empty($testParams['_qf_Test_next']) || empty($testParams['sendtest'])) {
         $error = TRUE;
         return $error;
     }
     $job = new CRM_Mailing_BAO_MailingJob();
     $job->mailing_id = $self->get('mailing_id');
     $job->is_test = TRUE;
     $job->save();
     $newEmails = NULL;
     $session = CRM_Core_Session::singleton();
     if (!empty($testParams['emails'])) {
         $query = "\nSELECT     e.id, e.contact_id, e.email\nFROM       civicrm_email e\nINNER JOIN civicrm_contact c ON e.contact_id = c.id\nWHERE      e.email IN ({$emails})\nAND        e.on_hold = 0\nAND        c.is_opt_out = 0\nAND        c.do_not_email = 0\nAND        c.is_deleted = 0\nAND        c.is_deceased = 0\nGROUP BY   e.id\nORDER BY   e.is_bulkmail DESC, e.is_primary DESC\n";
         $dao = CRM_Core_DAO::executeQuery($query);
         $emailDetail = array();
         // fetch contact_id and email id for all existing emails
         while ($dao->fetch()) {
             $emailDetail[$dao->email] = array('contact_id' => $dao->contact_id, 'email_id' => $dao->id);
         }
         $dao->free();
         foreach ($testParams['emails'] as $key => $email) {
             // Email addresses are forced to lower case when saved, so ensure
             // we have the same case when comparing.
             $email = trim(strtolower($email));
             $contactId = $emailId = NULL;
             if (array_key_exists($email, $emailDetail)) {
                 $emailId = $emailDetail[$email]['email_id'];
                 $contactId = $emailDetail[$email]['contact_id'];
             }
             if (!$contactId) {
                 //create new contact.
                 $params = array('contact_type' => 'Individual', 'email' => array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => 1)));
                 $contact = CRM_Contact_BAO_Contact::create($params);
                 $emailId = $contact->email[0]->id;
                 $contactId = $contact->id;
                 $contact->free();
             }
             $params = array('job_id' => $job->id, 'email_id' => $emailId, 'contact_id' => $contactId);
             CRM_Mailing_Event_BAO_Queue::create($params);
         }
     }
     $testParams['job_id'] = $job->id;
     $isComplete = FALSE;
     while (!$isComplete) {
         $isComplete = CRM_Mailing_BAO_MailingJob::runJobs($testParams);
     }
     if (!empty($testParams['sendtest'])) {
         $status = NULL;
         if (CRM_Mailing_Info::workflowEnabled()) {
             if (CRM_Core_Permission::check('schedule mailings') && CRM_Core_Permission::check('create mailings') || CRM_Core_Permission::check('access CiviMail')) {
                 $status = ts("Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
             }
         } else {
             $status = ts("Click 'Next' when you are ready to Schedule or Send your live mailing (you will still have a chance to confirm or cancel sending this mailing on the next page).");
         }
         if ($status) {
             CRM_Core_Session::setStatus($status, ts('Test message sent'), 'success');
         }
         $url = CRM_Utils_System::url($urlString, $urlParams);
         CRM_Utils_System::redirect($url);
     }
     $error = TRUE;
     return $error;
 }
Ejemplo n.º 23
0
/**
 * Validate a formatted contact parameter list.
 *
 * @param array $params  Structured parameter list (as in crm_format_params)
 *
 * @return bool|CRM_Core_Error
 * @access public
 */
function _civicrm_validate_formatted_contact(&$params)
{
    /* Look for offending email addresses */
    if (array_key_exists('email', $params)) {
        foreach ($params['email'] as $count => $values) {
            if (!is_array($values)) {
                continue;
            }
            if ($email = CRM_Utils_Array::value('email', $values)) {
                //validate each email
                if (!CRM_Utils_Rule::email($email)) {
                    return civicrm_create_error('No valid email address');
                }
                //check for loc type id.
                if (!CRM_Utils_Array::value('location_type_id', $values)) {
                    return civicrm_create_error('Location Type Id missing.');
                }
            }
        }
    }
    /* Validate custom data fields */
    if (is_array($params['custom'])) {
        foreach ($params['custom'] as $key => $custom) {
            if (is_array($custom)) {
                $valid = CRM_Core_BAO_CustomValue::typecheck($custom['type'], $custom['value']);
                if (!$valid) {
                    return civicrm_create_error('Invalid value for custom field \'' . $custom['name'] . '\'');
                }
                if ($custom['type'] == 'Date') {
                    $params['custom'][$key]['value'] = str_replace('-', '', $params['custom'][$key]['value']);
                }
            }
        }
    }
    return civicrm_create_success(true);
}
Ejemplo n.º 24
0
 /**
  * Function for validation
  *
  * @param array $params (ref.) an assoc array of name/value pairs
  *
  * @return mixed true or array of errors
  * @access public
  * @static
  */
 public static function formRule(&$params, &$files, $self)
 {
     $errors = array();
     if (CRM_Utils_Array::value('is_active', $params)) {
         if (CRM_Utils_Array::value('is_tellfriend_enabled', $params) && CRM_Utils_Array::value('tellfriend_limit', $params) <= 0) {
             $errors['tellfriend_limit'] = ts('if Tell Friend is enable, Maximum recipients limit should be greater than zero.');
         }
         if (!CRM_Utils_Array::value('supporter_profile_id', $params)) {
             $errors['supporter_profile_id'] = ts('Supporter profile is a required field.');
         } else {
             require_once 'CRM/Contribute/BAO/PCP.php';
             if (CRM_Contribute_BAO_PCP::checkEmailProfile($params['supporter_profile_id'])) {
                 $errors['supporter_profile_id'] = ts('Profile is not configured with Email address.');
             }
         }
         if ($emails = CRM_Utils_Array::value('notify_email', $params)) {
             $emailArray = explode(',', $emails);
             foreach ($emailArray as $email) {
                 if ($email && !CRM_Utils_Rule::email(trim($email))) {
                     $errors['notify_email'] = ts('A valid Notify Email address must be specified');
                 }
             }
         }
     }
     return empty($errors) ? true : $errors;
 }
Ejemplo n.º 25
0
 /**
  * Validate something we didn't document.
  *
  * @return bool
  */
 public function validate()
 {
     //  echo $this->_value."===========<br>";
     $message = '';
     if ($this->_value === NULL) {
         return TRUE;
     }
     //     Commented due to bug CRM-150, internationalization/wew.
     //         if ( $this->_name == 'phone' ) {
     //            return CRM_Utils_Rule::phone( $this->_value );
     //         }
     if ($this->_name == 'email') {
         return CRM_Utils_Rule::email($this->_value);
     }
 }
Ejemplo n.º 26
0
 /**
  * handle the values in summary mode
  *
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function summary(&$values)
 {
     $erroneousField = NULL;
     $response = $this->setActiveFieldValues($values, $erroneousField);
     $errorRequired = FALSE;
     if ($this->_membershipTypeIndex < 0) {
         $errorRequired = TRUE;
     } else {
         $errorRequired = !CRM_Utils_Array::value($this->_membershipTypeIndex, $values);
     }
     if ($errorRequired) {
         array_unshift($values, ts('Missing required fields'));
         return CRM_Import_Parser::ERROR;
     }
     $params =& $this->getActiveFieldParams();
     $errorMessage = NULL;
     //To check whether start date or join date is provided
     if (!CRM_Utils_Array::value('membership_start_date', $params) && !CRM_Utils_Array::value('join_date', $params)) {
         $errorMessage = 'Membership Start Date is required to create a memberships.';
         CRM_Contact_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
     }
     //end
     //for date-Formats
     $session = CRM_Core_Session::singleton();
     $dateType = $session->get('dateTypes');
     foreach ($params as $key => $val) {
         if ($val) {
             switch ($key) {
                 case 'join_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Contact_Import_Parser_Contact::addToErrorMsg('Member Since', $errorMessage);
                         }
                     } else {
                         CRM_Contact_Import_Parser_Contact::addToErrorMsg('Member Since', $errorMessage);
                     }
                     break;
                 case 'membership_start_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Contact_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
                         }
                     } else {
                         CRM_Contact_Import_Parser_Contact::addToErrorMsg('Start Date', $errorMessage);
                     }
                     break;
                 case 'membership_end_date':
                     if (CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key)) {
                         if (!CRM_Utils_Rule::date($params[$key])) {
                             CRM_Contact_Import_Parser_Contact::addToErrorMsg('End date', $errorMessage);
                         }
                     } else {
                         CRM_Contact_Import_Parser_Contact::addToErrorMsg('End date', $errorMessage);
                     }
                     break;
                 case 'membership_type_id':
                     $membershipTypes = CRM_Member_PseudoConstant::membershipType();
                     if (!CRM_Utils_Array::crmInArray($val, $membershipTypes) && !array_key_exists($val, $membershipTypes)) {
                         CRM_Contact_Import_Parser_Contact::addToErrorMsg('Membership Type', $errorMessage);
                     }
                     break;
                 case 'status_id':
                     if (!CRM_Utils_Array::crmInArray($val, CRM_Member_PseudoConstant::membershipStatus())) {
                         CRM_Contact_Import_Parser_Contact::addToErrorMsg('Membership Status', $errorMessage);
                     }
                     break;
                 case 'email':
                     if (!CRM_Utils_Rule::email($val)) {
                         CRM_Contact_Import_Parser_Contact::addToErrorMsg('Email Address', $errorMessage);
                     }
             }
         }
     }
     //date-Format part ends
     $params['contact_type'] = 'Membership';
     //checking error in custom data
     CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
     if ($errorMessage) {
         $tempMsg = "Invalid value for field(s) : {$errorMessage}";
         array_unshift($values, $tempMsg);
         $errorMessage = NULL;
         return CRM_Import_Parser::ERROR;
     }
     return CRM_Import_Parser::VALID;
 }
Ejemplo n.º 27
0
 /**
  * Synchronize the object with the UF Match entry. Can be called stand-alone from
  * the drupalUsers script
  *
  * @param Object  $user    the drupal user object
  * @param string  $userKey the id of the user from the uf object
  * @param string  $mail    the email address of the user
  * @param string  $uf      the name of the user framework
  * @param integer $status  returns the status if user created or already exits (used for drupal sync)
  *
  * @return the ufmatch object that was found or created
  * @access public
  * @static
  */
 function &synchronizeUFMatch(&$user, $userKey, $mail, $uf, $status = null)
 {
     // validate that mail is a valid email address. Drupal does not check for this stuff
     require_once 'CRM/Utils/Rule.php';
     if (!CRM_Utils_Rule::email($mail)) {
         return $status ? null : false;
     }
     $newContact = false;
     // make sure that a contact id exists for this user id
     $ufmatch =& new CRM_Core_DAO_UFMatch();
     $ufmatch->uf_id = $userKey;
     $ufmatch->domain_id = CRM_Core_Config::domainID();
     if (!$ufmatch->find(true)) {
         $query = "\nSELECT    civicrm_contact.id as contact_id, civicrm_contact.domain_id as domain_id\nFROM      civicrm_contact\nLEFT JOIN civicrm_location ON ( civicrm_location.entity_table = 'civicrm_contact' AND\n                                civicrm_contact.id  = civicrm_location.entity_id AND \n                                civicrm_location.is_primary = 1 )\nLEFT JOIN civicrm_email    ON ( civicrm_location.id = civicrm_email.location_id   AND civicrm_email.is_primary = 1    )\nWHERE     civicrm_email.email = '" . CRM_Utils_Type::escape($mail, 'String') . "' AND civicrm_contact.domain_id = " . CRM_Core_Config::domainID();
         $dao =& new CRM_Core_DAO();
         $dao->query($query);
         if ($dao->fetch()) {
             $ufmatch->contact_id = $dao->contact_id;
             $ufmatch->domain_id = $dao->domain_id;
             $ufmatch->email = $mail;
         } else {
             if ($uf == 'Mambo') {
                 CRM_Utils_System_Mambo::setEmail($user);
             }
             require_once 'CRM/Core/BAO/LocationType.php';
             $locationType =& CRM_Core_BAO_LocationType::getDefault();
             //CRM_Core_Error::debug('M', $mail);
             $params = array('email' => $mail, 'location_type' => $locationType->name);
             $contact =& crm_create_contact($params, 'Individual');
             if (is_a($contact, 'CRM_Core_Error')) {
                 //CRM_Core_Error::debug( 'error', $contact );
                 exit(1);
             }
             $ufmatch->contact_id = $contact->id;
             $ufmatch->domain_id = $contact->domain_id;
             $ufmatch->email = $mail;
         }
         $ufmatch->save();
         $newContact = true;
     }
     return $status ? $newContact : $ufmatch;
 }