3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * Class CRM_Core_BAO_RecurringEntity.
23 class CRM_Core_BAO_RecurringEntity
extends CRM_Core_DAO_RecurringEntity
implements \Symfony\Component\EventDispatcher\EventSubscriberInterface
{
26 public $schedule = [];
27 public $scheduleId = NULL;
28 public $scheduleFormValues = [];
30 public $dateColumns = [];
31 public $overwriteColumns = [];
32 public $intervalDateColumns = [];
33 public $excludeDates = [];
35 public $linkedEntities = [];
37 public $isRecurringEntityRecord = TRUE;
39 protected $recursion = NULL;
40 protected $recursion_start_date = NULL;
42 public static $_entitiesToBeDeleted = [];
44 public static $status = NULL;
46 public static $_recurringEntityHelper
49 'helper_class' => 'CRM_Event_DAO_Event',
50 'delete_func' => 'delete',
51 'pre_delete_func' => 'CRM_Event_Form_ManageEvent_Repeat::checkRegistrationForEvents',
53 'civicrm_activity' => [
54 'helper_class' => 'CRM_Activity_DAO_Activity',
55 'delete_func' => 'delete',
56 'pre_delete_func' => '',
60 public static $_dateColumns
63 'dateColumns' => ['start_date'],
64 'excludeDateRangeColumns' => ['start_date', 'end_date'],
65 'intervalDateColumns' => ['end_date'],
67 'civicrm_activity' => [
68 'dateColumns' => ['activity_date_time'],
72 public static $_tableDAOMapper
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',
83 public static $_updateSkipFields
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'],
91 public static $_linkedEntitiesInfo
93 'civicrm_tell_friend' => [
94 'entity_id_col' => 'entity_id',
95 'entity_table_col' => 'entity_table',
97 'civicrm_price_set_entity' => [
98 'entity_id_col' => 'entity_id',
99 'entity_table_col' => 'entity_table',
100 'is_multirecord' => TRUE,
102 'civicrm_uf_join' => [
103 'entity_id_col' => 'entity_id',
104 'entity_table_col' => 'entity_table',
105 'is_multirecord' => TRUE,
107 'civicrm_pcp_block' => [
108 'entity_id_col' => 'entity_id',
109 'entity_table_col' => 'entity_table',
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;
118 public static function getSubscribedEvents() {
120 'civi.dao.postInsert' => 'triggerInsert',
121 'civi.dao.postUpdate' => 'triggerUpdate',
122 'civi.dao.postDelete' => 'triggerDelete',
131 public static function getStatus() {
132 return self
::$status;
138 * @param string $status
140 public static function setStatus($status) {
141 self
::$status = $status;
145 * Create or update a RecurringEntity.
147 * @param array $params
148 * @return CRM_Core_DAO_RecurringEntity
150 public static function add($params) {
151 return self
::writeRecord($params);
155 * Convenience wrapper for self::writeRecord
157 * @param int $parentId
159 * @param int $entityId
161 * @param string $entityTable
162 * Name of the entity table .
164 * @return CRM_Core_DAO_RecurringEntity
166 public static function quickAdd($parentId, $entityId, $entityTable) {
168 'parent_id' => $parentId,
169 'entity_id' => $entityId,
170 'entity_table' => $entityTable,
172 return self
::writeRecord($params);
176 * This function updates the mode column in the civicrm_recurring_entity table.
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.
181 public function mode($mode) {
182 if ($this->entity_id
&& $this->entity_table
) {
183 if ($this->find(TRUE)) {
187 $this->parent_id
= $this->entity_id
;
195 * This function generates all new entities based on object vars.
199 public function generate() {
200 $this->generateRecursiveDates();
202 return $this->generateEntities();
206 * This function builds a "When" object based on schedule/reminder params
211 public function generateRecursion() {
212 // return if already generated
213 if (is_a($this->recursion
, 'When\When')) {
214 return $this->recursion
;
217 if ($this->scheduleId
) {
219 $this->schedule
= $this->getScheduleParams($this->scheduleId
);
221 elseif (!empty($this->scheduleFormValues
)) {
222 $this->schedule
= $this->mapFormValuesToDB($this->scheduleFormValues
);
225 if (!empty($this->schedule
)) {
226 $this->recursion
= $this->getRecursionFromSchedule($this->schedule
);
228 return $this->recursion
;
232 * Generate new DAOs and along with entries in civicrm_recurring_entity table.
235 * @throws CRM_Core_Exception
237 public function generateEntities() {
238 self
::setStatus(self
::RUNNING
);
242 if (!empty($this->recursionDates
)) {
243 if ($this->entity_id
) {
244 $findCriteria = ['id' => $this->entity_id
];
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
;
252 if (empty($findCriteria)) {
253 throw new CRM_Core_Exception("Find criteria missing to generate form. Make sure entity_id and table is set.");
257 foreach ($this->recursionDates
as $key => $dateCols) {
258 $newCriteria = $dateCols;
259 foreach ($this->overwriteColumns
as $col => $val) {
260 $newCriteria[$col] = $val;
262 // create main entities
263 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
266 $this->isRecurringEntityRecord
269 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
271 $newEntities[$this->entity_table
][$count] = $obj->id
;
273 foreach ($this->linkedEntities
as $linkedInfo) {
274 foreach ($linkedInfo['linkedColumns'] as $col) {
275 $newCriteria[$col] = $obj->id
;
277 // create linked entities
278 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
279 $linkedInfo['findCriteria'],
281 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
284 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
285 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
293 self
::$status = NULL;
298 * This function iterates through when object criteria and
299 * generates recursive dates based on that
304 public function generateRecursiveDates() {
305 $this->generateRecursion();
307 $recursionDates = [];
308 if (is_a($this->recursion
, 'When\When')) {
309 $initialCount = $this->schedule
['start_action_offset'] ??
NULL;
311 $exRangeStart = $exRangeEnd = NULL;
312 if (!empty($this->excludeDateRangeColumns
)) {
313 $exRangeStart = $this->excludeDateRangeColumns
[0];
314 $exRangeEnd = $this->excludeDateRangeColumns
[1];
317 if (CRM_Core_Config
::singleton()->userFramework
== 'UnitTests') {
318 $this->recursion
->RFC5545_COMPLIANT
= When
::IGNORE
;
321 $result = $this->recursion_start_date
;
322 while ($result = $this->getNextOccurrence($result)) {
324 if ($result == $this->recursion_start_date
) {
325 // skip the recursion-start-date from the list we going to generate
328 $baseDate = $result->format('YmdHis');
330 foreach ($this->dateColumns
as $col) {
331 $recursionDates[$count][$col] = $baseDate;
333 foreach ($this->intervalDateColumns
as $col => $interval) {
334 $newDate = new DateTime($baseDate);
335 $newDate->add($interval);
336 $recursionDates[$count][$col] = $newDate->format('YmdHis');
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');
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')) {
352 if (($exDate == $exRangeStartDate) ||
353 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
362 unset($recursionDates[$count]);
363 if ($initialCount && ($initialCount > 0)) {
364 // lets increase the counter, so we get correct number of occurrences
366 $this->recursion
->count($initialCount);
373 $this->recursionDates
= $recursionDates;
375 return $recursionDates;
379 * This function gets all the children for a particular parent entity.
381 * @param int $parentId
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 .
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 .
394 * an array of child ids
396 public static function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
398 if (empty($parentId) ||
empty($entityTable)) {
403 $initiatorId = $parentId;
407 1 => [$parentId, 'Integer'],
408 2 => [$entityTable, 'String'],
409 3 => [$initiatorId, 'Integer'],
413 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
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");
425 $query .= " AND entity_id = %3";
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'];
437 // something wrong, return empty
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
;
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.
454 * @param int $entityId
456 * @param string $entityTable
457 * Entity table name .
458 * @param bool $includeParent
459 * Include parent in result set .
461 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
465 * array of connected ids
467 public static function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
468 $parentId = self
::getParentFor($entityId, $entityTable);
470 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
476 * This function gets the parent for the entity id passed to it.
478 * @param int $entityId
480 * @param string $entityTable
481 * Entity table name .
482 * @param bool $includeParent
483 * Include parent in result set .
487 * unsigned $parentId Parent ID
489 public static function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
490 if (empty($entityId) ||
empty($entityTable)) {
496 FROM civicrm_recurring_entity
497 WHERE entity_id = %1 AND entity_table = %2";
498 if (!$includeParent) {
499 $query .= " AND parent_id != %1";
502 = CRM_Core_DAO
::singleValueQuery($query,
504 1 => [$entityId, 'Integer'],
505 2 => [$entityTable, 'String'],
512 * Finds the position of this entity as well as total count of the repeating set
515 * @param $entityTable
518 public static function getPositionAndCount($entityId, $entityTable) {
519 $position = $count = 0;
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";
526 $dao = CRM_Core_DAO
::executeQuery($query,
528 1 => [$entityId, 'Integer'],
529 2 => [$entityTable, 'String'],
533 while ($dao->fetch()) {
535 if ($dao->entity_id
<= $entityId) {
540 return [$position, $count];
546 * This function copies the information from parent entity and creates other entities with same information.
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 .
559 * @throws new CRM_Core_Exception
561 public static function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
562 $daoName = self
::$_tableDAOMapper[$entityTable];
564 throw new CRM_Core_Exception("DAO Mapper missing for $entityTable.");
566 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
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;
575 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
578 CRM_Utils_Hook
::copy(CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject);
583 * This function acts as a listener to dao->update whenever there is an update.
585 * It propagates any changes to all related entities present in recurring entity table
587 * @param object $event
588 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
590 public static function triggerUpdate($event) {
591 static $processedEntities = [];
592 $obj =& $event->object;
593 if (empty($obj->id
) ||
empty($obj->__table
)) {
596 $key = "{$obj->__table}_{$obj->id}";
598 if (array_key_exists($key, $processedEntities)) {
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
609 // mark being processed
610 $processedEntities[$key] = 1;
612 // to make sure we not copying to source itself
613 unset($repeatingEntities[$key]);
615 foreach ($repeatingEntities as $key => $val) {
616 $entityID = $val['id'];
617 $entityTable = $val['table'];
619 $processedEntities[$key] = 1;
621 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
622 $daoName = self
::$_tableDAOMapper[$entityTable];
625 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
626 $skipFields = self
::$_updateSkipFields[$entityTable];
627 foreach ($skipFields as $sfield) {
628 $skipData[$sfield] = NULL;
632 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
635 throw new CRM_Core_Exception("DAO Mapper missing for $entityTable.");
638 // done with processing. lets unset static var.
639 unset($processedEntities);
643 * This function acts as a listener to dao->save,
644 * and creates entries for linked entities in recurring entity table
646 * @param object $event
647 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
649 public static function triggerInsert($event) {
650 $obj =& $event->object;
651 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
655 static $processedEntities = [];
656 if (empty($obj->id
) ||
empty($obj->__table
)) {
659 $key = "{$obj->__table}_{$obj->id}";
661 if (array_key_exists($key, $processedEntities)) {
662 // already being processed. Exit recursive calls.
666 if (self
::getStatus() == self
::RUNNING
) {
667 // if recursion->generate() is doing some work, lets not intercept
671 // mark being processed
672 $processedEntities[$key] = 1;
674 // get related entities for table being saved
675 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
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'])
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'];
688 $pEntityID = $linkedDAO->$idCol;
689 $pEntityTable = $linkedDAO->$tableCol;
691 // find all parent recurring entity set
692 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
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
698 foreach ($pRepeatingEntities as $key => $val) {
699 if (array_key_exists($key, $processedEntities)) {
700 // this graph is already being processed
703 $processedEntities[$key] = 1;
706 // start with first entry with just itself
707 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
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
);
717 // linked entity doesn't exist. lets create them
719 $idCol => $val['id'],
720 $tableCol => $val['table'],
722 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
727 if ($linkedObj->id
) {
728 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
737 // done with processing. lets unset static var.
738 unset($processedEntities);
742 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
744 * @param object $event
745 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
747 public static function triggerDelete($event) {
748 $obj =& $event->object;
750 static $processedEntities = [];
751 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
754 $key = "{$obj->__table}_{$obj->id}";
756 if (array_key_exists($key, $processedEntities)) {
761 // mark being processed
762 $processedEntities[$key] = 1;
764 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
766 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
771 * This function deletes main entity and related linked entities from recurring-entity table.
773 * @param int $entityId
775 * @param string $entityTable
776 * Name of the entity table
778 * @param bool $isDelLinkedEntities
780 * @return bool|\CRM_Core_DAO_RecurringEntity
783 public static function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
784 if (empty($entityId) ||
empty($entityTable)) {
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];
797 throw new CRM_Core_Exception("DAO Mapper missing for $linkedTable.");
800 $linkedDao = new $daoName();
801 $linkedDao->{$linfo['entity_id_col']} = $entityId;
802 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
804 while ($linkedDao->fetch()) {
805 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
809 // delete main entity
810 return $dao->delete();
816 * This function maps values posted from form to civicrm_action_schedule columns.
818 * @param array $formParams
819 * And array of form values posted .
823 public function mapFormValuesToDB($formParams = []) {
825 if (!empty($formParams['used_for'])) {
826 $dbParams['used_for'] = $formParams['used_for'];
829 if (!empty($formParams['entity_id'])) {
830 $dbParams['entity_value'] = $formParams['entity_id'];
833 if (!empty($formParams['repetition_start_date'])) {
834 if (!empty($formParams['repetition_start_date_display'])) {
835 $repetitionStartDate = $formParams['repetition_start_date_display'];
838 $repetitionStartDate = $formParams['repetition_start_date'];
840 if (!empty($formParams['repetition_start_date_time'])) {
841 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
843 $repetition_start_date = new DateTime($repetitionStartDate);
844 $dbParams['start_action_date'] = $repetition_start_date->format('YmdHis');
847 if (!empty($formParams['repetition_frequency_unit'])) {
848 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
851 if (!empty($formParams['repetition_frequency_interval'])) {
852 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
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));
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'];
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'];
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'];
885 if ($formParams['ends'] == 2) {
886 if (!empty($formParams['repeat_absolute_date'])) {
887 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
894 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
896 * @param int $scheduleReminderId
897 * Primary key of civicrm_action_schedule table .
902 public static function getScheduleReminderDetailsById($scheduleReminderId) {
904 FROM civicrm_action_schedule WHERE 1";
905 if ($scheduleReminderId) {
909 $dao = CRM_Core_DAO
::executeQuery($query,
911 1 => [$scheduleReminderId, 'Integer'],
919 * wrapper of getScheduleReminderDetailsById function.
921 * @param int $scheduleReminderId
922 * Primary key of civicrm_action_schedule table .
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;
933 return $scheduleReminderDetails;
937 * This function takes criteria saved in civicrm_action_schedule table
938 * and creates recursion rule
940 * @param array $scheduleReminderDetails
941 * Array of repeat criteria saved in civicrm_action_schedule table .
946 public function getRecursionFromSchedule($scheduleReminderDetails = []) {
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']));
954 $currDate = date("Y-m-d H:i:s");
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";
962 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
963 $r->startDate($start)
964 ->exclusions([$start])
965 ->freq($repetition_frequency_unit);
967 if ($scheduleReminderDetails['repetition_frequency_interval']) {
968 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
971 $r->errors
[] = 'Repeats every: is a required field';
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));
983 $r->wkst('MO')->byday($buildRuleArray);
988 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
989 if ($scheduleReminderDetails['entity_status']) {
990 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
991 switch ($startActionDate[0]) {
993 $startActionDate1 = 1;
997 $startActionDate1 = 2;
1001 $startActionDate1 = 3;
1005 $startActionDate1 = 4;
1009 $startActionDate1 = -1;
1012 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1013 $r->byday([$concatStartActionDateBits]);
1015 elseif ($scheduleReminderDetails['limit_to']) {
1016 $r->bymonthday([$scheduleReminderDetails['limit_to']]);
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';
1025 $r->count($scheduleReminderDetails['start_action_offset']);
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);
1036 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1037 $r->errors
[] = 'Ends: is a required field';
1041 $r->errors
[] = 'Repeats: is a required field';
1047 * This function gets time difference between the two datetime object.
1049 * @param DateTime $startDate
1051 * @param DateTime $endDate
1056 * DateTime object which contain time difference
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);
1067 * This function gets all columns from civicrm_action_schedule on the basis of event id.
1069 * @param int $entityId
1071 * @param string $used_for
1072 * Specifies for which entity type it's used for .
1077 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1081 FROM civicrm_action_schedule
1082 WHERE entity_value = %1";
1084 $query .= " AND used_for = %2";
1087 1 => [$entityId, 'Integer'],
1088 2 => [$used_for, 'String'],
1090 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1097 * Update mode column in civicrm_recurring_entity table for event related tabs.
1099 * @param int $entityId
1101 * @param string $linkedEntityTable
1102 * Linked entity table name for this event .
1103 * @param string $mainEntityTable
1107 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1109 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1110 if (!empty(self
::$_tableDAOMapper[$linkedEntityTable])) {
1111 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1114 CRM_Core_Session
::setStatus(ts('Could not update mode for linked entities'));
1117 $entityTable = $linkedEntityTable;
1119 'entity_id' => $entityId,
1120 'entity_table' => $mainEntityTable,
1123 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1124 if (!empty($defaults['id'])) {
1125 $result['entityId'] = $defaults['id'];
1126 $result['entityTable'] = $entityTable;
1133 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1135 * @param int $entityId
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 .
1146 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
1149 if (!empty($linkedEntityTable)) {
1150 $result = CRM_Core_BAO_RecurringEntity
::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1153 $dao = new CRM_Core_DAO_RecurringEntity();
1154 if (!empty($result)) {
1155 $dao->entity_id
= $result['entityId'];
1156 $dao->entity_table
= $result['entityTable'];
1159 $dao->entity_id
= $entityId;
1160 $dao->entity_table
= $entityTable;
1163 if ($dao->find(TRUE)) {
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']);
1181 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
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']);
1196 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1202 //CRM-20787 - Fix end
1203 $finalResult['status'] = 'Done';
1206 $finalResult['status'] = 'Error';
1209 return $finalResult;
1213 * Get next occurrence for the given date
1215 * @param \DateTime $occurDate
1216 * @param bool $strictly_after
1220 private function getNextOccurrence($occurDate, $strictly_after = TRUE) {
1222 return $this->recursion
->getNextOccurrence($occurDate, $strictly_after);
1224 catch (Exception
$exception) {
1225 CRM_Core_Session
::setStatus(ts($exception->getMessage()));