Avoid sending blank invoices
[civicrm-core.git] / CRM / Core / BAO / Domain.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 *
20 */
21 class CRM_Core_BAO_Domain extends CRM_Core_DAO_Domain {
22
23 /**
24 * Cache for a domain's location array
25 * @var array
26 */
27 private $_location = NULL;
28
29 /**
30 * Flushes the cache set by getDomain.
31 *
32 * @see CRM_Core_BAO_Domain::getDomain()
33 * @param CRM_Core_DAO_Domain $domain
34 */
35 public static function onPostSave($domain) {
36 // We want to clear out any cached tokens.
37 // Editing a domain is so rare we can risk being heavy handed.
38 Civi::cache('metadata')->clear();
39 Civi::$statics[__CLASS__]['current'] = NULL;
40 }
41
42 /**
43 * Retrieve DB object and copy to defaults array.
44 *
45 * @param array $params
46 * Array of criteria values.
47 * @param array $defaults
48 * Array to be populated with found values.
49 *
50 * @return self|null
51 * The DAO object, if found.
52 *
53 * @deprecated
54 */
55 public static function retrieve($params, &$defaults) {
56 return self::commonRetrieve(self::class, $params, $defaults);
57 }
58
59 /**
60 * Get the current domain.
61 *
62 * @return \CRM_Core_BAO_Domain
63 * @throws \CRM_Core_Exception
64 */
65 public static function getDomain() {
66 $domain = Civi::$statics[__CLASS__]['current'] ?? NULL;
67 if (!$domain) {
68 $domain = new CRM_Core_BAO_Domain();
69 $domain->id = CRM_Core_Config::domainID();
70 if (!$domain->find(TRUE)) {
71 throw new CRM_Core_Exception('No domain in DB');
72 }
73 Civi::$statics[__CLASS__]['current'] = $domain;
74 }
75 return $domain;
76 }
77
78 /**
79 * @param bool $skipUsingCache
80 *
81 * @return string
82 *
83 * @throws \CRM_Core_Exception
84 */
85 public static function version($skipUsingCache = FALSE) {
86 if ($skipUsingCache) {
87 Civi::$statics[__CLASS__]['current'] = NULL;
88 }
89
90 return self::getDomain()->version;
91 }
92
93 /**
94 * Is a database update required to apply latest schema changes.
95 *
96 * @return bool
97 *
98 * @throws \CRM_Core_Exception
99 */
100 public static function isDBUpdateRequired() {
101 $dbVersion = self::version();
102 $codeVersion = CRM_Utils_System::version();
103 return version_compare($dbVersion, $codeVersion) < 0;
104 }
105
106 /**
107 * Checks that the current DB schema is at least $min version
108 *
109 * @param string|int $min
110 * @return bool
111 */
112 public static function isDBVersionAtLeast($min) {
113 return version_compare(self::version(), $min, '>=');
114 }
115
116 /**
117 * @return string
118 */
119 protected static function getMissingDomainFromEmailMessage(): string {
120 $url = CRM_Utils_System::url('civicrm/admin/options/from_email_address',
121 'reset=1'
122 );
123 $status = ts("There is no valid default from email address configured for the domain. You can configure here <a href='%1'>Configure From Email Address.</a>", [1 => $url]);
124 return $status;
125 }
126
127 /**
128 * Get the location values of a domain.
129 *
130 * @return CRM_Core_BAO_Location[]|NULL
131 */
132 public function getLocationValues() {
133 if ($this->_location == NULL) {
134 $params = [
135 'contact_id' => $this->contact_id,
136 ];
137 $this->_location = CRM_Core_BAO_Location::getValues($params, TRUE);
138
139 if (empty($this->_location)) {
140 $this->_location = NULL;
141 }
142 }
143 return $this->_location;
144 }
145
146 /**
147 * Update a domain.
148 *
149 * @param array $params
150 * @param int $id
151 *
152 * @deprecated
153 * @return CRM_Core_DAO_Domain
154 * @throws \CRM_Core_Exception
155 */
156 public static function edit($params, $id): CRM_Core_DAO_Domain {
157 $params['id'] = $id;
158 return self::writeRecord($params);
159 }
160
161 /**
162 * Create or update domain.
163 *
164 * @deprecated
165 * @param array $params
166 * @return CRM_Core_DAO_Domain
167 */
168 public static function create($params) {
169 return self::writeRecord($params);
170 }
171
172 /**
173 * @return bool
174 */
175 public static function multipleDomains() {
176 $session = CRM_Core_Session::singleton();
177
178 $numberDomains = $session->get('numberDomains');
179 if (!$numberDomains) {
180 $query = 'SELECT count(*) from civicrm_domain';
181 $numberDomains = CRM_Core_DAO::singleValueQuery($query);
182 $session->set('numberDomains', $numberDomains);
183 }
184 return $numberDomains > 1;
185 }
186
187 /**
188 * @param bool $skipFatal
189 * @param bool $returnString
190 * If you are using this second parameter you probably are better
191 * calling `getFromEmail()` which will return an actual string.
192 *
193 * @return array
194 * name & email for domain
195 *
196 * @throws \CRM_Core_Exception
197 */
198 public static function getNameAndEmail($skipFatal = FALSE, $returnString = FALSE) {
199 $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
200 if (!empty($fromEmailAddress)) {
201 if ($returnString) {
202 // Return a string like: "Demonstrators Anonymous" <info@example.org>
203 return $fromEmailAddress;
204 }
205 foreach ($fromEmailAddress as $key => $value) {
206 $email = CRM_Utils_Mail::pluckEmailFromHeader($value);
207 $fromArray = explode('"', $value);
208 $fromName = $fromArray[1] ?? NULL;
209 break;
210 }
211 return [$fromName, $email];
212 }
213
214 if ($skipFatal) {
215 return [NULL, NULL];
216 }
217
218 $status = self::getMissingDomainFromEmailMessage();
219
220 throw new CRM_Core_Exception($status);
221 }
222
223 /**
224 * Get the domain email in a format suitable for using as the from address.
225 *
226 * @return string
227 * @throws \CRM_Core_Exception
228 */
229 public static function getFromEmail(): string {
230 $email = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
231 $email = current($email);
232 if (!$email) {
233 throw new CRM_Core_Exception(self::getMissingDomainFromEmailMessage());
234 }
235 return $email;
236 }
237
238 /**
239 * @param int $contactID
240 *
241 * @return bool|null|object|string
242 *
243 * @throws \CRM_Core_Exception
244 */
245 public static function addContactToDomainGroup($contactID) {
246 $groupID = self::getGroupId();
247
248 if ($groupID) {
249 $contactIDs = [$contactID];
250 CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIDs, $groupID);
251
252 return $groupID;
253 }
254 return FALSE;
255 }
256
257 /**
258 * @return bool|null|object|string
259 *
260 * @throws \CRM_Core_Exception
261 */
262 public static function getGroupId() {
263 static $groupID = NULL;
264
265 if ($groupID) {
266 return $groupID;
267 }
268
269 $domainGroupID = Civi::settings()->get('domain_group_id');
270 $multisite = Civi::settings()->get('is_enabled');
271
272 if ($domainGroupID) {
273 $groupID = $domainGroupID;
274 }
275 elseif ($multisite) {
276 // create a group with that of domain name
277 $title = self::getDomain()->name;
278 $groupID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group',
279 $title, 'id', 'title', TRUE
280 );
281 }
282 return $groupID ? $groupID : FALSE;
283 }
284
285 /**
286 * @param int $groupId
287 *
288 * @return bool
289 *
290 * @throws \CRM_Core_Exception
291 */
292 public static function isDomainGroup($groupId) {
293 $domainGroupID = self::getGroupId();
294 return $domainGroupID == (bool) $groupId;
295 }
296
297 /**
298 * @return array
299 *
300 * @throws \CRM_Core_Exception
301 */
302 public static function getChildGroupIds() {
303 $domainGroupID = self::getGroupId();
304 $childGrps = [];
305
306 if ($domainGroupID) {
307 $childGrps = CRM_Contact_BAO_GroupNesting::getChildGroupIds($domainGroupID);
308 $childGrps[] = $domainGroupID;
309 }
310 return $childGrps;
311 }
312
313 /**
314 * Retrieve a list of contact-ids that belongs to current domain/site.
315 *
316 * @return array
317 *
318 * @throws \CRM_Core_Exception
319 */
320 public static function getContactList() {
321 $siteGroups = CRM_Core_BAO_Domain::getChildGroupIds();
322 $siteContacts = [];
323
324 if (!empty($siteGroups)) {
325 $query = "
326 SELECT cc.id
327 FROM civicrm_contact cc
328 INNER JOIN civicrm_group_contact gc ON
329 (gc.contact_id = cc.id AND gc.status = 'Added' AND gc.group_id IN (" . implode(',', $siteGroups) . "))";
330
331 $dao = CRM_Core_DAO::executeQuery($query);
332 while ($dao->fetch()) {
333 $siteContacts[] = $dao->id;
334 }
335 }
336 return $siteContacts;
337 }
338
339 /**
340 * CRM-20308 & CRM-19657
341 * Return domain information / user information for the usage in receipts
342 * Try default from address then fall back to using logged in user details
343 *
344 * @throws \CiviCRM_API3_Exception
345 */
346 public static function getDefaultReceiptFrom() {
347 $domain = civicrm_api3('domain', 'getsingle', ['id' => CRM_Core_Config::domainID()]);
348 if (!empty($domain['from_email'])) {
349 return [$domain['from_name'], $domain['from_email']];
350 }
351 if (!empty($domain['domain_email'])) {
352 return [$domain['name'], $domain['domain_email']];
353 }
354 $userName = '';
355 $userEmail = '';
356
357 if (!Civi::settings()->get('allow_mail_from_logged_in_contact')) {
358 return [$userName, $userEmail];
359 }
360
361 $userID = CRM_Core_Session::getLoggedInContactID();
362 if (!empty($userID)) {
363 [$userName, $userEmail] = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
364 }
365 // If still empty fall back to the logged in user details.
366 // return empty values no matter what.
367 return [$userName, $userEmail];
368 }
369
370 /**
371 * Get address to be used for system from addresses when a reply is not expected.
372 */
373 public static function getNoReplyEmailAddress() {
374 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
375 return "do-not-reply@$emailDomain";
376 }
377
378 }