Merge pull request #4630 from atif-shaikh/CRM-15546
[civicrm-core.git] / CRM / Mailing / Event / BAO / Subscribe.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36
37 require_once 'Mail/mime.php';
38
39 /**
40 * Class CRM_Mailing_Event_BAO_Subscribe
41 */
42 class CRM_Mailing_Event_BAO_Subscribe extends CRM_Mailing_Event_DAO_Subscribe {
43
44 /**
45 * Class constructor
46 */
47 function __construct() {
48 parent::__construct();
49 }
50
51 /**
52 * Register a subscription event. Create a new contact if one does not
53 * already exist.
54 *
55 * @param int $group_id The group id to subscribe to
56 * @param string $email The email address of the (new) contact
57 * @param int $contactId Currently used during event registration/contribution.
58 * Specifically to avoid linking group to wrong duplicate contact
59 * during event registration.
60 * @param string $context
61 *
62 * @return int|null $se_id The id of the subscription event, null on failure
63 * @access public
64 * @static
65 */
66 public static function &subscribe($group_id, $email, $contactId = NULL, $context = NULL) {
67 // CRM-1797 - allow subscription only to public groups
68 $params = array('id' => (int) $group_id);
69 $defaults = array();
70 $contact_id = NULL;
71 $success = NULL;
72
73 $bao = CRM_Contact_BAO_Group::retrieve($params, $defaults);
74 if ($bao && substr($bao->visibility, 0, 6) != 'Public' && $context != 'profile') {
75 return $success;
76 }
77
78 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
79 $email = $strtolower($email);
80
81 // process the query only if no contactId
82 if ($contactId) {
83 $contact_id = $contactId;
84 }
85 else {
86 /* First, find out if the contact already exists */
87
88 $query = "
89 SELECT DISTINCT contact_a.id as contact_id
90 FROM civicrm_contact contact_a
91 LEFT JOIN civicrm_email ON contact_a.id = civicrm_email.contact_id
92 WHERE civicrm_email.email = %1 AND contact_a.is_deleted = 0";
93
94 $params = array(1 => array($email, 'String'));
95 $dao = CRM_Core_DAO::executeQuery($query, $params);
96 $id = array();
97 // lets just use the first contact id we got
98 if ($dao->fetch()) {
99 $contact_id = $dao->contact_id;
100 }
101 $dao->free();
102 }
103
104 $transaction = new CRM_Core_Transaction();
105
106 if (!$contact_id) {
107 require_once 'CRM/Utils/DeprecatedUtils.php';
108
109 /* If the contact does not exist, create one. */
110
111 $formatted = array(
112 'contact_type' => 'Individual',
113 'version' => 3,
114 );
115 $locationType = CRM_Core_BAO_LocationType::getDefault();
116 $value = array(
117 'email' => $email,
118 'location_type_id' => $locationType->id,
119 );
120 _civicrm_api3_deprecated_add_formatted_param($value, $formatted);
121
122 $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP;
123 $formatted['fixAddress'] = TRUE;
124 require_once 'api/api.php';
125 $contact = civicrm_api('contact', 'create', $formatted);
126 if (civicrm_error($contact)) {
127 return $success;
128 }
129 $contact_id = $contact['id'];
130 }
131 elseif (!is_numeric($contact_id) &&
132 (int ) $contact_id > 0
133 ) {
134 // make sure contact_id is numeric
135 return $success;
136 }
137
138
139 /* Get the primary email id from the contact to use as a hash input */
140
141 $dao = new CRM_Core_DAO();
142
143 $query = "
144 SELECT civicrm_email.id as email_id
145 FROM civicrm_email
146 WHERE civicrm_email.email = %1
147 AND civicrm_email.contact_id = %2";
148 $params = array(1 => array($email, 'String'),
149 2 => array($contact_id, 'Integer'),
150 );
151 $dao = CRM_Core_DAO::executeQuery($query, $params);
152
153 if (!$dao->fetch()) {
154 CRM_Core_Error::fatal('Please file an issue with the backtrace');
155 return $success;
156 }
157
158 $se = new CRM_Mailing_Event_BAO_Subscribe();
159 $se->group_id = $group_id;
160 $se->contact_id = $contact_id;
161 $se->time_stamp = date('YmdHis');
162 $se->hash = substr(sha1("{$group_id}:{$contact_id}:{$dao->email_id}:" . time()),
163 0, 16
164 );
165 $se->save();
166
167 $contacts = array($contact_id);
168 CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id,
169 'Email', 'Pending', $se->id
170 );
171
172 $transaction->commit();
173 return $se;
174 }
175
176 /**
177 * Verify the hash of a subscription event
178 *
179 * @param int $contact_id ID of the contact
180 * @param int $subscribe_id ID of the subscription event
181 * @param string $hash Hash to verify
182 *
183 * @return object|null The subscribe event object, or null on failure
184 * @access public
185 * @static
186 */
187 public static function &verify($contact_id, $subscribe_id, $hash) {
188 $success = NULL;
189 $se = new CRM_Mailing_Event_BAO_Subscribe();
190 $se->contact_id = $contact_id;
191 $se->id = $subscribe_id;
192 $se->hash = $hash;
193 if ($se->find(TRUE)) {
194 $success = $se;
195 }
196 return $success;
197 }
198
199 /**
200 * Ask a contact for subscription confirmation (opt-in)
201 *
202 * @param string $email The email address
203 *
204 * @return void
205 * @access public
206 */
207 public function send_confirm_request($email) {
208 $config = CRM_Core_Config::singleton();
209
210 $domain = CRM_Core_BAO_Domain::getDomain();
211
212 //get the default domain email address.
213 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
214
215 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
216 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
217
218 $confirm = implode($config->verpSeparator,
219 array(
220 $localpart . 'c',
221 $this->contact_id,
222 $this->id,
223 $this->hash,
224 )
225 ) . "@$emailDomain";
226
227 $group = new CRM_Contact_BAO_Group();
228 $group->id = $this->group_id;
229 $group->find(TRUE);
230
231 $component = new CRM_Mailing_BAO_Component();
232 $component->is_default = 1;
233 $component->is_active = 1;
234 $component->component_type = 'Subscribe';
235
236 $component->find(TRUE);
237
238 $headers = array(
239 'Subject' => $component->subject,
240 'From' => "\"{$domainEmailName}\" <{$domainEmailAddress}>",
241 'To' => $email,
242 'Reply-To' => $confirm,
243 'Return-Path' => "do-not-reply@$emailDomain",
244 );
245
246 $url = CRM_Utils_System::url('civicrm/mailing/confirm',
247 "reset=1&cid={$this->contact_id}&sid={$this->id}&h={$this->hash}",
248 TRUE
249 );
250
251 $html = $component->body_html;
252
253 if ($component->body_text) {
254 $text = $component->body_text;
255 }
256 else {
257 $text = CRM_Utils_String::htmlToText($component->body_html);
258 }
259
260 $bao = new CRM_Mailing_BAO_Mailing();
261 $bao->body_text = $text;
262 $bao->body_html = $html;
263 $tokens = $bao->getTokens();
264
265 $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
266 $html = CRM_Utils_Token::replaceSubscribeTokens($html,
267 $group->title,
268 $url, TRUE
269 );
270
271 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
272 $text = CRM_Utils_Token::replaceSubscribeTokens($text,
273 $group->title,
274 $url, FALSE
275 );
276 // render the &amp; entities in text mode, so that the links work
277 $text = str_replace('&amp;', '&', $text);
278
279 $message = new Mail_mime("\n");
280
281 $message->setHTMLBody($html);
282 $message->setTxtBody($text);
283 $b = CRM_Utils_Mail::setMimeParams($message);
284 $h = $message->headers($headers);
285 CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 's',
286 $this->contact_id,
287 $this->id,
288 $this->hash
289 );
290 $mailer = $config->getMailer();
291
292 if (is_object($mailer)) {
293 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
294 $mailer->send($email, $h, $b);
295 unset($errorScope);
296 }
297 }
298
299 /**
300 * Get the domain object given a subscribe event
301 *
302 * @param int $subscribe_id ID of the subscribe event
303 *
304 * @return object $domain The domain owning the event
305 * @access public
306 * @static
307 */
308 public static function &getDomain($subscribe_id) {
309 return CRM_Core_BAO_Domain::getDomain();
310 }
311
312 /**
313 * Get the group details to which given email belongs
314 *
315 * @param string $email email of the contact
316 * @param int $contactID contactID if we want an exact match
317 *
318 * @return array $groups array of group ids
319 * @access public
320 */
321 public static function getContactGroups($email, $contactID = NULL) {
322 if ($contactID) {
323 $query = "
324 SELECT DISTINCT group_a.group_id, group_a.status, civicrm_group.title
325 FROM civicrm_group_contact group_a
326 LEFT JOIN civicrm_group ON civicrm_group.id = group_a.group_id
327 LEFT JOIN civicrm_contact ON ( group_a.contact_id = civicrm_contact.id )
328 WHERE civicrm_contact.id = %1";
329
330 $params = array(1 => array($contactID, 'Integer'));
331 }
332 else {
333 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
334 $email = $strtolower($email);
335
336 $query = "
337 SELECT DISTINCT group_a.group_id, group_a.status, civicrm_group.title
338 FROM civicrm_group_contact group_a
339 LEFT JOIN civicrm_group ON civicrm_group.id = group_a.group_id
340 LEFT JOIN civicrm_contact ON ( group_a.contact_id = civicrm_contact.id ) AND civicrm_contact.is_deleted = 0
341 LEFT JOIN civicrm_email ON civicrm_contact.id = civicrm_email.contact_id
342 WHERE civicrm_email.email = %1";
343
344 $params = array(1 => array($email, 'String'));
345 }
346
347 $dao = CRM_Core_DAO::executeQuery($query, $params);
348 $groups = array();
349 while ($dao->fetch()) {
350 $groups[$dao->group_id] = array(
351 'id' => $dao->group_id,
352 'title' => $dao->title,
353 'status' => $dao->status,
354 );
355 }
356
357 $dao->free();
358 return $groups;
359 }
360
361 /**
362 * Send subscribe mail
363 *
364 * @param array $groups the list of group ids for subscribe
365 * @param array $params the list of email
366 * @param int $contactId Currently used during event registration/contribution.
367 * Specifically to avoid linking group to wrong duplicate contact
368 * during event registration.
369 * @param string $context
370 *
371 * @return void
372 * @static
373 * @access public
374 */
375 public static function commonSubscribe(&$groups, &$params, $contactId = NULL, $context = NULL) {
376 $contactGroups = CRM_Mailing_Event_BAO_Subscribe::getContactGroups($params['email'], $contactId);
377 $group = array();
378 $success = NULL;
379 foreach ($groups as $groupID) {
380 $title = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $groupID, 'title');
381 if (array_key_exists($groupID, $contactGroups) && $contactGroups[$groupID]['status'] != 'Removed') {
382 $group[$groupID]['title'] = $contactGroups[$groupID]['title'];
383
384 $group[$groupID]['status'] = $contactGroups[$groupID]['status'];
385 $status = ts('You are already subscribed in %1, your subscription is %2.', array(1 => $group[$groupID]['title'], 2 => $group[$groupID]['status']));
386 CRM_Utils_System::setUFMessage($status);
387 continue;
388 }
389
390 $se = self::subscribe($groupID,
391 $params['email'], $contactId, $context
392 );
393 if ($se !== NULL) {
394 $success = TRUE;
395 $groupAdded[] = $title;
396
397 // Ask the contact for confirmation
398 $se->send_confirm_request($params['email']);
399 }
400 else {
401 $success = FALSE;
402 $groupFailed[] = $title;
403 }
404 }
405 if ($success) {
406 $groupTitle = implode(', ', $groupAdded);
407 CRM_Utils_System::setUFMessage(ts('Your subscription request has been submitted for %1. Check your inbox shortly for the confirmation email(s). If you do not see a confirmation email, please check your spam/junk mail folder.', array(1 => $groupTitle)));
408 }
409 elseif ($success === FALSE) {
410 $groupTitle = implode(',', $groupFailed);
411 CRM_Utils_System::setUFMessage(ts('We had a problem processing your subscription request for %1. You have tried to subscribe to a private group and/or we encountered a database error. Please contact the site administrator.', array(1 => $groupTitle)));
412 }
413 }
414 }
415