Merge pull request #1 from civicrm/master
[civicrm-core.git] / CRM / Core / BAO / RecurringEntity.php
CommitLineData
0775436c
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
0775436c 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
0775436c
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
0775436c
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
0775436c
TO
32 */
33
2ba9aad6 34use When\When;
0775436c 35
1cd3ffa9 36/**
8eedd10a 37 * Class CRM_Core_BAO_RecurringEntity.
1cd3ffa9 38 */
0775436c
TO
39class CRM_Core_BAO_RecurringEntity extends CRM_Core_DAO_RecurringEntity {
40
41 const RUNNING = 1;
be2fb01f 42 public $schedule = [];
0775436c 43 public $scheduleId = NULL;
be2fb01f 44 public $scheduleFormValues = [];
0775436c 45
be2fb01f
CW
46 public $dateColumns = [];
47 public $overwriteColumns = [];
48 public $intervalDateColumns = [];
49 public $excludeDates = [];
0775436c 50
be2fb01f 51 public $linkedEntities = [];
0775436c
TO
52
53 public $isRecurringEntityRecord = TRUE;
54
55 protected $recursion = NULL;
56 protected $recursion_start_date = NULL;
57
be2fb01f 58 public static $_entitiesToBeDeleted = [];
0775436c
TO
59
60 public static $status = NULL;
61
518fa0ee 62 public static $_recurringEntityHelper
be2fb01f
CW
63 = [
64 'civicrm_event' => [
0775436c
TO
65 'helper_class' => 'CRM_Event_DAO_Event',
66 'delete_func' => 'delete',
e7483cbe 67 'pre_delete_func' => 'CRM_Event_Form_ManageEvent_Repeat::checkRegistrationForEvents',
be2fb01f
CW
68 ],
69 'civicrm_activity' => [
0775436c
TO
70 'helper_class' => 'CRM_Activity_DAO_Activity',
71 'delete_func' => 'delete',
e7483cbe 72 'pre_delete_func' => '',
be2fb01f
CW
73 ],
74 ];
0775436c 75
518fa0ee 76 public static $_dateColumns
be2fb01f
CW
77 = [
78 'civicrm_event' => [
79 'dateColumns' => ['start_date'],
80 'excludeDateRangeColumns' => ['start_date', 'end_date'],
81 'intervalDateColumns' => ['end_date'],
82 ],
83 'civicrm_activity' => [
84 'dateColumns' => ['activity_date_time'],
85 ],
86 ];
0775436c 87
518fa0ee 88 public static $_tableDAOMapper
be2fb01f 89 = [
353ffa53 90 'civicrm_event' => 'CRM_Event_DAO_Event',
0775436c 91 'civicrm_price_set_entity' => 'CRM_Price_DAO_PriceSetEntity',
353ffa53 92 'civicrm_uf_join' => 'CRM_Core_DAO_UFJoin',
0775436c 93 'civicrm_tell_friend' => 'CRM_Friend_DAO_Friend',
353ffa53
TO
94 'civicrm_pcp_block' => 'CRM_PCP_DAO_PCPBlock',
95 'civicrm_activity' => 'CRM_Activity_DAO_Activity',
96 'civicrm_activity_contact' => 'CRM_Activity_DAO_ActivityContact',
be2fb01f 97 ];
0775436c 98
518fa0ee 99 public static $_updateSkipFields
be2fb01f
CW
100 = [
101 'civicrm_event' => ['start_date', 'end_date'],
102 'civicrm_tell_friend' => ['entity_id'],
103 'civicrm_pcp_block' => ['entity_id'],
104 'civicrm_activity' => ['activity_date_time'],
105 ];
0775436c 106
518fa0ee 107 public static $_linkedEntitiesInfo
be2fb01f
CW
108 = [
109 'civicrm_tell_friend' => [
353ffa53 110 'entity_id_col' => 'entity_id',
e7483cbe 111 'entity_table_col' => 'entity_table',
be2fb01f
CW
112 ],
113 'civicrm_price_set_entity' => [
353ffa53 114 'entity_id_col' => 'entity_id',
0775436c 115 'entity_table_col' => 'entity_table',
353ffa53 116 'is_multirecord' => TRUE,
be2fb01f
CW
117 ],
118 'civicrm_uf_join' => [
353ffa53 119 'entity_id_col' => 'entity_id',
0775436c 120 'entity_table_col' => 'entity_table',
353ffa53 121 'is_multirecord' => TRUE,
be2fb01f
CW
122 ],
123 'civicrm_pcp_block' => [
353ffa53 124 'entity_id_col' => 'entity_id',
e7483cbe 125 'entity_table_col' => 'entity_table',
be2fb01f
CW
126 ],
127 ];
0775436c 128
b0f2e06f
RJ
129 //Define global CLASS CONSTANTS for recurring entity mode types
130 const MODE_THIS_ENTITY_ONLY = 1;
131 const MODE_NEXT_ALL_ENTITY = 2;
132 const MODE_ALL_ENTITY_IN_SERIES = 3;
133
2e2605fe
EM
134 /**
135 * Getter for status.
136 *
137 * @return string
138 */
0775436c
TO
139 public static function getStatus() {
140 return self::$status;
141 }
142
2e2605fe
EM
143 /**
144 * Setter for status.
145 *
146 * @param string $status
147 */
0775436c
TO
148 public static function setStatus($status) {
149 self::$status = $status;
150 }
353ffa53 151
0775436c 152 /**
2e2605fe 153 * Save records in civicrm_recurring_entity table.
0775436c 154 *
6a0b768e 155 * @param array $params
2e2605fe 156 * Reference array contains the values submitted by the form.
0775436c
TO
157 *
158 * @return object
159 */
160 public static function add(&$params) {
b53cbfbc 161 if (!empty($params['id'])) {
0775436c
TO
162 CRM_Utils_Hook::pre('edit', 'RecurringEntity', $params['id'], $params);
163 }
164 else {
165 CRM_Utils_Hook::pre('create', 'RecurringEntity', NULL, $params);
166 }
167
168 $daoRecurringEntity = new CRM_Core_DAO_RecurringEntity();
169 $daoRecurringEntity->copyValues($params);
170 $daoRecurringEntity->find(TRUE);
171 $result = $daoRecurringEntity->save();
172
b53cbfbc 173 if (!empty($params['id'])) {
0775436c
TO
174 CRM_Utils_Hook::post('edit', 'RecurringEntity', $daoRecurringEntity->id, $daoRecurringEntity);
175 }
176 else {
177 CRM_Utils_Hook::post('create', 'RecurringEntity', $daoRecurringEntity->id, $daoRecurringEntity);
178 }
179 return $result;
180 }
181
182 /**
183 * Wrapper for the function add() to add entry in recurring entity
184 *
6a0b768e
TO
185 * @param int $parentId
186 * Parent entity id .
187 * @param int $entityId
188 * Child entity id .
189 * @param string $entityTable
190 * Name of the entity table .
0775436c 191 *
0775436c
TO
192 *
193 * @return object
194 */
195 public static function quickAdd($parentId, $entityId, $entityTable) {
e7483cbe 196 $params
be2fb01f 197 = [
353ffa53
TO
198 'parent_id' => $parentId,
199 'entity_id' => $entityId,
e7483cbe 200 'entity_table' => $entityTable,
be2fb01f 201 ];
0775436c
TO
202 return self::add($params);
203 }
204
205 /**
fe482240 206 * This function updates the mode column in the civicrm_recurring_entity table.
0775436c 207 *
6a0b768e 208 * @param int $mode
8eedd10a 209 * Mode of the entity to cascade changes across parent/child relations eg 1 - only this entity, 2 - this and the following entities, 3 - All the entity.
0775436c
TO
210 */
211 public function mode($mode) {
212 if ($this->entity_id && $this->entity_table) {
213 if ($this->find(TRUE)) {
214 $this->mode = $mode;
215 }
216 else {
217 $this->parent_id = $this->entity_id;
218 $this->mode = $mode;
219 }
220 $this->save();
221 }
222 }
223
224 /**
fe482240 225 * This function generates all new entities based on object vars.
0775436c
TO
226 *
227 * @return array
228 */
229 public function generate() {
230 $this->generateRecursiveDates();
231
232 return $this->generateEntities();
233 }
234
235 /**
236 * This function builds a "When" object based on schedule/reminder params
237 *
a6c01b45
CW
238 * @return object
239 * When object
0775436c
TO
240 */
241 public function generateRecursion() {
242 // return if already generated
30aa3e54 243 if (is_a($this->recursion, 'When\When')) {
0775436c
TO
244 return $this->recursion;
245 }
246
247 if ($this->scheduleId) {
248 // get params by ID
249 $this->schedule = $this->getScheduleParams($this->scheduleId);
250 }
251 elseif (!empty($this->scheduleFormValues)) {
252 $this->schedule = $this->mapFormValuesToDB($this->scheduleFormValues);
253 }
254
255 if (!empty($this->schedule)) {
256 $this->recursion = $this->getRecursionFromSchedule($this->schedule);
257 }
258 return $this->recursion;
259 }
260
261 /**
fe482240 262 * Generate new DAOs and along with entries in civicrm_recurring_entity table.
0775436c
TO
263 *
264 * @return array
265 */
266 public function generateEntities() {
267 self::setStatus(self::RUNNING);
268
be2fb01f
CW
269 $newEntities = [];
270 $findCriteria = [];
0775436c
TO
271 if (!empty($this->recursionDates)) {
272 if ($this->entity_id) {
be2fb01f 273 $findCriteria = ['id' => $this->entity_id];
0775436c
TO
274
275 // save an entry with initiating entity-id & entity-table
276 if ($this->entity_table && !$this->find(TRUE)) {
277 $this->parent_id = $this->entity_id;
278 $this->save();
279 }
280 }
281 if (empty($findCriteria)) {
282 CRM_Core_Error::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
283 }
284
285 $count = 0;
286 foreach ($this->recursionDates as $key => $dateCols) {
287 $newCriteria = $dateCols;
288 foreach ($this->overwriteColumns as $col => $val) {
289 $newCriteria[$col] = $val;
290 }
291 // create main entities
292 $obj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($this->entity_table,
293 $findCriteria,
294 $newCriteria,
295 $this->isRecurringEntityRecord
296 );
297
298 if (is_a($obj, 'CRM_Core_DAO') && $obj->id) {
be2fb01f 299 $newCriteria = [];
0775436c
TO
300 $newEntities[$this->entity_table][$count] = $obj->id;
301
302 foreach ($this->linkedEntities as $linkedInfo) {
303 foreach ($linkedInfo['linkedColumns'] as $col) {
304 $newCriteria[$col] = $obj->id;
305 }
306 // create linked entities
307 $linkedObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($linkedInfo['table'],
308 $linkedInfo['findCriteria'],
309 $newCriteria,
310 CRM_Utils_Array::value('isRecurringEntityRecord', $linkedInfo, TRUE)
311 );
312
313 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id) {
314 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id;
315 }
316 }
317 }
318 $count++;
319 }
320 }
321
322 self::$status = NULL;
323 return $newEntities;
324 }
325
326 /**
b44e3f84 327 * This function iterates through when object criteria and
0775436c
TO
328 * generates recursive dates based on that
329 *
a6c01b45
CW
330 * @return array
331 * array of dates
0775436c
TO
332 */
333 public function generateRecursiveDates() {
334 $this->generateRecursion();
335
be2fb01f 336 $recursionDates = [];
2ba9aad6 337 if (is_a($this->recursion, 'When\When')) {
0775436c
TO
338 $initialCount = CRM_Utils_Array::value('start_action_offset', $this->schedule);
339
340 $exRangeStart = $exRangeEnd = NULL;
341 if (!empty($this->excludeDateRangeColumns)) {
342 $exRangeStart = $this->excludeDateRangeColumns[0];
353ffa53 343 $exRangeEnd = $this->excludeDateRangeColumns[1];
0775436c
TO
344 }
345
30aa3e54
PZ
346 if (CRM_Core_Config::singleton()->userFramework == 'UnitTests') {
347 $this->recursion->RFC5545_COMPLIANT = When::IGNORE;
348 }
0775436c 349 $count = 1;
30aa3e54
PZ
350 $result = $this->recursion_start_date;
351 while ($result = $this->getNextOccurrence($result)) {
352 $skip = FALSE;
353 if ($result == $this->recursion_start_date) {
354 // skip the recursion-start-date from the list we going to generate
355 $skip = TRUE;
5e73744d 356 }
1043bac2 357 $baseDate = $result->format('YmdHis');
0775436c
TO
358
359 foreach ($this->dateColumns as $col) {
360 $recursionDates[$count][$col] = $baseDate;
361 }
362 foreach ($this->intervalDateColumns as $col => $interval) {
363 $newDate = new DateTime($baseDate);
364 $newDate->add($interval);
1043bac2 365 $recursionDates[$count][$col] = $newDate->format('YmdHis');
0775436c
TO
366 }
367 if ($exRangeStart) {
3b39fda2
CW
368 $exRangeStartDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value($exRangeStart, $recursionDates[$count]), NULL, FALSE, 'Ymd');
369 $exRangeEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value($exRangeEnd, $recursionDates[$count]), NULL, FALSE, 'Ymd');
0775436c
TO
370 }
371
372 foreach ($this->excludeDates as $exDate) {
373 $exDate = CRM_Utils_Date::processDate($exDate, NULL, FALSE, 'Ymd');
374 if (!$exRangeStart) {
375 if ($exDate == $result->format('Ymd')) {
376 $skip = TRUE;
377 break;
378 }
379 }
380 else {
381 if (($exDate == $exRangeStartDate) ||
382 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
383 ) {
384 $skip = TRUE;
385 break;
386 }
387 }
388 }
389
30aa3e54
PZ
390 if ($skip) {
391 unset($recursionDates[$count]);
392 if ($initialCount && ($initialCount > 0)) {
393 // lets increase the counter, so we get correct number of occurrences
394 $initialCount++;
395 $this->recursion->count($initialCount);
396 }
397 continue;
398 }
0775436c
TO
399 $count++;
400 }
401 }
402 $this->recursionDates = $recursionDates;
403
404 return $recursionDates;
405 }
406
407 /**
fe482240 408 * This function gets all the children for a particular parent entity.
0775436c 409 *
6a0b768e
TO
410 * @param int $parentId
411 * Parent entity id .
412 * @param string $entityTable
413 * Name of the entity table .
414 * @param bool $includeParent
415 * If true parent id is included in result set and vice versa .
416 * @param int $mode
417 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
418 * @param int $initiatorId
419 * The instance where this function is invoked from .
0775436c 420 *
0775436c 421 *
a6c01b45
CW
422 * @return array
423 * an array of child ids
0775436c 424 */
518fa0ee 425 public static function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
be2fb01f 426 $entities = [];
0775436c
TO
427 if (empty($parentId) || empty($entityTable)) {
428 return $entities;
429 }
430
431 if (!$initiatorId) {
432 $initiatorId = $parentId;
433 }
434
be2fb01f
CW
435 $queryParams = [
436 1 => [$parentId, 'Integer'],
437 2 => [$entityTable, 'String'],
438 3 => [$initiatorId, 'Integer'],
439 ];
0775436c
TO
440
441 if (!$mode) {
442 $mode = CRM_Core_DAO::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
443 }
444
445 $query = "SELECT *
446 FROM civicrm_recurring_entity
447 WHERE parent_id = %1 AND entity_table = %2";
448 if (!$includeParent) {
449 $query .= " AND entity_id != " . ($initiatorId ? "%3" : "%1");
450 }
451
e7483cbe
J
452 // MODE = SINGLE
453 if ($mode == '1') {
0775436c
TO
454 $query .= " AND entity_id = %3";
455 }
e7483cbe
J
456 // MODE = FUTURE
457 elseif ($mode == '2') {
0775436c
TO
458 $recurringEntityID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
459 if ($recurringEntityID) {
460 $query .= $includeParent ? " AND id >= %4" : " AND id > %4";
518fa0ee
SL
461 // FIXME: change to order by dates
462 $query .= " ORDER BY id ASC";
be2fb01f 463 $queryParams[4] = [$recurringEntityID, 'Integer'];
0775436c
TO
464 }
465 else {
466 // something wrong, return empty
be2fb01f 467 return [];
0775436c
TO
468 }
469 }
470
471 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
472 while ($dao->fetch()) {
473 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table;
474 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id;
475 }
476 return $entities;
477 }
478
479 /**
480 * This function when passed an entity id checks if it has parent and
481 * returns all other entities that are connected to same parent.
482 *
6a0b768e
TO
483 * @param int $entityId
484 * Entity id .
485 * @param string $entityTable
486 * Entity table name .
487 * @param bool $includeParent
488 * Include parent in result set .
489 * @param int $mode
490 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
0775436c 491 *
0775436c 492 *
a6c01b45
CW
493 * @return array
494 * array of connected ids
0775436c 495 */
518fa0ee 496 public static function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
0775436c
TO
497 $parentId = self::getParentFor($entityId, $entityTable);
498 if ($parentId) {
499 return self::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
500 }
be2fb01f 501 return [];
0775436c
TO
502 }
503
504 /**
fe482240 505 * This function gets the parent for the entity id passed to it.
0775436c 506 *
6a0b768e
TO
507 * @param int $entityId
508 * Entity ID .
509 * @param string $entityTable
510 * Entity table name .
511 * @param bool $includeParent
512 * Include parent in result set .
0775436c 513 *
0775436c 514 *
a6c01b45
CW
515 * @return int
516 * unsigned $parentId Parent ID
0775436c 517 */
518fa0ee 518 public static function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
0775436c
TO
519 if (empty($entityId) || empty($entityTable)) {
520 return NULL;
521 }
522
523 $query = "
524 SELECT parent_id
525 FROM civicrm_recurring_entity
526 WHERE entity_id = %1 AND entity_table = %2";
527 if (!$includeParent) {
528 $query .= " AND parent_id != %1";
529 }
e7483cbe
J
530 $parentId
531 = CRM_Core_DAO::singleValueQuery($query,
be2fb01f
CW
532 [
533 1 => [$entityId, 'Integer'],
534 2 => [$entityTable, 'String'],
535 ]
0775436c
TO
536 );
537 return $parentId;
538 }
539
04374d9d
CW
540 /**
541 * Finds the position of this entity as well as total count of the repeating set
542 *
543 * @param $entityId
544 * @param $entityTable
545 * @return array|null
546 */
518fa0ee 547 public static function getPositionAndCount($entityId, $entityTable) {
04374d9d
CW
548 $position = $count = 0;
549
550 $query = "
551 SELECT entity_id
552 FROM civicrm_recurring_entity
553 WHERE parent_id = (SELECT parent_id FROM civicrm_recurring_entity WHERE entity_id = %1 AND entity_table = %2) AND entity_table = %2";
554
555 $dao = CRM_Core_DAO::executeQuery($query,
be2fb01f
CW
556 [
557 1 => [$entityId, 'Integer'],
558 2 => [$entityTable, 'String'],
559 ]
04374d9d
CW
560 );
561
562 while ($dao->fetch()) {
563 ++$count;
564 if ($dao->entity_id <= $entityId) {
565 ++$position;
566 }
567 }
568 if ($count) {
be2fb01f 569 return [$position, $count];
04374d9d
CW
570 }
571 return NULL;
572 }
573
0775436c 574 /**
fe482240 575 * This function copies the information from parent entity and creates other entities with same information.
0775436c 576 *
6a0b768e
TO
577 * @param string $entityTable
578 * Entity table name .
579 * @param array $fromCriteria
580 * Array of all the fields & values on which basis to copy .
581 * @param array $newParams
582 * Array of all the fields & values to be copied besides the other fields .
583 * @param bool $createRecurringEntity
584 * If to create a record in recurring_entity table .
0775436c 585 *
0775436c
TO
586 *
587 * @return object
588 */
518fa0ee 589 public static function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
0775436c
TO
590 $daoName = self::$_tableDAOMapper[$entityTable];
591 if (!$daoName) {
592 CRM_Core_Error::fatal("DAO Mapper missing for $entityTable.");
593 }
594 $newObject = CRM_Core_DAO::copyGeneric($daoName, $fromCriteria, $newParams);
595
596 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id && $createRecurringEntity) {
353ffa53 597 $object = new $daoName();
0775436c
TO
598 foreach ($fromCriteria as $key => $value) {
599 $object->$key = $value;
600 }
601 $object->find(TRUE);
602
603 CRM_Core_BAO_RecurringEntity::quickAdd($object->id, $newObject->id, $entityTable);
604 }
605 return $newObject;
606 }
607
608 /**
8eedd10a 609 * This function acts as a listener to dao->update whenever there is an update.
0775436c 610 *
8eedd10a 611 * It propagates any changes to all related entities present in recurring entity table
0775436c 612 *
8eedd10a 613 * @param object $event
614 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
0775436c 615 */
518fa0ee 616 public static function triggerUpdate($event) {
0775436c
TO
617 // if DB version is earlier than 4.6 skip any processing
618 static $currentVer = NULL;
619 if (!$currentVer) {
620 $currentVer = CRM_Core_BAO_Domain::version();
621 }
622 if (version_compare($currentVer, '4.6.alpha1') < 0) {
623 return;
624 }
625
be2fb01f 626 static $processedEntities = [];
0775436c
TO
627 $obj =& $event->object;
628 if (empty($obj->id) || empty($obj->__table)) {
8eedd10a 629 return;
0775436c
TO
630 }
631 $key = "{$obj->__table}_{$obj->id}";
632
633 if (array_key_exists($key, $processedEntities)) {
634 // already processed
8eedd10a 635 return;
0775436c
TO
636 }
637
638 // get related entities
639 $repeatingEntities = self::getEntitiesFor($obj->id, $obj->__table, FALSE, NULL);
640 if (empty($repeatingEntities)) {
641 // return if its not a recurring entity parent
8eedd10a 642 return;
0775436c
TO
643 }
644 // mark being processed
645 $processedEntities[$key] = 1;
646
647 // to make sure we not copying to source itself
648 unset($repeatingEntities[$key]);
649
650 foreach ($repeatingEntities as $key => $val) {
651 $entityID = $val['id'];
652 $entityTable = $val['table'];
653
654 $processedEntities[$key] = 1;
655
656 if (array_key_exists($entityTable, self::$_tableDAOMapper)) {
353ffa53 657 $daoName = self::$_tableDAOMapper[$entityTable];
0775436c 658
be2fb01f 659 $skipData = [];
0775436c
TO
660 if (array_key_exists($entityTable, self::$_updateSkipFields)) {
661 $skipFields = self::$_updateSkipFields[$entityTable];
662 foreach ($skipFields as $sfield) {
663 $skipData[$sfield] = NULL;
664 }
665 }
666
667 $updateDAO = CRM_Core_DAO::cascadeUpdate($daoName, $obj->id, $entityID, $skipData);
0775436c
TO
668 }
669 else {
670 CRM_Core_Error::fatal("DAO Mapper missing for $entityTable.");
671 }
672 }
673 // done with processing. lets unset static var.
674 unset($processedEntities);
675 }
676
677 /**
678 * This function acts as a listener to dao->save,
679 * and creates entries for linked entities in recurring entity table
680 *
6a0b768e 681 * @param object $event
8eedd10a 682 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
0775436c 683 */
518fa0ee 684 public static function triggerInsert($event) {
0775436c
TO
685 $obj =& $event->object;
686 if (!array_key_exists($obj->__table, self::$_linkedEntitiesInfo)) {
8eedd10a 687 return;
0775436c
TO
688 }
689
690 // if DB version is earlier than 4.6 skip any processing
691 static $currentVer = NULL;
692 if (!$currentVer) {
693 $currentVer = CRM_Core_BAO_Domain::version();
694 }
695 if (version_compare($currentVer, '4.6.alpha1') < 0) {
696 return;
697 }
698
be2fb01f 699 static $processedEntities = [];
0775436c 700 if (empty($obj->id) || empty($obj->__table)) {
8eedd10a 701 return;
0775436c
TO
702 }
703 $key = "{$obj->__table}_{$obj->id}";
704
705 if (array_key_exists($key, $processedEntities)) {
706 // already being processed. Exit recursive calls.
8eedd10a 707 return;
0775436c
TO
708 }
709
710 if (self::getStatus() == self::RUNNING) {
711 // if recursion->generate() is doing some work, lets not intercept
8eedd10a 712 return;
0775436c
TO
713 }
714
715 // mark being processed
716 $processedEntities[$key] = 1;
717
718 // get related entities for table being saved
719 $hasaRecurringRecord = self::getParentFor($obj->id, $obj->__table);
720
721 if (empty($hasaRecurringRecord)) {
722 // check if its a linked entity
723 if (array_key_exists($obj->__table, self::$_linkedEntitiesInfo) &&
353ffa53
TO
724 !CRM_Utils_Array::value('is_multirecord', self::$_linkedEntitiesInfo[$obj->__table])
725 ) {
0775436c
TO
726 $linkedDAO = new self::$_tableDAOMapper[$obj->__table]();
727 $linkedDAO->id = $obj->id;
728 if ($linkedDAO->find(TRUE)) {
729 $idCol = self::$_linkedEntitiesInfo[$obj->__table]['entity_id_col'];
730 $tableCol = self::$_linkedEntitiesInfo[$obj->__table]['entity_table_col'];
731
353ffa53 732 $pEntityID = $linkedDAO->$idCol;
0775436c
TO
733 $pEntityTable = $linkedDAO->$tableCol;
734
735 // find all parent recurring entity set
736 $pRepeatingEntities = self::getEntitiesFor($pEntityID, $pEntityTable);
737
738 if (!empty($pRepeatingEntities)) {
739 // for each parent entity in the set, find out a similar linked entity,
740 // if doesn't exist create one, and also create entries in recurring_entity table
741
742 foreach ($pRepeatingEntities as $key => $val) {
743 if (array_key_exists($key, $processedEntities)) {
744 // this graph is already being processed
8eedd10a 745 return;
0775436c
TO
746 }
747 $processedEntities[$key] = 1;
748 }
749
750 // start with first entry with just itself
751 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $obj->id, $obj->__table);
752
753 foreach ($pRepeatingEntities as $key => $val) {
754 $rlinkedDAO = new self::$_tableDAOMapper[$obj->__table]();
755 $rlinkedDAO->$idCol = $val['id'];
756 $rlinkedDAO->$tableCol = $val['table'];
757 if ($rlinkedDAO->find(TRUE)) {
758 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $rlinkedDAO->id, $obj->__table);
759 }
760 else {
761 // linked entity doesn't exist. lets create them
be2fb01f 762 $newCriteria = [
353ffa53 763 $idCol => $val['id'],
e7483cbe 764 $tableCol => $val['table'],
be2fb01f 765 ];
0775436c 766 $linkedObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($obj->__table,
be2fb01f 767 ['id' => $obj->id],
0775436c
TO
768 $newCriteria,
769 TRUE
770 );
771 if ($linkedObj->id) {
772 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $linkedObj->id, $obj->__table);
773 }
774 }
775 }
776 }
777 }
778 }
779 }
780
781 // done with processing. lets unset static var.
782 unset($processedEntities);
783 }
784
785 /**
786 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
787 *
6a0b768e 788 * @param object $event
8eedd10a 789 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
0775436c 790 */
518fa0ee 791 public static function triggerDelete($event) {
0775436c
TO
792 $obj =& $event->object;
793
794 // if DB version is earlier than 4.6 skip any processing
795 static $currentVer = NULL;
796 if (!$currentVer) {
797 $currentVer = CRM_Core_BAO_Domain::version();
798 }
799 if (version_compare($currentVer, '4.6.alpha1') < 0) {
800 return;
801 }
802
be2fb01f 803 static $processedEntities = [];
0775436c 804 if (empty($obj->id) || empty($obj->__table) || !$event->result) {
8eedd10a 805 return;
0775436c
TO
806 }
807 $key = "{$obj->__table}_{$obj->id}";
808
809 if (array_key_exists($key, $processedEntities)) {
810 // already processed
8eedd10a 811 return;
0775436c
TO
812 }
813
814 // mark being processed
815 $processedEntities[$key] = 1;
816
817 $parentID = self::getParentFor($obj->id, $obj->__table);
818 if ($parentID) {
819 CRM_Core_BAO_RecurringEntity::delEntity($obj->id, $obj->__table, TRUE);
820 }
821 }
822
823 /**
ad37ac8e 824 * This function deletes main entity and related linked entities from recurring-entity table.
0775436c 825 *
6a0b768e 826 * @param int $entityId
72b3a70c 827 * Entity id
6a0b768e 828 * @param string $entityTable
72b3a70c 829 * Name of the entity table
0775436c 830 *
ad37ac8e 831 * @param bool $isDelLinkedEntities
0775436c 832 *
ad37ac8e 833 * @return bool|\CRM_Core_DAO_RecurringEntity
834 * @throws \Exception
0775436c 835 */
518fa0ee 836 public static function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
0775436c
TO
837 if (empty($entityId) || empty($entityTable)) {
838 return FALSE;
839 }
840 $dao = new CRM_Core_DAO_RecurringEntity();
841 $dao->entity_id = $entityId;
842 $dao->entity_table = $entityTable;
843 if ($dao->find(TRUE)) {
844 // make sure its not a linked entity thats being deleted
845 if ($isDelLinkedEntities && !array_key_exists($entityTable, self::$_linkedEntitiesInfo)) {
846 // delete all linked entities from recurring entity table
847 foreach (self::$_linkedEntitiesInfo as $linkedTable => $linfo) {
848 $daoName = self::$_tableDAOMapper[$linkedTable];
849 if (!$daoName) {
850 CRM_Core_Error::fatal("DAO Mapper missing for $linkedTable.");
851 }
852
853 $linkedDao = new $daoName();
6ef04c72
MM
854 $linkedDao->{$linfo['entity_id_col']} = $entityId;
855 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
0775436c
TO
856 $linkedDao->find();
857 while ($linkedDao->fetch()) {
858 CRM_Core_BAO_RecurringEntity::delEntity($linkedDao->id, $linkedTable, FALSE);
859 }
860 }
861 }
862 // delete main entity
863 return $dao->delete();
864 }
865 return FALSE;
866 }
867
868 /**
fe482240 869 * This function maps values posted from form to civicrm_action_schedule columns.
0775436c 870 *
6a0b768e
TO
871 * @param array $formParams
872 * And array of form values posted .
0775436c
TO
873 *
874 * @return array
875 */
be2fb01f
CW
876 public function mapFormValuesToDB($formParams = []) {
877 $dbParams = [];
b53cbfbc 878 if (!empty($formParams['used_for'])) {
0775436c
TO
879 $dbParams['used_for'] = $formParams['used_for'];
880 }
881
b53cbfbc 882 if (!empty($formParams['entity_id'])) {
0775436c
TO
883 $dbParams['entity_value'] = $formParams['entity_id'];
884 }
885
b53cbfbc
CW
886 if (!empty($formParams['repetition_start_date'])) {
887 if (!empty($formParams['repetition_start_date_display'])) {
0775436c
TO
888 $repetitionStartDate = $formParams['repetition_start_date_display'];
889 }
890 else {
891 $repetitionStartDate = $formParams['repetition_start_date'];
892 }
b53cbfbc 893 if (!empty($formParams['repetition_start_date_time'])) {
0775436c
TO
894 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
895 }
896 $repetition_start_date = new DateTime($repetitionStartDate);
1043bac2 897 $dbParams['start_action_date'] = $repetition_start_date->format('YmdHis');
0775436c
TO
898 }
899
b53cbfbc 900 if (!empty($formParams['repetition_frequency_unit'])) {
0775436c
TO
901 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
902 }
903
b53cbfbc 904 if (!empty($formParams['repetition_frequency_interval'])) {
0775436c
TO
905 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
906 }
907
908 //For Repeats on:(weekly case)
909 if ($formParams['repetition_frequency_unit'] == 'week') {
b53cbfbc 910 if (!empty($formParams['start_action_condition'])) {
0775436c
TO
911 $repeats_on = CRM_Utils_Array::value('start_action_condition', $formParams);
912 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
913 }
914 }
915
916 //For Repeats By:(monthly case)
917 if ($formParams['repetition_frequency_unit'] == 'month') {
918 if ($formParams['repeats_by'] == 1) {
b53cbfbc 919 if (!empty($formParams['limit_to'])) {
0775436c
TO
920 $dbParams['limit_to'] = $formParams['limit_to'];
921 }
922 }
923 if ($formParams['repeats_by'] == 2) {
de6c59ca 924 if (!empty($formParams['entity_status_1']) && !empty($formParams['entity_status_2'])) {
353ffa53 925 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
0775436c
TO
926 }
927 }
928 }
929
930 //For "Ends" - After:
931 if ($formParams['ends'] == 1) {
b53cbfbc 932 if (!empty($formParams['start_action_offset'])) {
0775436c
TO
933 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
934 }
935 }
936
937 //For "Ends" - On:
938 if ($formParams['ends'] == 2) {
b53cbfbc 939 if (!empty($formParams['repeat_absolute_date'])) {
0775436c
TO
940 $dbParams['absolute_date'] = CRM_Utils_Date::processDate($formParams['repeat_absolute_date']);
941 }
942 }
943 return $dbParams;
944 }
945
946 /**
947 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
948 *
6a0b768e
TO
949 * @param int $scheduleReminderId
950 * Primary key of civicrm_action_schedule table .
0775436c 951 *
0775436c
TO
952 *
953 * @return object
954 */
518fa0ee 955 public static function getScheduleReminderDetailsById($scheduleReminderId) {
0775436c
TO
956 $query = "SELECT *
957 FROM civicrm_action_schedule WHERE 1";
958 if ($scheduleReminderId) {
959 $query .= "
960 AND id = %1";
961 }
962 $dao = CRM_Core_DAO::executeQuery($query,
be2fb01f
CW
963 [
964 1 => [$scheduleReminderId, 'Integer'],
965 ]
0775436c
TO
966 );
967 $dao->fetch();
968 return $dao;
969 }
970
971 /**
fe482240 972 * wrapper of getScheduleReminderDetailsById function.
0775436c 973 *
6a0b768e
TO
974 * @param int $scheduleReminderId
975 * Primary key of civicrm_action_schedule table .
0775436c
TO
976 *
977 * @return array
978 */
979 public function getScheduleParams($scheduleReminderId) {
be2fb01f 980 $scheduleReminderDetails = [];
0775436c
TO
981 if ($scheduleReminderId) {
982 //Get all the details from schedule reminder table
983 $scheduleReminderDetails = self::getScheduleReminderDetailsById($scheduleReminderId);
984 $scheduleReminderDetails = (array) $scheduleReminderDetails;
985 }
986 return $scheduleReminderDetails;
987 }
988
989 /**
b44e3f84 990 * This function takes criteria saved in civicrm_action_schedule table
0775436c
TO
991 * and creates recursion rule
992 *
6a0b768e 993 * @param array $scheduleReminderDetails
b44e3f84 994 * Array of repeat criteria saved in civicrm_action_schedule table .
0775436c 995 *
a6c01b45
CW
996 * @return object
997 * When object
0775436c 998 */
be2fb01f 999 public function getRecursionFromSchedule($scheduleReminderDetails = []) {
0775436c
TO
1000 $r = new When();
1001 //If there is some data for this id
1002 if ($scheduleReminderDetails['repetition_frequency_unit']) {
1003 if ($scheduleReminderDetails['start_action_date']) {
1004 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
1005 }
1006 else {
1007 $currDate = date("Y-m-d H:i:s");
1008 }
1009 $start = new DateTime($currDate);
1010 $this->recursion_start_date = $start;
30aa3e54
PZ
1011 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
1012 if ($repetition_frequency_unit == "day") {
1013 $repetition_frequency_unit = "dai";
0775436c 1014 }
30aa3e54
PZ
1015 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
1016 $r->startDate($start)
1017 ->exclusions([$start])
1018 ->freq($repetition_frequency_unit);
0775436c
TO
1019
1020 if ($scheduleReminderDetails['repetition_frequency_interval']) {
1021 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
1022 }
1023 else {
1024 $r->errors[] = 'Repeats every: is a required field';
1025 }
1026
1027 //week
1028 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
1029 if ($scheduleReminderDetails['start_action_condition']) {
1030 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
1031 $explodeStartActionCondition = explode(',', $startActionCondition);
be2fb01f 1032 $buildRuleArray = [];
0775436c
TO
1033 foreach ($explodeStartActionCondition as $key => $val) {
1034 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
1035 }
1036 $r->wkst('MO')->byday($buildRuleArray);
1037 }
1038 }
1039
1040 //month
1041 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1042 if ($scheduleReminderDetails['entity_status']) {
1043 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1044 switch ($startActionDate[0]) {
353ffa53
TO
1045 case 'first':
1046 $startActionDate1 = 1;
1047 break;
ea100cb5 1048
353ffa53
TO
1049 case 'second':
1050 $startActionDate1 = 2;
1051 break;
ea100cb5 1052
353ffa53
TO
1053 case 'third':
1054 $startActionDate1 = 3;
1055 break;
ea100cb5 1056
353ffa53
TO
1057 case 'fourth':
1058 $startActionDate1 = 4;
1059 break;
ea100cb5 1060
353ffa53
TO
1061 case 'last':
1062 $startActionDate1 = -1;
1063 break;
0775436c 1064 }
353ffa53 1065 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
be2fb01f 1066 $r->byday([$concatStartActionDateBits]);
0775436c
TO
1067 }
1068 elseif ($scheduleReminderDetails['limit_to']) {
be2fb01f 1069 $r->bymonthday([$scheduleReminderDetails['limit_to']]);
0775436c
TO
1070 }
1071 }
1072
1073 //Ends
1074 if ($scheduleReminderDetails['start_action_offset']) {
1075 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1076 $r->errors[] = 'Occurrences should be less than or equal to 30';
1077 }
1078 $r->count($scheduleReminderDetails['start_action_offset']);
1079 }
1080
b53cbfbc 1081 if (!empty($scheduleReminderDetails['absolute_date'])) {
0775436c 1082 $absoluteDate = CRM_Utils_Date::setDateDefaults($scheduleReminderDetails['absolute_date']);
2069e839 1083 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1084 // and we always want the date to be included, and therefore appending 23:59
1085 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
0775436c
TO
1086 $r->until($endDate);
1087 }
1088
1089 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1090 $r->errors[] = 'Ends: is a required field';
1091 }
1092 }
1093 else {
1094 $r->errors[] = 'Repeats: is a required field';
1095 }
1096 return $r;
1097 }
1098
0775436c 1099 /**
fe482240 1100 * This function gets time difference between the two datetime object.
0775436c 1101 *
6a0b768e
TO
1102 * @param DateTime $startDate
1103 * Start Date .
1104 * @param DateTime $endDate
1105 * End Date .
0775436c 1106 *
0775436c 1107 *
a6c01b45
CW
1108 * @return object
1109 * DateTime object which contain time difference
0775436c 1110 */
518fa0ee 1111 public static function getInterval($startDate, $endDate) {
0775436c
TO
1112 if ($startDate && $endDate) {
1113 $startDate = new DateTime($startDate);
353ffa53 1114 $endDate = new DateTime($endDate);
0775436c
TO
1115 return $startDate->diff($endDate);
1116 }
1117 }
1118
1119 /**
fe482240 1120 * This function gets all columns from civicrm_action_schedule on the basis of event id.
0775436c 1121 *
6a0b768e
TO
1122 * @param int $entityId
1123 * Entity ID .
1124 * @param string $used_for
1125 * Specifies for which entity type it's used for .
0775436c 1126 *
0775436c
TO
1127 *
1128 * @return object
1129 */
1130 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1131 if ($entityId) {
1132 $query = "
1133 SELECT *
1134 FROM civicrm_action_schedule
1135 WHERE entity_value = %1";
1136 if ($used_for) {
1137 $query .= " AND used_for = %2";
1138 }
be2fb01f
CW
1139 $params = [
1140 1 => [$entityId, 'Integer'],
1141 2 => [$used_for, 'String'],
1142 ];
0775436c
TO
1143 $dao = CRM_Core_DAO::executeQuery($query, $params);
1144 $dao->fetch();
1145 }
1146 return $dao;
1147 }
1148
1149 /**
fe482240 1150 * Update mode column in civicrm_recurring_entity table for event related tabs.
0775436c 1151 *
6a0b768e
TO
1152 * @param int $entityId
1153 * Event id .
1154 * @param string $linkedEntityTable
1155 * Linked entity table name for this event .
ad37ac8e 1156 * @param string $mainEntityTable
1157 *
0775436c
TO
1158 * @return array
1159 */
1160 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
be2fb01f 1161 $result = [];
353ffa53 1162 if ($entityId && $linkedEntityTable && $mainEntityTable) {
0775436c
TO
1163 if (CRM_Utils_Array::value($linkedEntityTable, self::$_tableDAOMapper)) {
1164 $dao = self::$_tableDAOMapper[$linkedEntityTable];
1165 }
1166 else {
1167 CRM_Core_Session::setStatus('Could not update mode for linked entities');
e7483cbe 1168 return NULL;
0775436c
TO
1169 }
1170 $entityTable = $linkedEntityTable;
be2fb01f 1171 $params = [
353ffa53 1172 'entity_id' => $entityId,
e7483cbe 1173 'entity_table' => $mainEntityTable,
be2fb01f
CW
1174 ];
1175 $defaults = [];
0775436c 1176 CRM_Core_DAO::commonRetrieve($dao, $params, $defaults);
b53cbfbc 1177 if (!empty($defaults['id'])) {
0775436c
TO
1178 $result['entityId'] = $defaults['id'];
1179 $result['entityTable'] = $entityTable;
1180 }
1181 }
1182 return $result;
1183 }
96025800 1184
543aa76e
AP
1185 /**
1186 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1187 *
1188 * @param int $entityId
1189 * Event id .
1190 * @param string $entityTable
1191 * @param string $mode
1192 * @param string $linkedEntityTable
1193 * Linked entity table name for this event .
1194 * @param string $priceSet
1195 * Price set of the event .
1196 *
1197 * @return array
1198 */
1199 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
be2fb01f 1200 $finalResult = [];
543aa76e
AP
1201
1202 if (!empty($linkedEntityTable)) {
1203 $result = CRM_Core_BAO_RecurringEntity::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1204 }
1205
1206 $dao = new CRM_Core_DAO_RecurringEntity();
1207 if (!empty($result)) {
1208 $dao->entity_id = $result['entityId'];
1209 $dao->entity_table = $result['entityTable'];
1210 }
1211 else {
1212 $dao->entity_id = $entityId;
1213 $dao->entity_table = $entityTable;
1214 }
1215
1216 if ($dao->find(TRUE)) {
1217 $dao->mode = $mode;
1218 $dao->save();
1219
55d676f2
AP
1220 if ($priceSet) {
1221 //CRM-20787 Fix
1222 //I am not sure about other fields, if mode = 3 apply for an event then other fields
1223 //should be save for all other series events or not so applying for price set only for now here.
1224 if (CRM_Core_BAO_RecurringEntity::MODE_ALL_ENTITY_IN_SERIES === $mode) {
1225 //Step-1: Get all events of series
1226 $seriesEventRecords = CRM_Core_BAO_RecurringEntity::getEntitiesFor($entityId, $entityTable);
1227 foreach ($seriesEventRecords as $event) {
1228 //Step-2: Save price set in other series events
518fa0ee
SL
1229 //Remove existing priceset
1230 if (CRM_Price_BAO_PriceSet::removeFrom($event['table'], $event['id'])) {
55d676f2
AP
1231 CRM_Core_BAO_Discount::del($event['id'], $event['table']);
1232 }
518fa0ee
SL
1233 //Add new price set
1234 CRM_Price_BAO_PriceSet::addTo($event['table'], $event['id'], $priceSet);
543aa76e
AP
1235 }
1236 }
55d676f2
AP
1237
1238 if (CRM_Core_BAO_RecurringEntity::MODE_NEXT_ALL_ENTITY === $mode) {
1239 //Step-1: Get all events of series
1240 $seriesEventRecords = CRM_Core_BAO_RecurringEntity::getEntitiesFor($entityId, $entityTable);
1241 foreach ($seriesEventRecords as $event) {
1242 //Step-2: Save price set in other series events
1243 if ($entityId < $event["id"]) {
518fa0ee
SL
1244 //Remove existing priceset
1245 if (CRM_Price_BAO_PriceSet::removeFrom($event['table'], $event['id'])) {
55d676f2
AP
1246 CRM_Core_BAO_Discount::del($event['id'], $event['table']);
1247 }
518fa0ee
SL
1248 //Add new price set
1249 CRM_Price_BAO_PriceSet::addTo($event['table'], $event['id'], $priceSet);
55d676f2
AP
1250 }
1251 }
1252 }
543aa76e 1253 }
55d676f2 1254
543aa76e
AP
1255 //CRM-20787 - Fix end
1256 $finalResult['status'] = 'Done';
1257 }
1258 else {
1259 $finalResult['status'] = 'Error';
1260 }
1261
1262 return $finalResult;
1263 }
1264
30aa3e54
PZ
1265 /**
1266 * Get next occurrence for the given date
1267 *
1268 * @param \DateTime $occurDate
1269 * @param bool $strictly_after
1270 *
1271 * @return bool
1272 */
1273 private function getNextOccurrence($occurDate, $strictly_after = TRUE) {
1274 try {
1275 return $this->recursion->getNextOccurrence($occurDate, $strictly_after);
1276 }
1277 catch (Exception $exception) {
1278 CRM_Core_Session::setStatus(ts($exception->getMessage()));
1279 }
1280 return FALSE;
1281 }
1282
0775436c 1283}