dev/core#562 Remove more DAO->free() calls
[civicrm-core.git] / CRM / Mailing / Event / BAO / Subscribe.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
32 */
33
34
35 require_once 'Mail/mime.php';
36
37 /**
38 * Class CRM_Mailing_Event_BAO_Subscribe
39 */
40 class CRM_Mailing_Event_BAO_Subscribe extends CRM_Mailing_Event_DAO_Subscribe {
41
42 /**
43 * Class constructor.
44 */
45 public function __construct() {
46 parent::__construct();
47 }
48
49 /**
50 * Register a subscription event. Create a new contact if one does not
51 * already exist.
52 *
53 * @param int $group_id
54 * The group id to subscribe to.
55 * @param string $email
56 * The email address of the (new) contact.
57 * @param int $contactId
58 * Currently used during event registration/contribution.
59 * Specifically to avoid linking group to wrong duplicate contact
60 * during event registration.
61 * @param string $context
62 *
63 * @return int|null
64 * $se_id The id of the subscription event, null on failure
65 */
66 public static function &subscribe($group_id, $email, $contactId = NULL, $context = NULL) {
67 // CRM-1797 - allow subscription only to public groups
68 $params = ['id' => (int) $group_id];
69 $defaults = [];
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 = [1 => [$email, 'String']];
95 $dao = CRM_Core_DAO::executeQuery($query, $params);
96 // lets just use the first contact id we got
97 if ($dao->fetch()) {
98 $contact_id = $dao->contact_id;
99 }
100 }
101
102 $transaction = new CRM_Core_Transaction();
103
104 if (!$contact_id) {
105 $locationType = CRM_Core_BAO_LocationType::getDefault();
106 $formatted = [
107 'contact_type' => 'Individual',
108 'email' => $email,
109 'location_type_id' => $locationType->id,
110 ];
111
112 $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP;
113 $formatted['fixAddress'] = TRUE;
114 $contact = civicrm_api3('contact', 'create', $formatted);
115 if (civicrm_error($contact)) {
116 return $success;
117 }
118 $contact_id = $contact['id'];
119 }
120 elseif (!is_numeric($contact_id) &&
121 (int ) $contact_id > 0
122 ) {
123 // make sure contact_id is numeric
124 return $success;
125 }
126
127 // Get the primary email id from the contact to use as a hash input.
128 $query = "
129 SELECT civicrm_email.id as email_id
130 FROM civicrm_email
131 WHERE civicrm_email.email = %1
132 AND civicrm_email.contact_id = %2";
133 $params = [
134 1 => [$email, 'String'],
135 2 => [$contact_id, 'Integer'],
136 ];
137 $dao = CRM_Core_DAO::executeQuery($query, $params);
138
139 if (!$dao->fetch()) {
140 CRM_Core_Error::fatal('Please file an issue with the backtrace');
141 return $success;
142 }
143
144 $se = new CRM_Mailing_Event_BAO_Subscribe();
145 $se->group_id = $group_id;
146 $se->contact_id = $contact_id;
147 $se->time_stamp = date('YmdHis');
148 $se->hash = substr(sha1("{$group_id}:{$contact_id}:{$dao->email_id}:" . time()),
149 0, 16
150 );
151 $se->save();
152
153 $contacts = [$contact_id];
154 CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id,
155 'Email', 'Pending', $se->id
156 );
157
158 $transaction->commit();
159 return $se;
160 }
161
162 /**
163 * Verify the hash of a subscription event.
164 *
165 * @param int $contact_id
166 * ID of the contact.
167 * @param int $subscribe_id
168 * ID of the subscription event.
169 * @param string $hash
170 * Hash to verify.
171 *
172 * @return object|null
173 * The subscribe event object, or null on failure
174 */
175 public static function &verify($contact_id, $subscribe_id, $hash) {
176 $success = NULL;
177 $se = new CRM_Mailing_Event_BAO_Subscribe();
178 $se->contact_id = $contact_id;
179 $se->id = $subscribe_id;
180 $se->hash = $hash;
181 if ($se->find(TRUE)) {
182 $success = $se;
183 }
184 return $success;
185 }
186
187 /**
188 * Ask a contact for subscription confirmation (opt-in)
189 *
190 * @param string $email
191 * The email address.
192 */
193 public function send_confirm_request($email) {
194 $config = CRM_Core_Config::singleton();
195
196 $domain = CRM_Core_BAO_Domain::getDomain();
197
198 //get the default domain email address.
199 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
200
201 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
202 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
203
204 $confirm = implode($config->verpSeparator,
205 [
206 $localpart . 'c',
207 $this->contact_id,
208 $this->id,
209 $this->hash,
210 ]
211 ) . "@$emailDomain";
212
213 $group = new CRM_Contact_BAO_Group();
214 $group->id = $this->group_id;
215 $group->find(TRUE);
216
217 $component = new CRM_Mailing_BAO_MailingComponent();
218 $component->is_default = 1;
219 $component->is_active = 1;
220 $component->component_type = 'Subscribe';
221
222 $component->find(TRUE);
223
224 $headers = [
225 'Subject' => $component->subject,
226 'From' => "\"{$domainEmailName}\" <{$domainEmailAddress}>",
227 'To' => $email,
228 'Reply-To' => $confirm,
229 'Return-Path' => CRM_Core_BAO_Domain::getNoReplyEmailAddress(),
230 ];
231
232 $url = CRM_Utils_System::url('civicrm/mailing/confirm',
233 "reset=1&cid={$this->contact_id}&sid={$this->id}&h={$this->hash}",
234 TRUE
235 );
236
237 $html = $component->body_html;
238
239 if ($component->body_text) {
240 $text = $component->body_text;
241 }
242 else {
243 $text = CRM_Utils_String::htmlToText($component->body_html);
244 }
245
246 $bao = new CRM_Mailing_BAO_Mailing();
247 $bao->body_text = $text;
248 $bao->body_html = $html;
249 $tokens = $bao->getTokens();
250
251 $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
252 $html = CRM_Utils_Token::replaceSubscribeTokens($html,
253 $group->title,
254 $url, TRUE
255 );
256
257 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
258 $text = CRM_Utils_Token::replaceSubscribeTokens($text,
259 $group->title,
260 $url, FALSE
261 );
262 // render the &amp; entities in text mode, so that the links work
263 $text = str_replace('&amp;', '&', $text);
264
265 $message = new Mail_mime("\n");
266
267 $message->setHTMLBody($html);
268 $message->setTxtBody($text);
269 $b = CRM_Utils_Mail::setMimeParams($message);
270 $h = $message->headers($headers);
271 CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 's',
272 $this->contact_id,
273 $this->id,
274 $this->hash
275 );
276 $mailer = \Civi::service('pear_mail');
277
278 if (is_object($mailer)) {
279 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
280 $mailer->send($email, $h, $b);
281 unset($errorScope);
282 }
283 }
284
285 /**
286 * Get the domain object given a subscribe event.
287 *
288 * @param int $subscribe_id
289 * ID of the subscribe event.
290 *
291 * @return object
292 * $domain The domain owning the event
293 */
294 public static function &getDomain($subscribe_id) {
295 return CRM_Core_BAO_Domain::getDomain();
296 }
297
298 /**
299 * Get the group details to which given email belongs.
300 *
301 * @param string $email
302 * Email of the contact.
303 * @param int $contactID
304 * ContactID if we want an exact match.
305 *
306 * @return array
307 * array of group ids
308 */
309 public static function getContactGroups($email, $contactID = NULL) {
310 if ($contactID) {
311 $query = "
312 SELECT DISTINCT group_a.group_id, group_a.status, civicrm_group.title
313 FROM civicrm_group_contact group_a
314 LEFT JOIN civicrm_group ON civicrm_group.id = group_a.group_id
315 LEFT JOIN civicrm_contact ON ( group_a.contact_id = civicrm_contact.id )
316 WHERE civicrm_contact.id = %1";
317
318 $params = [1 => [$contactID, 'Integer']];
319 }
320 else {
321 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
322 $email = $strtolower($email);
323
324 $query = "
325 SELECT DISTINCT group_a.group_id, group_a.status, civicrm_group.title
326 FROM civicrm_group_contact group_a
327 LEFT JOIN civicrm_group ON civicrm_group.id = group_a.group_id
328 LEFT JOIN civicrm_contact ON ( group_a.contact_id = civicrm_contact.id ) AND civicrm_contact.is_deleted = 0
329 LEFT JOIN civicrm_email ON civicrm_contact.id = civicrm_email.contact_id
330 WHERE civicrm_email.email = %1";
331
332 $params = [1 => [$email, 'String']];
333 }
334
335 $dao = CRM_Core_DAO::executeQuery($query, $params);
336 $groups = [];
337 while ($dao->fetch()) {
338 $groups[$dao->group_id] = [
339 'id' => $dao->group_id,
340 'title' => $dao->title,
341 'status' => $dao->status,
342 ];
343 }
344
345 return $groups;
346 }
347
348 /**
349 * Send subscribe mail.
350 *
351 * @param array $groups
352 * The list of group ids for subscribe.
353 * @param array $params
354 * The list of email.
355 * @param int $contactId
356 * Currently used during event registration/contribution.
357 * Specifically to avoid linking group to wrong duplicate contact
358 * during event registration.
359 * @param string $context
360 */
361 public static function commonSubscribe(&$groups, &$params, $contactId = NULL, $context = NULL) {
362 $contactGroups = CRM_Mailing_Event_BAO_Subscribe::getContactGroups($params['email'], $contactId);
363 $group = [];
364 $success = NULL;
365 foreach ($groups as $groupID) {
366 $title = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $groupID, 'title');
367 if (array_key_exists($groupID, $contactGroups) && $contactGroups[$groupID]['status'] != 'Removed') {
368 $group[$groupID]['title'] = $contactGroups[$groupID]['title'];
369
370 $group[$groupID]['status'] = $contactGroups[$groupID]['status'];
371 $status = ts('You are already subscribed in %1, your subscription is %2.', [
372 1 => $group[$groupID]['title'],
373 2 => ts($group[$groupID]['status']),
374 ]);
375 CRM_Utils_System::setUFMessage($status);
376 continue;
377 }
378
379 $se = self::subscribe($groupID,
380 $params['email'], $contactId, $context
381 );
382 if ($se !== NULL) {
383 $success = TRUE;
384 $groupAdded[] = $title;
385
386 // Ask the contact for confirmation
387 $se->send_confirm_request($params['email']);
388 }
389 else {
390 $success = FALSE;
391 $groupFailed[] = $title;
392 }
393 }
394 if ($success) {
395 $groupTitle = implode(', ', $groupAdded);
396 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.', [1 => $groupTitle]));
397 }
398 elseif ($success === FALSE) {
399 $groupTitle = implode(',', $groupFailed);
400 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.', [1 => $groupTitle]));
401 }
402 }
403
404 }