Exemplo n.º 1
0
 /**
  * Confirm a pending subscription
  *
  * @param int $contact_id       The id of the contact
  * @param int $subscribe_id     The id of the subscription event
  * @param string $hash          The hash
  * @return boolean              True on success
  * @access public
  * @static
  */
 function confirm($contact_id, $subscribe_id, $hash)
 {
     $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash);
     if (!$se) {
         return false;
     }
     CRM_Core_DAO::transaction('BEGIN');
     $ce =& new CRM_Mailing_Event_BAO_Confirm();
     $ce->event_subscribe_id = $se->id;
     $ce->time_stamp = date('YmdHis');
     $ce->save();
     CRM_Contact_BAO_GroupContact::updateGroupMembershipStatus($contact_id, $se->group_id, 'Email', $ce->id);
     CRM_Core_DAO::transaction('COMMIT');
     $config =& CRM_Core_Config::singleton();
     $domain =& CRM_Mailing_Event_BAO_Subscribe::getDomain($subscribe_id);
     list($display_name, $email) = CRM_Contact_BAO_Contact::getEmailDetails($se->contact_id);
     $group =& new CRM_Contact_DAO_Group();
     $group->id = $se->group_id;
     $group->find(true);
     require_once 'CRM/Mailing/BAO/Component.php';
     $component =& new CRM_Mailing_BAO_Component();
     $component->domain_id = $domain->id;
     $component->is_default = 1;
     $component->is_active = 1;
     $component->component_type = 'Welcome';
     $component->find(true);
     $headers = array('Subject' => $component->subject, 'From' => ts('"%1 Administrator" <do-not-reply@%2>', array(1 => $domain->name, 2 => $domain->email_domain)), 'To' => $email, 'Reply-To' => "do-not-reply@{$domain->email_domain}", 'Return-Path' => "do-not-reply@{$domain->email_domain}");
     $html = $component->body_html;
     require_once 'CRM/Utils/Token.php';
     $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true);
     $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->name, true);
     $text = $component->body_text;
     $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false);
     $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->name, false);
     $message =& new Mail_Mime("\n");
     $message->setHTMLBody($html);
     $message->setTxtBody($text);
     $b = $message->get();
     $h = $message->headers($headers);
     $mailer =& $config->getMailer();
     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Mailing_BAO_Mailing', 'catchSMTP'));
     $mailer->send($email, $h, $b);
     CRM_Core_Error::setCallback();
     return true;
 }
Exemplo n.º 2
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 '';
 }
Exemplo n.º 3
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 function postProcess()
 {
     $emailAddress = null;
     if ($this->_single) {
         $emailAddress = $this->controller->exportValue('Email', 'to');
     }
     if ($this->_noEmails) {
         $emailAddress = $this->controller->exportValue('Email', 'emailAddress');
         // for adding the email-id to the primary address
         $cid = CRM_Utils_Request::retrieve('cid', $this, false);
         if ($cid) {
             $location =& CRM_Contact_BAO_Contact::getEmailDetails($cid);
             if ($location[3]) {
                 $locationID = $location[3];
                 $email =& new CRM_Core_DAO_Email();
                 $email->location_id = $locationID;
                 $email->is_primary = 1;
                 $email->email = $emailAddress;
                 $email->save();
             } else {
                 require_once 'CRM/Core/BAO/LocationType.php';
                 $ids = $params = $locID = array();
                 $params['contact_id'] = $cid;
                 $locType = CRM_Core_BAO_LocationType::getDefault();
                 $params['location'][1]['location_type_id'] = $locType->id;
                 $params['location'][1]['is_primary'] = 1;
                 $params['location'][1]['email'][1]['email'] = $emailAddress;
                 CRM_Core_BAO_Location::add($params, $ids, 1);
             }
         }
     }
     $subject = $this->controller->exportValue('Email', 'subject');
     $message = $this->controller->exportValue('Email', 'message');
     require_once 'CRM/Core/BAO/EmailHistory.php';
     list($total, $sent, $notSent) = CRM_Core_BAO_EmailHistory::sendEmail($this->_contactIds, $subject, $message, $emailAddress);
     $status = array('', ts('Total Selected Contact(s): %1', array(1 => $total)));
     if ($sent) {
         $status[] = ts('Email sent to contact(s): %1', array(1 => $sent));
     }
     if ($notSent) {
         $status[] = ts('Email not sent to contact(s) (no email address on file or communication preferences specify DO NOT EMAIL): %1', array(1 => $notSent));
     }
     CRM_Core_Session::setStatus($status);
 }
Exemplo n.º 4
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
  */
 function formRule(&$fields, &$files, $options = null)
 {
     $errors = array();
     // if no values, return
     if (empty($fields)) {
         return true;
     }
     // hack add the email, does not work in registration, we need the real user object
     // hack this will not work in mambo/joomla, not sure why we need it
     global $user;
     if (isset($user) && !CRM_Utils_Array::value('email', $fields)) {
         $fields['email'] = $user->mail;
     }
     $cid = $register = null;
     // hack we use a -1 in options to indicate that its registration
     if ($options) {
         $options = (int) $options;
         if ($options > 0) {
             $cid = $options;
         } else {
             $register = true;
         }
     }
     $cid = null;
     if ($options) {
         $cid = (int) $options;
         // get the primary location type id and email
         list($name, $primaryEmail, $primaryLocationType) = CRM_Contact_BAO_Contact::getEmailDetails($cid);
     }
     // dont check for duplicates during registration validation: CRM-375
     if (!$register) {
         $locationType = array();
         $count = 1;
         $primaryLocation = 0;
         foreach ($fields as $key => $value) {
             $keyValue = explode('-', $key);
             if (is_numeric($keyValue[1])) {
                 if (!in_array($keyValue[1], $locationType)) {
                     $locationType[$count] = $keyValue[1];
                     $count++;
                 }
                 require_once 'CRM/Utils/Array.php';
                 $loc = CRM_Utils_Array::key($keyValue[1], $locationType);
                 $data['location'][$loc]['location_type_id'] = $keyValue[1];
                 // if we are getting in a new primary email, dont overwrite the new one
                 if ($keyValue[1] == $primaryLocationType) {
                     if (CRM_Utils_Array::value('email-' . $primaryLocationType, $fields)) {
                         $data['location'][$loc]['email'][$loc]['email'] = $fields['email-' . $primaryLocationType];
                     } else {
                         $data['location'][$loc]['email'][$loc]['email'] = $primaryEmail;
                     }
                     $primaryLocation++;
                 }
                 if ($loc == 1) {
                     $data['location'][$loc]['is_primary'] = 1;
                 }
                 if ($keyValue[0] == 'phone') {
                     if ($keyValue[2]) {
                         $data['location'][$loc]['phone'][$loc]['phone_type'] = $keyValue[2];
                     } else {
                         $data['location'][$loc]['phone'][$loc]['phone_type'] = '';
                     }
                     $data['location'][$loc]['phone'][$loc]['phone'] = $value;
                 } else {
                     if ($keyValue[0] == 'email') {
                         $data['location'][$loc]['email'][$loc]['email'] = $value;
                     } elseif ($keyValue[0] == 'im') {
                         $data['location'][$loc]['im'][$loc]['name'] = $value;
                     } else {
                         if ($keyValue[0] === 'state_province') {
                             $data['location'][$loc]['address']['state_province_id'] = $value;
                         } else {
                             if ($keyValue[0] === 'country') {
                                 $data['location'][$loc]['address']['country_id'] = $value;
                             } else {
                                 $data['location'][$loc]['address'][$keyValue[0]] = $value;
                             }
                         }
                     }
                 }
             } else {
                 if ($key === 'individual_suffix') {
                     $data['suffix_id'] = $value;
                 } else {
                     if ($key === 'individual_prefix') {
                         $data['prefix_id'] = $value;
                     } else {
                         if ($key === 'gender') {
                             $data['gender_id'] = $value;
                         } else {
                             if (substr($key, 0, 6) === 'custom') {
                                 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                                     //fix checkbox
                                     if ($customFields[$customFieldID][3] == 'CheckBox') {
                                         $value = implode(CRM_CORE_BAO_CUSTOMOPTION_VALUE_SEPERATOR, array_keys($value));
                                     }
                                     // fix the date field
                                     if ($customFields[$customFieldID][2] == 'Date') {
                                         $date = CRM_Utils_Date::format($value);
                                         if (!$date) {
                                             $date = '';
                                         }
                                         $value = $date;
                                     }
                                     $data['custom'][$customFieldID] = array('id' => $id, 'value' => $value, 'extends' => $customFields[$customFieldID][3], 'type' => $customFields[$customFieldID][2], 'custom_field_id' => $customFieldID);
                                 }
                             } else {
                                 if ($key == 'edit') {
                                     continue;
                                 } else {
                                     $data[$key] = $value;
                                 }
                             }
                         }
                     }
                 }
             }
         }
         if (!$primaryLocation) {
             $loc++;
             $data['location'][$loc]['email'][$loc]['email'] = $primaryEmail;
         }
         $ids = CRM_Core_BAO_UFGroup::findContact($data, $cid, true);
         if ($ids) {
             $errors['_qf_default'] = ts('An account already exists with the same information.');
         }
     }
     // Validate Country - State list
     $countryId = $fields['country'];
     $stateProvinceId = $fields['state_province'];
     if ($stateProvinceId && $countryId) {
         $stateProvinceDAO =& new CRM_Core_DAO_StateProvince();
         $stateProvinceDAO->id = $stateProvinceId;
         $stateProvinceDAO->find(true);
         if ($stateProvinceDAO->country_id != $countryId) {
             // country mismatch hence display error
             $stateProvinces = CRM_Core_PseudoConstant::stateProvince();
             $countries =& CRM_Core_PseudoConstant::country();
             $errors['state_province'] = "State/Province " . $stateProvinces[$stateProvinceId] . " is not part of " . $countries[$countryId] . ". It belongs to " . $countries[$stateProvinceDAO->country_id] . ".";
         }
     }
     return empty($errors) ? true : $errors;
 }
Exemplo n.º 5
0
 /**
  * Process the form
  *
  * @return void
  * @access public
  */
 function postProcess()
 {
     $contactID = $this->get('contactID');
     if (!$contactID) {
         // make a copy of params so we dont destroy our params
         // (since we pass this by reference)
         $premiumParams = $params = $this->_params;
         // so now we have a confirmed financial transaction
         // lets create or update a contact first
         require_once 'api/crm.php';
         $ids = CRM_Core_BAO_UFGroup::findContact($params);
         $contactsIDs = explode(',', $ids);
         // if we find more than one contact, use the first one
         $contact_id = $contactsIDs[0];
         $contact = null;
         if ($contact_id) {
             $contact =& crm_get_contact(array('contact_id' => $contact_id));
         }
         $ids = array();
         if (!$contact || !is_a($contact, 'CRM_Contact_BAO_Contact')) {
             $contact =& CRM_Contact_BAO_Contact::createFlat($params, $ids);
         } else {
             // need to fix and unify all contact creation
             $idParams = array('id' => $contact_id, 'contact_id' => $contact_id);
             $defaults = array();
             CRM_Contact_BAO_Contact::retrieve($idParams, $defaults, $ids);
             $contact =& CRM_Contact_BAO_Contact::createFlat($params, $ids);
         }
         if (is_a($contact, 'CRM_Core_Error')) {
             CRM_Core_Error::fatal("Failed creating contact for contributor");
         }
         $contactID = $contact->id;
         $this->set('contactID', $contactID);
     }
     $contributionType =& new CRM_Contribute_DAO_ContributionType();
     $contributionType->id = $this->_values['contribution_type_id'];
     if (!$contributionType->find(true)) {
         CRM_Core_Error::fatal("Could not find a system table");
     }
     // add some contribution type details to the params list
     // if folks need to use it
     $this->_params['contributionType_name'] = $contributionType->name;
     $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
     $this->_params['contributionForm_id'] = $this->_values['id'];
     require_once 'CRM/Contribute/Payment.php';
     $payment =& CRM_Contribute_Payment::singleton($this->_mode);
     if ($this->_contributeMode == 'express') {
         $result =& $payment->doExpressCheckout($this->_params);
     } else {
         $result =& $payment->doDirectPayment($this->_params);
     }
     if (is_a($result, 'CRM_Core_Error')) {
         CRM_Core_Error::displaySessionError($result);
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', '_qf_Main_display=true'));
     }
     $now = date('YmdHis');
     $this->_params = array_merge($this->_params, $result);
     $this->_params['receive_date'] = $now;
     $this->set('params', $this->_params);
     $this->assign('trxn_id', $result['trxn_id']);
     $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($this->_params['receive_date']));
     // result has all the stuff we need
     // lets archive it to a financial transaction
     $config =& CRM_Core_Config::singleton();
     $receiptDate = null;
     if ($this->_values['is_email_receipt']) {
         $receiptDate = $now;
     }
     if ($contributionType->is_deductible) {
         $this->assign('is_deductible', true);
         $this->set('is_deductible', true);
     }
     // assigning Premium information to receipt tpl
     if ($premiumParams['selectProduct'] && $premiumParams['selectProduct'] != 'no_thanks') {
         $startDate = $endDate = "";
         $this->assign('selectPremium', true);
         require_once 'CRM/Contribute/DAO/Product.php';
         $productDAO =& new CRM_Contribute_DAO_Product();
         $productDAO->id = $premiumParams['selectProduct'];
         $productDAO->find(true);
         $this->assign('product_name', $productDAO->name);
         $this->assign('price', $productDAO->price);
         $this->assign('sku', $productDAO->sku);
         $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']]);
         $periodType = $productDAO->period_type;
         if ($periodType) {
             $fixed_period_start_day = $productDAO->fixed_period_start_day;
             $duration_unit = $productDAO->duration_unit;
             $duration_interval = $productDAO->duration_interval;
             if ($periodType == 'rolling') {
                 $startDate = date('Y-m-d');
             } else {
                 if ($periodType == 'fixed') {
                     if ($fixed_period_start_day) {
                         $date = explode('-', date('Y-m-d'));
                         $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
                         $day = substr($fixed_period_start_day, -2) . "<br>";
                         $year = $date[0];
                         $startDate = $year . '-' . $month . '-' . $day;
                     } else {
                         $startDate = date('Y-m-d');
                     }
                 }
             }
             $date = explode('-', $startDate);
             $year = $date[0];
             $month = $date[1];
             $day = $date[2];
             switch ($duration_unit) {
                 case 'year':
                     $year = $year + $duration_interval;
                     break;
                 case 'month':
                     $month = $month + $duration_interval;
                     break;
                 case 'day':
                     $day = $day + $duration_interval;
                     break;
                 case 'week':
                     $day = $day + $duration_interval * 7;
             }
             $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
             $this->assign('start_date', $startDate);
             $this->assign('end_date', $endDate);
         }
         require_once 'CRM/Contribute/DAO/Premium.php';
         $dao =& new CRM_Contribute_DAO_Premium();
         $dao->entity_table = 'civicrm_contribution_page';
         $dao->entity_id = $this->_id;
         $dao->find(true);
         $this->assign('contact_phone', $dao->premiums_contact_phone);
         $this->assign('contact_email', $dao->premiums_contact_email);
     }
     CRM_Core_DAO::transaction('BEGIN');
     $nonDeductibleAmount = $result['gross_amount'];
     if ($contributionType->is_deductible) {
         if ($premiumParams['selectProduct'] != 'no_thanks') {
             require_once 'CRM/Contribute/DAO/Product.php';
             $productDAO =& new CRM_Contribute_DAO_Product();
             $productDAO->id = $premiumParams['selectProduct'];
             $productDAO->find(true);
             if ($result['gross_amount'] < $productDAO->price) {
                 $nonDeductibleAmount = $result['gross_amount'];
             } else {
                 $nonDeductibleAmount = $productDAO->price;
             }
         } else {
             $nonDeductibleAmount = '0.00';
         }
     }
     // check contribution Type
     // first create the contribution record
     $params = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'payment_instrument_id' => 1, 'receive_date' => $now, 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $result['gross_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $result['gross_amount']), 'trxn_id' => $result['trxn_id'], 'invoice_id' => $this->_params['invoiceID'], 'currency' => $this->_params['currencyID'], 'receipt_date' => $receiptDate, 'source' => ts('Online Contribution:') . ' ' . $this->_values['title']);
     $ids = array();
     $contribution =& CRM_Contribute_BAO_Contribution::add($params, $ids);
     //create Premium record
     if ($premiumParams['selectProduct'] && $premiumParams['selectProduct'] != 'no_thanks') {
         require_once 'CRM/Contribute/DAO/Product.php';
         $productDAO =& new CRM_Contribute_DAO_Product();
         $productDAO->id = $premiumParams['selectProduct'];
         $productDAO->find(true);
         $periodType = $productDAO->period_type;
         require_once 'CRM/Utils/Date.php';
         $params = array('product_id' => $premiumParams['selectProduct'], 'contribution_id' => $contribution->id, 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']], 'quantity' => 1, 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'), 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'));
         CRM_Contribute_BAO_Contribution::addPremium($params);
     }
     // process the custom data that is submitted or that came via the url
     $groupTree = $this->get('groupTree');
     $customValues = $this->get('customGetValues');
     $customValues = array_merge($this->_params, $customValues);
     require_once 'CRM/Core/BAO/CustomGroup.php';
     CRM_Core_BAO_CustomGroup::postProcess($groupTree, $customValues);
     CRM_Core_BAO_CustomGroup::updateCustomData($groupTree, 'Contribution', $contribution->id);
     // next create the transaction record
     $params = array('entity_table' => 'civicrm_contribution', 'entity_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $result['gross_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $result['gross_amount']), 'currency' => $this->_params['currencyID'], 'payment_processor' => $config->paymentProcessor, 'trxn_id' => $result['trxn_id']);
     require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
     $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($params);
     // also create an activity history record
     require_once 'CRM/Utils/Money.php';
     $params = array('entity_table' => 'civicrm_contact', 'entity_id' => $contactID, 'activity_type' => $contributionType->name, 'module' => 'CiviContribute', 'callback' => 'CRM_Contribute_Page_Contribution::details', 'activity_id' => $contribution->id, 'activity_summary' => 'Online - ' . CRM_Utils_Money::format($this->_params['amount']), 'activity_date' => $now);
     if (is_a(crm_create_activity_history($params), 'CRM_Core_Error')) {
         CRM_Core_Error::fatal("Could not create a system record");
     }
     CRM_Core_DAO::transaction('COMMIT');
     // finally send an email receipt
     if ($this->_values['is_email_receipt']) {
         list($displayName, $email) = CRM_Contact_BAO_Contact::getEmailDetails($contactID);
         $template =& CRM_Core_Smarty::singleton();
         $subject = trim($template->fetch('CRM/Contribute/Form/Contribution/ReceiptSubject.tpl'));
         $message = $template->fetch('CRM/Contribute/Form/Contribution/ReceiptMessage.tpl');
         $receiptFrom = '"' . $this->_values['receipt_from_name'] . '" <' . $this->_values['receipt_from_email'] . '>';
         require_once 'CRM/Utils/Mail.php';
         CRM_Utils_Mail::send($receiptFrom, $displayName, $email, $subject, $message, $this->_values['cc_receipt'], $this->_values['bcc_receipt']);
     }
 }
Exemplo n.º 6
0
 /**
  * Update the email value for the contact and user profile
  *  
  * @param  $contactId  Int     Contact ID of the user
  * @param  $email      String  email to be modified for the user
  *
  * @return void
  * @access public
  * @static
  */
 function updateContactEmail($contactId, $emailAddress)
 {
     $ufmatch =& new CRM_Core_DAO_UFMatch();
     $ufmatch->contact_id = $contactId;
     if ($ufmatch->find(true)) {
         // Save the email in UF Match table
         $ufmatch->email = $emailAddress;
         $ufmatch->save();
         //check if the primary email for the contact exists
         //$contactDetails[1] - email
         //$contactDetails[3] - location id
         $contactDetails = CRM_Contact_BAO_Contact::getEmailDetails($contactId);
         if (trim($contactDetails[1])) {
             //update if record is found
             $query = "UPDATE  civicrm_contact, civicrm_location,civicrm_email\n                     SET email = '" . CRM_Utils_Type::escape($emailAddress, 'String') . "'\n                     WHERE civicrm_location.entity_table = 'civicrm_contact' \n                       AND civicrm_contact.id  = civicrm_location.entity_id \n                       AND civicrm_location.is_primary = 1 \n                       AND civicrm_location.id = civicrm_email.location_id \n                       AND civicrm_email.is_primary = 1   \n                       AND civicrm_contact.id =  " . CRM_Utils_Type::escape($contactId, 'Integer');
             $dao =& new CRM_Core_DAO();
             $dao->query($query);
         } else {
             //else insert a new email record
             $email =& new CRM_Core_DAO_Email();
             $email->location_id = $contactDetails[3];
             $email->is_primary = 1;
             $email->email = $emailAddress;
             $email->save();
         }
     }
 }