/**
 * Subscribe from mailing group
 *
 * @param array $params Associative array of property
 *                       name/value pairs to insert in new 'survey'
 *
 * @throws API_Exception
 * @return array api result array
 * {@getfields mailing_event_subscribe_create}
 * @access public
 */
function civicrm_api3_mailing_event_subscribe_create($params)
{
    $email = $params['email'];
    $group_id = $params['group_id'];
    $contact_id = CRM_Utils_Array::value('contact_id', $params);
    $group = new CRM_Contact_DAO_Group();
    $group->is_active = 1;
    $group->id = (int) $group_id;
    if (!$group->find(TRUE)) {
        throw new API_Exception('Invalid Group id');
    }
    $subscribe = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $email, $contact_id);
    if ($subscribe !== NULL) {
        /* Ask the contact for confirmation */
        $subscribe->send_confirm_request($email);
        $values = array();
        $values[$subscribe->id]['contact_id'] = $subscribe->contact_id;
        $values[$subscribe->id]['subscribe_id'] = $subscribe->id;
        $values[$subscribe->id]['hash'] = $subscribe->hash;
        return civicrm_api3_create_success($values);
    }
    return civicrm_api3_create_error('Subscription failed');
}
 /**
 * takes an associative array and sends a thank you or email verification email
 *
 * @param array $params (reference ) an assoc array of name/value pairs
 *
 * @param $sendEmailMode
 *
 * @throws Exception
 * @return void
   @access public
 * @static
 */
 public static function sendEmail($params, $sendEmailMode)
 {
     /* sendEmailMode
      * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK
      *   connected user via login/pwd - thank you
      *    or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
      *   or login using fb connect - thank you + click to add msg to fb wall
      *
      * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM
      *  send a confirmation request email
      */
     // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it
     $petitionGroupName = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'petition_contacts', NULL, 'Petition Contacts');
     $dao = new CRM_Contact_DAO_Group();
     $dao->title = $petitionGroupName;
     if (!$dao->find(TRUE)) {
         $dao->is_active = 1;
         $dao->visibility = 'User and User Admin Only';
         $dao->save();
     }
     $group_id = $dao->id;
     // get petition info
     $petitionParams['id'] = $params['sid'];
     $petitionInfo = array();
     CRM_Campaign_BAO_Survey::retrieve($petitionParams, $petitionInfo);
     if (empty($petitionInfo)) {
         CRM_Core_Error::fatal('Petition doesn\'t exist.');
     }
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $toName = CRM_Contact_BAO_Contact::displayName($params['contactId']);
     $replyTo = "do-not-reply@{$emailDomain}";
     // set additional general message template params (custom tokens to use in email msg templates)
     // tokens then available in msg template as {$petition.title}, etc
     $petitionTokens['title'] = $petitionInfo['title'];
     $petitionTokens['petitionId'] = $params['sid'];
     $tplParams['petition'] = $petitionTokens;
     switch ($sendEmailMode) {
         case CRM_Campaign_Form_Petition_Signature::EMAIL_THANK:
             // add this contact to the CIVICRM_PETITION_CONTACTS group
             // Cannot pass parameter 1 by reference
             $p = array($params['contactId']);
             CRM_Contact_BAO_GroupContact::addContactsToGroup($p, $group_id, 'API');
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_sign', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title']));
             }
             break;
         case CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM:
             // create mailing event subscription record for this contact
             // this will allow using a hash key to confirm email address by sending a url link
             $se = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $params['email-Primary'], $params['contactId'], 'profile');
             //    require_once 'CRM/Core/BAO/Domain.php';
             //    $domain = CRM_Core_BAO_Domain::getDomain();
             $config = CRM_Core_Config::singleton();
             $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
             $replyTo = implode($config->verpSeparator, array($localpart . 'c', $se->contact_id, $se->id, $se->hash)) . "@{$emailDomain}";
             $confirmUrl = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE);
             $confirmUrlPlainText = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE, NULL, FALSE);
             // set email specific message template params and assign to tplParams
             $petitionTokens['confirmUrl'] = $confirmUrl;
             $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText;
             $tplParams['petition'] = $petitionTokens;
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_confirmation_needed', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title'], 'confirmUrl' => $confirmUrl));
             }
             break;
     }
 }
/**
 * Handle a subscription event
 *
 * @param array $params
 *
 * @return array
 */
function civicrm_mailer_event_subscribe($params)
{
    $errors = _civicrm_mailer_check_params($params, array('email', 'group_id'));
    if (!empty($errors)) {
        return $errors;
    }
    $email = $params['email'];
    $group_id = $params['group_id'];
    $contact_id = CRM_Utils_Array::value('contact_id', $params);
    $group = new CRM_Contact_DAO_Group();
    $group->is_active = 1;
    $group->id = (int) $group_id;
    if (!$group->find(TRUE)) {
        return civicrm_create_error(ts('Invalid Group id'));
    }
    $subscribe = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $email, $contact_id);
    if ($subscribe !== NULL) {
        /* Ask the contact for confirmation */
        $subscribe->send_confirm_request($email);
        $values = array();
        $values['contact_id'] = $subscribe->contact_id;
        $values['subscribe_id'] = $subscribe->id;
        $values['hash'] = $subscribe->hash;
        $values['is_error'] = 0;
        return $values;
    }
    return civicrm_create_error(ts('Subscription failed'));
}
 /**
  * takes an associative array and sends a thank you or email verification email
  *
  * @param array  $params (reference ) an assoc array of name/value pairs
  *
  * @return 
  * @access public
  * @static
  */
 function sendEmail($params, $sendEmailMode)
 {
     /* sendEmailMode
      * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK
      * 		connected user via login/pwd - thank you
      * 	 	or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
      *  	or login using fb connect - thank you + click to add msg to fb wall
      *
      * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM
      *		send a confirmation request email     
      */
     require_once 'CRM/Campaign/Form/Petition/Signature.php';
     // define constant CIVICRM_PETITION_CONTACTS, if not exist in civicrm.settings.php
     if (!defined('CIVICRM_PETITION_CONTACTS')) {
         define('CIVICRM_PETITION_CONTACTS', 'Petition Contacts');
     }
     // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it
     require_once 'api/v2/Group.php';
     $group_params['title'] = CIVICRM_PETITION_CONTACTS;
     $groups = civicrm_group_get($group_params);
     if (CRM_Utils_Array::value('is_error', $groups) == 1 && CRM_Utils_Array::value('error_message', $groups) == 'No such group exists') {
         $group_params['is_active'] = 1;
         $group_params['visibility'] = 'Public Pages';
         $newgroup = civicrm_group_add($group_params);
         if ($newgroup['is_error'] == 0) {
             $group_id[0] = $newgroup['result'];
         }
     } else {
         $group_id = array_keys($groups);
     }
     // get petition info
     $petitionParams['id'] = $params['sid'];
     $petitionInfo = array();
     CRM_Campaign_BAO_Survey::retrieve($petitionParams, $petitionInfo);
     if (empty($petitionInfo)) {
         CRM_Core_Error::fatal('Petition doesn\'t exist.');
     }
     require_once 'CRM/Core/BAO/Domain.php';
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     require_once 'CRM/Core/BAO/MailSettings.php';
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     require_once 'CRM/Contact/BAO/Contact.php';
     $toName = CRM_Contact_BAO_Contact::displayName($params['contactId']);
     $replyTo = "do-not-reply@{$emailDomain}";
     // set additional general message template params (custom tokens to use in email msg templates)
     // tokens then available in msg template as {$petition.title}, etc
     $petitionTokens['title'] = $petitionInfo['title'];
     $petitionTokens['petitionId'] = $params['sid'];
     $tplParams['petition'] = $petitionTokens;
     switch ($sendEmailMode) {
         case CRM_Campaign_Form_Petition_Signature::EMAIL_THANK:
             //add this contact to the CIVICRM_PETITION_CONTACTS group
             require_once 'api/v2/GroupContact.php';
             $params['group_id'] = $group_id[0];
             $params['contact_id'] = $params['contactId'];
             civicrm_group_contact_add($params);
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_sign', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title']));
             }
             break;
         case CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM:
             // create mailing event subscription record for this contact
             // this will allow using a hash key to confirm email address by sending a url link
             require_once 'CRM/Mailing/Event/BAO/Subscribe.php';
             $se = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id[0], $params['email-Primary'], $params['contactId']);
             //				require_once 'CRM/Core/BAO/Domain.php';
             //				$domain =& CRM_Core_BAO_Domain::getDomain();
             $config = CRM_Core_Config::singleton();
             $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
             require_once 'CRM/Utils/Verp.php';
             $replyTo = implode($config->verpSeparator, array($localpart . 'c', $se->contact_id, $se->id, $se->hash)) . "@{$emailDomain}";
             $confirmUrl = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", true);
             $confirmUrlPlainText = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", true, null, false);
             // set email specific message template params and assign to tplParams
             $petitionTokens['confirmUrl'] = $confirmUrl;
             $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText;
             $tplParams['petition'] = $petitionTokens;
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_confirmation_needed', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title'], 'confirmUrl' => $confirmUrl));
             }
             break;
     }
 }
/**
 * Handle a subscription event
 *
 * @param string $email     The email address to subscribe
 * @param int $domain_id    The domain of the subscription
 * @param int $group_id     The group of the subscription
 * @return boolean
 */
function crm_mailer_event_subscribe($email, $domain_id, $group_id)
{
    $se =& CRM_Mailing_Event_BAO_Subscribe::subscribe($domain_id, $group_id, $email);
    if ($se !== null) {
        /* Ask the contact for confirmation */
        $se->send_confirm_request($email);
        return true;
    }
    return false;
}