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