/**
  * Register a subscription event.  Create a new contact if one does not
  * already exist.
  *
  * @param int $domain_id        The domain id of the new subscription
  * @param int $group_id         The group id to subscribe to
  * @param string $email         The email address of the (new) contact
  * @return int|null $se_id      The id of the subscription event, null on failure
  * @access public
  * @static
  */
 function &subscribe($domain_id, $group_id, $email)
 {
     /* First, find out if the contact already exists */
     $params = array('email' => $email, 'domain_id' => $domain_id);
     require_once 'CRM/Core/BAO/UFGroup.php';
     $contact_id = CRM_Core_BAO_UFGroup::findContact($params);
     CRM_Core_DAO::transaction('BEGIN');
     if (is_a($contact_id, CRM_Core_Error)) {
         require_once 'CRM/Core/BAO/LocationType.php';
         /* If the contact does not exist, create one. */
         $formatted = array('contact_type' => 'Individual');
         $value = array('email' => $email, 'location_type' => CRM_Core_BAO_LocationType::getDefaultID());
         _crm_add_formatted_param($value, $formatted);
         $contact =& crm_create_contact_formatted($formatted, CRM_IMPORT_PARSER_DUPLICATE_SKIP);
         if (is_a($contact, CRM_Core_Error)) {
             return null;
         }
         $contact_id = $contact->id;
     }
     require_once 'CRM/Core/BAO/Email.php';
     require_once 'CRM/Core/BAO/Location.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     /* Get the primary email id from the contact to use as a hash input */
     $dao =& new CRM_Core_DAO();
     $emailTable = CRM_Core_BAO_Email::getTableName();
     $locTable = CRM_Core_BAO_Location::getTableName();
     $contactTable = CRM_Contact_BAO_Contact::getTableName();
     $dao->query("SELECT {$emailTable}.id as email_id\n                    FROM {$emailTable}\n                    INNER JOIN {$locTable}\n                        ON  {$emailTable}.location_id = {$locTable}.id\n                    WHERE   {$emailTable}.is_primary = 1\n                    AND     {$locTable}.is_primary = 1\n                    AND     {$locTable}.entity_table = '{$contactTable}'\n                    AND     {$locTable}.entity_id = " . CRM_Utils_Type::escape($contact_id, 'Integer'));
     $dao->fetch();
     $se =& new CRM_Mailing_Event_BAO_Subscribe();
     $se->group_id = $group_id;
     $se->contact_id = $contact_id;
     $se->time_stamp = date('YmdHis');
     $se->hash = sha1("{$group_id}:{$contact_id}:{$dao->email_id}");
     $se->save();
     $contacts = array($contact_id);
     require_once 'CRM/Contact/BAO/GroupContact.php';
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Pending', $se->id);
     CRM_Core_DAO::transaction('COMMIT');
     return $se;
 }