Merge pull request #18422 from eileenmcnaughton/iso
[civicrm-core.git] / CRM / Member / BAO / MembershipStatus.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 class CRM_Member_BAO_MembershipStatus extends CRM_Member_DAO_MembershipStatus {
18
19 /**
20 * Static holder for the default LT.
21 * @var int
22 */
23 public static $_defaultMembershipStatus = NULL;
24
25 /**
26 * Class constructor.
27 */
28 public function __construct() {
29 parent::__construct();
30 }
31
32 /**
33 * Fetch object based on array of properties.
34 *
35 * @param array $params
36 * (reference ) an assoc array of name/value pairs.
37 * @param array $defaults
38 * (reference ) an assoc array to hold the flattened values.
39 *
40 * @return CRM_Member_BAO_MembershipStatus
41 */
42 public static function retrieve(&$params, &$defaults) {
43 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
44 $membershipStatus->copyValues($params);
45 if ($membershipStatus->find(TRUE)) {
46 CRM_Core_DAO::storeValues($membershipStatus, $defaults);
47 return $membershipStatus;
48 }
49 return NULL;
50 }
51
52 /**
53 * Update the is_active flag in the db.
54 *
55 * @param int $id
56 * Id of the database record.
57 * @param bool $is_active
58 * Value we want to set the is_active field.
59 *
60 * @return bool
61 * true if we found and updated the object, else false
62 */
63 public static function setIsActive($id, $is_active) {
64 return CRM_Core_DAO::setFieldValue('CRM_Member_DAO_MembershipStatus', $id, 'is_active', $is_active);
65 }
66
67 /**
68 * Takes an associative array and creates a membership Status object.
69 *
70 * @param array $params
71 * (reference ) an assoc array of name/value pairs.
72 *
73 * @throws Exception
74 * @return CRM_Member_BAO_MembershipStatus
75 */
76 public static function create($params) {
77 $ids = [];
78 if (!empty($params['id'])) {
79 $ids['membershipStatus'] = $params['id'];
80 }
81 else {
82 //don't allow duplicate names - if id not set
83 $status = new CRM_Member_DAO_MembershipStatus();
84 $status->name = $params['name'];
85 if ($status->find(TRUE)) {
86 throw new Exception('A membership status with this name already exists.');
87 }
88 }
89 $membershipStatusBAO = CRM_Member_BAO_MembershipStatus::add($params, $ids);
90 return $membershipStatusBAO;
91 }
92
93 /**
94 * Add the membership types.
95 *
96 * @param array $params
97 * Reference array contains the values submitted by the form.
98 * @param array $ids
99 * Array contains the id - this param is deprecated.
100 *
101 *
102 * @return object
103 */
104 public static function add(&$params, $ids = []) {
105 $id = $params['id'] ?? $ids['membershipStatus'] ?? NULL;
106 if (!$id) {
107 CRM_Core_DAO::setCreateDefaults($params, self::getDefaults());
108 //copy name to label when not passed.
109 if (empty($params['label']) && !empty($params['name'])) {
110 $params['label'] = $params['name'];
111 }
112
113 if (empty($params['name']) && !empty($params['label'])) {
114 $params['name'] = $params['label'];
115 }
116 }
117
118 // set all other defaults to false.
119 if (!empty($params['is_default'])) {
120 $query = "UPDATE civicrm_membership_status SET is_default = 0";
121 CRM_Core_DAO::executeQuery($query);
122 }
123
124 // action is taken depending upon the mode
125 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
126 $membershipStatus->copyValues($params);
127
128 $membershipStatus->id = $id;
129
130 $membershipStatus->save();
131 CRM_Member_PseudoConstant::flush('membershipStatus');
132 return $membershipStatus;
133 }
134
135 /**
136 * Get defaults for new entity.
137 * @return array
138 */
139 public static function getDefaults() {
140 return [
141 'is_active' => FALSE,
142 'is_current_member' => FALSE,
143 'is_admin' => FALSE,
144 'is_default' => FALSE,
145 ];
146 }
147
148 /**
149 * Get membership status.
150 *
151 * @param int $membershipStatusId
152 *
153 * @return array
154 */
155 public static function getMembershipStatus($membershipStatusId) {
156 $statusDetails = [];
157 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
158 $membershipStatus->id = $membershipStatusId;
159 if ($membershipStatus->find(TRUE)) {
160 CRM_Core_DAO::storeValues($membershipStatus, $statusDetails);
161 }
162 return $statusDetails;
163 }
164
165 /**
166 * Delete membership Types.
167 *
168 * @param int $membershipStatusId
169 *
170 * @throws CRM_Core_Exception
171 */
172 public static function del($membershipStatusId) {
173 //check dependencies
174 //checking if membership status is present in some other table
175 $check = FALSE;
176
177 $dependency = ['Membership', 'MembershipLog'];
178 foreach ($dependency as $name) {
179 $baoString = 'CRM_Member_BAO_' . $name;
180 $dao = new $baoString();
181 $dao->status_id = $membershipStatusId;
182 if ($dao->find(TRUE)) {
183 throw new CRM_Core_Exception(ts('This membership status cannot be deleted as memberships exist with this status'));
184 }
185 }
186 CRM_Utils_Weight::delWeight('CRM_Member_DAO_MembershipStatus', $membershipStatusId);
187 //delete from membership Type table
188 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
189 $membershipStatus->id = $membershipStatusId;
190 if (!$membershipStatus->find()) {
191 throw new CRM_Core_Exception(ts('Cannot delete membership status ' . $membershipStatusId));
192 }
193 $membershipStatus->delete();
194 CRM_Member_PseudoConstant::flush('membershipStatus');
195 }
196
197 /**
198 * Find the membership status based on start date, end date, join date & status date.
199 *
200 * Loop through all the membership status definitions, ordered by their
201 * weight. For each, we loop through all possible variations of the given
202 * start, end, and join dates and adjust the starts and ends based on that
203 * membership status's rules, where the last computed set of adjusted start
204 * and end becomes a candidate. Then we compare that candidate to either
205 * "today" or some other given date, and if it falls between the adjusted
206 * start and end we have a match and we stop looping through status
207 * definitions. Then we call a hook in case that wasn't enough loops.
208 *
209 * @param string $startDate
210 * Start date of the member whose membership status is to be calculated.
211 * @param string $endDate
212 * End date of the member whose membership status is to be calculated.
213 * @param string $joinDate
214 * Join date of the member whose membership status is to be calculated.
215 * @param string $statusDate
216 * Either the string "today" or a date against which we compare the adjusted start and end based on the status rules.
217 * @param bool $excludeIsAdmin
218 * Exclude the statuses having is_admin = 1.
219 * @param int $membershipTypeID
220 * Not used directly but gets passed to the hook.
221 * @param array $membership
222 * Membership params as available to calling function - not used directly but passed to the hook.
223 *
224 * @return array
225 */
226 public static function getMembershipStatusByDate(
227 $startDate, $endDate, $joinDate,
228 $statusDate = 'today', $excludeIsAdmin = FALSE, $membershipTypeID = NULL, $membership = []
229 ) {
230 $membershipDetails = [];
231
232 if (!$statusDate || $statusDate == 'today') {
233 $statusDate = date('Ymd');
234 }
235 else {
236 $statusDate = CRM_Utils_Date::customFormat($statusDate, '%Y%m%d');
237 }
238
239 //fix for CRM-3570, if we have statuses with is_admin=1,
240 //exclude these statuses from calculatation during import.
241 $where = "is_active = 1";
242 if ($excludeIsAdmin) {
243 $where .= " AND is_admin != 1";
244 }
245
246 $query = "
247 SELECT *
248 FROM civicrm_membership_status
249 WHERE {$where}
250 ORDER BY weight ASC";
251
252 $membershipStatus = CRM_Core_DAO::executeQuery($query);
253
254 $dates = [
255 'start' => ($startDate && $startDate !== 'null') ? date('Ymd', strtotime($startDate)) : '',
256 'end' => ($endDate && $endDate !== 'null') ? date('Ymd', strtotime($endDate)) : '',
257 'join' => ($joinDate && $joinDate !== 'null') ? date('Ymd', strtotime($joinDate)) : '',
258 ];
259
260 while ($membershipStatus->fetch()) {
261 $startEvent = NULL;
262 $endEvent = NULL;
263 foreach (['start', 'end'] as $eve) {
264 foreach ($dates as $dat => $date) {
265 // calculate start-event/date and end-event/date
266 if (($membershipStatus->{$eve . '_event'} === $dat . '_date') &&
267 $date
268 ) {
269 if ($membershipStatus->{$eve . '_event_adjust_unit'} &&
270 $membershipStatus->{$eve . '_event_adjust_interval'}
271 ) {
272 $month = date('m', strtotime($date));
273 $day = date('d', strtotime($date));
274 $year = date('Y', strtotime($date));
275 // add in months
276 if ($membershipStatus->{$eve . '_event_adjust_unit'} === 'month') {
277 ${$eve . 'Event'} = date('Ymd', mktime(0, 0, 0,
278 $month + $membershipStatus->{$eve . '_event_adjust_interval'},
279 $day,
280 $year
281 ));
282 }
283 // add in days
284 if ($membershipStatus->{$eve . '_event_adjust_unit'} === 'day') {
285 ${$eve . 'Event'} = date('Ymd', mktime(0, 0, 0,
286 $month,
287 $day + $membershipStatus->{$eve . '_event_adjust_interval'},
288 $year
289 ));
290 }
291 // add in years
292 if ($membershipStatus->{$eve . '_event_adjust_unit'} === 'year') {
293 ${$eve . 'Event'} = date('Ymd', mktime(0, 0, 0,
294 $month,
295 $day,
296 $year + $membershipStatus->{$eve . '_event_adjust_interval'}
297 ));
298 }
299 // if no interval and unit, present
300 }
301 else {
302 ${$eve . 'Event'} = $date;
303 }
304 }
305 }
306 }
307
308 // check if statusDate is in the range of start & end events.
309 if ($startEvent && $endEvent) {
310 if (($statusDate >= $startEvent) && ($statusDate <= $endEvent)) {
311 $membershipDetails['id'] = $membershipStatus->id;
312 $membershipDetails['name'] = $membershipStatus->name;
313 }
314 }
315 elseif ($startEvent) {
316 if ($statusDate >= $startEvent) {
317 $membershipDetails['id'] = $membershipStatus->id;
318 $membershipDetails['name'] = $membershipStatus->name;
319 }
320 }
321 elseif ($endEvent) {
322 if ($statusDate <= $endEvent) {
323 $membershipDetails['id'] = $membershipStatus->id;
324 $membershipDetails['name'] = $membershipStatus->name;
325 }
326 }
327
328 // returns FIRST status record for which status_date is in range.
329 if ($membershipDetails) {
330 break;
331 }
332 }
333 //end fetch
334
335 //we bundle the arguments into an array as we can't pass 8 variables to the hook otherwise
336 // the membership array might contain the pre-altered settings so we don't want to merge this
337 $arguments = [
338 'start_date' => $startDate,
339 'end_date' => $endDate,
340 'join_date' => $joinDate,
341 'status_date' => $statusDate,
342 'exclude_is_admin' => $endDate,
343 'membership_type_id' => $membershipTypeID,
344 'start_event' => $startEvent,
345 'end_event' => $endEvent,
346 ];
347 CRM_Utils_Hook::alterCalculatedMembershipStatus($membershipDetails, $arguments, $membership);
348 return $membershipDetails;
349 }
350
351 /**
352 * Function that return the status ids whose is_current_member is set.
353 *
354 * @return array
355 */
356 public static function getMembershipStatusCurrent() {
357 $statusIds = [];
358 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
359 $membershipStatus->is_current_member = 1;
360 $membershipStatus->find();
361 $membershipStatus->selectAdd();
362 $membershipStatus->selectAdd('id');
363 while ($membershipStatus->fetch()) {
364 $statusIds[] = $membershipStatus->id;
365 }
366 return $statusIds;
367 }
368
369 }