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
{
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;
123 public static function getStatus() {
124 return self
::$status;
130 * @param string $status
132 public static function setStatus($status) {
133 self
::$status = $status;
137 * Create or update a RecurringEntity.
139 * @param array $params
140 * @return CRM_Core_DAO_RecurringEntity
142 public static function add($params) {
143 return self
::writeRecord($params);
147 * Convenience wrapper for self::writeRecord
149 * @param int $parentId
151 * @param int $entityId
153 * @param string $entityTable
154 * Name of the entity table .
156 * @return CRM_Core_DAO_RecurringEntity
158 public static function quickAdd($parentId, $entityId, $entityTable) {
160 'parent_id' => $parentId,
161 'entity_id' => $entityId,
162 'entity_table' => $entityTable,
164 return self
::writeRecord($params);
168 * This function updates the mode column in the civicrm_recurring_entity table.
171 * 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.
173 public function mode($mode) {
174 if ($this->entity_id
&& $this->entity_table
) {
175 if ($this->find(TRUE)) {
179 $this->parent_id
= $this->entity_id
;
187 * This function generates all new entities based on object vars.
191 public function generate() {
192 $this->generateRecursiveDates();
194 return $this->generateEntities();
198 * This function builds a "When" object based on schedule/reminder params
203 public function generateRecursion() {
204 // return if already generated
205 if (is_a($this->recursion
, 'When\When')) {
206 return $this->recursion
;
209 if ($this->scheduleId
) {
211 $this->schedule
= $this->getScheduleParams($this->scheduleId
);
213 elseif (!empty($this->scheduleFormValues
)) {
214 $this->schedule
= $this->mapFormValuesToDB($this->scheduleFormValues
);
217 if (!empty($this->schedule
)) {
218 $this->recursion
= $this->getRecursionFromSchedule($this->schedule
);
220 return $this->recursion
;
224 * Generate new DAOs and along with entries in civicrm_recurring_entity table.
227 * @throws CRM_Core_Exception
229 public function generateEntities() {
230 self
::setStatus(self
::RUNNING
);
234 if (!empty($this->recursionDates
)) {
235 if ($this->entity_id
) {
236 $findCriteria = ['id' => $this->entity_id
];
238 // save an entry with initiating entity-id & entity-table
239 if ($this->entity_table
&& !$this->find(TRUE)) {
240 $this->parent_id
= $this->entity_id
;
244 if (empty($findCriteria)) {
245 throw new CRM_Core_Exception("Find criteria missing to generate form. Make sure entity_id and table is set.");
249 foreach ($this->recursionDates
as $key => $dateCols) {
250 $newCriteria = $dateCols;
251 foreach ($this->overwriteColumns
as $col => $val) {
252 $newCriteria[$col] = $val;
254 // create main entities
255 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
258 $this->isRecurringEntityRecord
261 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
263 $newEntities[$this->entity_table
][$count] = $obj->id
;
265 foreach ($this->linkedEntities
as $linkedInfo) {
266 foreach ($linkedInfo['linkedColumns'] as $col) {
267 $newCriteria[$col] = $obj->id
;
269 // create linked entities
270 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
271 $linkedInfo['findCriteria'],
273 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
276 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
277 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
285 self
::$status = NULL;
290 * This function iterates through when object criteria and
291 * generates recursive dates based on that
296 public function generateRecursiveDates() {
297 $this->generateRecursion();
299 $recursionDates = [];
300 if (is_a($this->recursion
, 'When\When')) {
301 $initialCount = $this->schedule
['start_action_offset'] ??
NULL;
303 $exRangeStart = $exRangeEnd = NULL;
304 if (!empty($this->excludeDateRangeColumns
)) {
305 $exRangeStart = $this->excludeDateRangeColumns
[0];
306 $exRangeEnd = $this->excludeDateRangeColumns
[1];
309 if (CRM_Core_Config
::singleton()->userFramework
== 'UnitTests') {
310 $this->recursion
->RFC5545_COMPLIANT
= When
::IGNORE
;
313 $result = $this->recursion_start_date
;
314 while ($result = $this->getNextOccurrence($result)) {
316 if ($result == $this->recursion_start_date
) {
317 // skip the recursion-start-date from the list we going to generate
320 $baseDate = $result->format('YmdHis');
322 foreach ($this->dateColumns
as $col) {
323 $recursionDates[$count][$col] = $baseDate;
325 foreach ($this->intervalDateColumns
as $col => $interval) {
326 $newDate = new DateTime($baseDate);
327 $newDate->add($interval);
328 $recursionDates[$count][$col] = $newDate->format('YmdHis');
331 $exRangeStartDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeStart, $recursionDates[$count]), NULL, FALSE, 'Ymd');
332 $exRangeEndDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeEnd, $recursionDates[$count]), NULL, FALSE, 'Ymd');
335 foreach ($this->excludeDates
as $exDate) {
336 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
337 if (!$exRangeStart) {
338 if ($exDate == $result->format('Ymd')) {
344 if (($exDate == $exRangeStartDate) ||
345 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
354 unset($recursionDates[$count]);
355 if ($initialCount && ($initialCount > 0)) {
356 // lets increase the counter, so we get correct number of occurrences
358 $this->recursion
->count($initialCount);
365 $this->recursionDates
= $recursionDates;
367 return $recursionDates;
371 * This function gets all the children for a particular parent entity.
373 * @param int $parentId
375 * @param string $entityTable
376 * Name of the entity table .
377 * @param bool $includeParent
378 * If true parent id is included in result set and vice versa .
380 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
381 * @param int $initiatorId
382 * The instance where this function is invoked from .
386 * an array of child ids
388 public static function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
390 if (empty($parentId) ||
empty($entityTable)) {
395 $initiatorId = $parentId;
399 1 => [$parentId, 'Integer'],
400 2 => [$entityTable, 'String'],
401 3 => [$initiatorId, 'Integer'],
405 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
409 FROM civicrm_recurring_entity
410 WHERE parent_id = %1 AND entity_table = %2";
411 if (!$includeParent) {
412 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
417 $query .= " AND entity_id = %3";
420 elseif ($mode == '2') {
421 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
422 if ($recurringEntityID) {
423 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
424 // FIXME: change to order by dates
425 $query .= " ORDER BY id ASC";
426 $queryParams[4] = [$recurringEntityID, 'Integer'];
429 // something wrong, return empty
434 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
435 while ($dao->fetch()) {
436 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
437 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
443 * This function when passed an entity id checks if it has parent and
444 * returns all other entities that are connected to same parent.
446 * @param int $entityId
448 * @param string $entityTable
449 * Entity table name .
450 * @param bool $includeParent
451 * Include parent in result set .
453 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
457 * array of connected ids
459 public static function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
460 $parentId = self
::getParentFor($entityId, $entityTable);
462 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
468 * This function gets the parent for the entity id passed to it.
470 * @param int $entityId
472 * @param string $entityTable
473 * Entity table name .
474 * @param bool $includeParent
475 * Include parent in result set .
479 * unsigned $parentId Parent ID
481 public static function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
482 if (empty($entityId) ||
empty($entityTable)) {
488 FROM civicrm_recurring_entity
489 WHERE entity_id = %1 AND entity_table = %2";
490 if (!$includeParent) {
491 $query .= " AND parent_id != %1";
494 = CRM_Core_DAO
::singleValueQuery($query,
496 1 => [$entityId, 'Integer'],
497 2 => [$entityTable, 'String'],
504 * Finds the position of this entity as well as total count of the repeating set
507 * @param $entityTable
510 public static function getPositionAndCount($entityId, $entityTable) {
511 $position = $count = 0;
515 FROM civicrm_recurring_entity
516 WHERE parent_id = (SELECT parent_id FROM civicrm_recurring_entity WHERE entity_id = %1 AND entity_table = %2) AND entity_table = %2";
518 $dao = CRM_Core_DAO
::executeQuery($query,
520 1 => [$entityId, 'Integer'],
521 2 => [$entityTable, 'String'],
525 while ($dao->fetch()) {
527 if ($dao->entity_id
<= $entityId) {
532 return [$position, $count];
538 * This function copies the information from parent entity and creates other entities with same information.
540 * @param string $entityTable
541 * Entity table name .
542 * @param array $fromCriteria
543 * Array of all the fields & values on which basis to copy .
544 * @param array $newParams
545 * Array of all the fields & values to be copied besides the other fields .
546 * @param bool $createRecurringEntity
547 * If to create a record in recurring_entity table .
551 * @throws new CRM_Core_Exception
553 public static function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
554 $daoName = self
::$_tableDAOMapper[$entityTable];
556 throw new CRM_Core_Exception("DAO Mapper missing for $entityTable.");
558 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
560 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
561 $object = new $daoName();
562 foreach ($fromCriteria as $key => $value) {
563 $object->$key = $value;
567 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
570 CRM_Utils_Hook
::copy(CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject);
575 * This function acts as a listener to dao->update whenever there is an update.
577 * It propagates any changes to all related entities present in recurring entity table
579 * @param object $event
580 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
582 public static function triggerUpdate($event) {
583 // if DB version is earlier than 4.6 skip any processing
584 static $currentVer = NULL;
586 $currentVer = CRM_Core_BAO_Domain
::version();
588 if (version_compare($currentVer, '4.6.alpha1') < 0) {
592 static $processedEntities = [];
593 $obj =& $event->object;
594 if (empty($obj->id
) ||
empty($obj->__table
)) {
597 $key = "{$obj->__table}_{$obj->id}";
599 if (array_key_exists($key, $processedEntities)) {
604 // get related entities
605 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
606 if (empty($repeatingEntities)) {
607 // return if its not a recurring entity parent
610 // mark being processed
611 $processedEntities[$key] = 1;
613 // to make sure we not copying to source itself
614 unset($repeatingEntities[$key]);
616 foreach ($repeatingEntities as $key => $val) {
617 $entityID = $val['id'];
618 $entityTable = $val['table'];
620 $processedEntities[$key] = 1;
622 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
623 $daoName = self
::$_tableDAOMapper[$entityTable];
626 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
627 $skipFields = self
::$_updateSkipFields[$entityTable];
628 foreach ($skipFields as $sfield) {
629 $skipData[$sfield] = NULL;
633 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
636 throw new CRM_Core_Exception("DAO Mapper missing for $entityTable.");
639 // done with processing. lets unset static var.
640 unset($processedEntities);
644 * This function acts as a listener to dao->save,
645 * and creates entries for linked entities in recurring entity table
647 * @param object $event
648 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
650 public static function triggerInsert($event) {
651 $obj =& $event->object;
652 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
656 // if DB version is earlier than 4.6 skip any processing
657 static $currentVer = NULL;
659 $currentVer = CRM_Core_BAO_Domain
::version();
661 if (version_compare($currentVer, '4.6.alpha1') < 0) {
665 static $processedEntities = [];
666 if (empty($obj->id
) ||
empty($obj->__table
)) {
669 $key = "{$obj->__table}_{$obj->id}";
671 if (array_key_exists($key, $processedEntities)) {
672 // already being processed. Exit recursive calls.
676 if (self
::getStatus() == self
::RUNNING
) {
677 // if recursion->generate() is doing some work, lets not intercept
681 // mark being processed
682 $processedEntities[$key] = 1;
684 // get related entities for table being saved
685 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
687 if (empty($hasaRecurringRecord)) {
688 // check if its a linked entity
689 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
690 empty(self
::$_linkedEntitiesInfo[$obj->__table
]['is_multirecord'])
692 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
693 $linkedDAO->id
= $obj->id
;
694 if ($linkedDAO->find(TRUE)) {
695 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
696 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
698 $pEntityID = $linkedDAO->$idCol;
699 $pEntityTable = $linkedDAO->$tableCol;
701 // find all parent recurring entity set
702 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
704 if (!empty($pRepeatingEntities)) {
705 // for each parent entity in the set, find out a similar linked entity,
706 // if doesn't exist create one, and also create entries in recurring_entity table
708 foreach ($pRepeatingEntities as $key => $val) {
709 if (array_key_exists($key, $processedEntities)) {
710 // this graph is already being processed
713 $processedEntities[$key] = 1;
716 // start with first entry with just itself
717 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
719 foreach ($pRepeatingEntities as $key => $val) {
720 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
721 $rlinkedDAO->$idCol = $val['id'];
722 $rlinkedDAO->$tableCol = $val['table'];
723 if ($rlinkedDAO->find(TRUE)) {
724 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
727 // linked entity doesn't exist. lets create them
729 $idCol => $val['id'],
730 $tableCol => $val['table'],
732 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
737 if ($linkedObj->id
) {
738 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
747 // done with processing. lets unset static var.
748 unset($processedEntities);
752 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
754 * @param object $event
755 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
757 public static function triggerDelete($event) {
758 $obj =& $event->object;
760 // if DB version is earlier than 4.6 skip any processing
761 static $currentVer = NULL;
763 $currentVer = CRM_Core_BAO_Domain
::version();
765 if (version_compare($currentVer, '4.6.alpha1') < 0) {
769 static $processedEntities = [];
770 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
773 $key = "{$obj->__table}_{$obj->id}";
775 if (array_key_exists($key, $processedEntities)) {
780 // mark being processed
781 $processedEntities[$key] = 1;
783 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
785 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
790 * This function deletes main entity and related linked entities from recurring-entity table.
792 * @param int $entityId
794 * @param string $entityTable
795 * Name of the entity table
797 * @param bool $isDelLinkedEntities
799 * @return bool|\CRM_Core_DAO_RecurringEntity
802 public static function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
803 if (empty($entityId) ||
empty($entityTable)) {
806 $dao = new CRM_Core_DAO_RecurringEntity();
807 $dao->entity_id
= $entityId;
808 $dao->entity_table
= $entityTable;
809 if ($dao->find(TRUE)) {
810 // make sure its not a linked entity thats being deleted
811 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
812 // delete all linked entities from recurring entity table
813 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
814 $daoName = self
::$_tableDAOMapper[$linkedTable];
816 throw new CRM_Core_Exception("DAO Mapper missing for $linkedTable.");
819 $linkedDao = new $daoName();
820 $linkedDao->{$linfo['entity_id_col']} = $entityId;
821 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
823 while ($linkedDao->fetch()) {
824 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
828 // delete main entity
829 return $dao->delete();
835 * This function maps values posted from form to civicrm_action_schedule columns.
837 * @param array $formParams
838 * And array of form values posted .
842 public function mapFormValuesToDB($formParams = []) {
844 if (!empty($formParams['used_for'])) {
845 $dbParams['used_for'] = $formParams['used_for'];
848 if (!empty($formParams['entity_id'])) {
849 $dbParams['entity_value'] = $formParams['entity_id'];
852 if (!empty($formParams['repetition_start_date'])) {
853 if (!empty($formParams['repetition_start_date_display'])) {
854 $repetitionStartDate = $formParams['repetition_start_date_display'];
857 $repetitionStartDate = $formParams['repetition_start_date'];
859 if (!empty($formParams['repetition_start_date_time'])) {
860 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
862 $repetition_start_date = new DateTime($repetitionStartDate);
863 $dbParams['start_action_date'] = $repetition_start_date->format('YmdHis');
866 if (!empty($formParams['repetition_frequency_unit'])) {
867 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
870 if (!empty($formParams['repetition_frequency_interval'])) {
871 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
874 //For Repeats on:(weekly case)
875 if ($formParams['repetition_frequency_unit'] == 'week') {
876 if (!empty($formParams['start_action_condition'])) {
877 $repeats_on = $formParams['start_action_condition'] ??
NULL;
878 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
882 //For Repeats By:(monthly case)
883 if ($formParams['repetition_frequency_unit'] == 'month') {
884 if ($formParams['repeats_by'] == 1) {
885 if (!empty($formParams['limit_to'])) {
886 $dbParams['limit_to'] = $formParams['limit_to'];
889 if ($formParams['repeats_by'] == 2) {
890 if (!empty($formParams['entity_status_1']) && !empty($formParams['entity_status_2'])) {
891 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
896 //For "Ends" - After:
897 if ($formParams['ends'] == 1) {
898 if (!empty($formParams['start_action_offset'])) {
899 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
904 if ($formParams['ends'] == 2) {
905 if (!empty($formParams['repeat_absolute_date'])) {
906 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
913 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
915 * @param int $scheduleReminderId
916 * Primary key of civicrm_action_schedule table .
921 public static function getScheduleReminderDetailsById($scheduleReminderId) {
923 FROM civicrm_action_schedule WHERE 1";
924 if ($scheduleReminderId) {
928 $dao = CRM_Core_DAO
::executeQuery($query,
930 1 => [$scheduleReminderId, 'Integer'],
938 * wrapper of getScheduleReminderDetailsById function.
940 * @param int $scheduleReminderId
941 * Primary key of civicrm_action_schedule table .
945 public function getScheduleParams($scheduleReminderId) {
946 $scheduleReminderDetails = [];
947 if ($scheduleReminderId) {
948 //Get all the details from schedule reminder table
949 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
950 $scheduleReminderDetails = (array) $scheduleReminderDetails;
952 return $scheduleReminderDetails;
956 * This function takes criteria saved in civicrm_action_schedule table
957 * and creates recursion rule
959 * @param array $scheduleReminderDetails
960 * Array of repeat criteria saved in civicrm_action_schedule table .
965 public function getRecursionFromSchedule($scheduleReminderDetails = []) {
967 //If there is some data for this id
968 if ($scheduleReminderDetails['repetition_frequency_unit']) {
969 if ($scheduleReminderDetails['start_action_date']) {
970 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
973 $currDate = date("Y-m-d H:i:s");
975 $start = new DateTime($currDate);
976 $this->recursion_start_date
= $start;
977 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
978 if ($repetition_frequency_unit == "day") {
979 $repetition_frequency_unit = "dai";
981 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
982 $r->startDate($start)
983 ->exclusions([$start])
984 ->freq($repetition_frequency_unit);
986 if ($scheduleReminderDetails['repetition_frequency_interval']) {
987 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
990 $r->errors
[] = 'Repeats every: is a required field';
994 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
995 if ($scheduleReminderDetails['start_action_condition']) {
996 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
997 $explodeStartActionCondition = explode(',', $startActionCondition);
998 $buildRuleArray = [];
999 foreach ($explodeStartActionCondition as $key => $val) {
1000 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
1002 $r->wkst('MO')->byday($buildRuleArray);
1007 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1008 if ($scheduleReminderDetails['entity_status']) {
1009 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1010 switch ($startActionDate[0]) {
1012 $startActionDate1 = 1;
1016 $startActionDate1 = 2;
1020 $startActionDate1 = 3;
1024 $startActionDate1 = 4;
1028 $startActionDate1 = -1;
1031 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1032 $r->byday([$concatStartActionDateBits]);
1034 elseif ($scheduleReminderDetails['limit_to']) {
1035 $r->bymonthday([$scheduleReminderDetails['limit_to']]);
1040 if ($scheduleReminderDetails['start_action_offset']) {
1041 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1042 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1044 $r->count($scheduleReminderDetails['start_action_offset']);
1047 if (!empty($scheduleReminderDetails['absolute_date'])) {
1048 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1049 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1050 // and we always want the date to be included, and therefore appending 23:59
1051 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
1052 $r->until($endDate);
1055 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1056 $r->errors
[] = 'Ends: is a required field';
1060 $r->errors
[] = 'Repeats: is a required field';
1066 * This function gets time difference between the two datetime object.
1068 * @param DateTime $startDate
1070 * @param DateTime $endDate
1075 * DateTime object which contain time difference
1077 public static function getInterval($startDate, $endDate) {
1078 if ($startDate && $endDate) {
1079 $startDate = new DateTime($startDate);
1080 $endDate = new DateTime($endDate);
1081 return $startDate->diff($endDate);
1086 * This function gets all columns from civicrm_action_schedule on the basis of event id.
1088 * @param int $entityId
1090 * @param string $used_for
1091 * Specifies for which entity type it's used for .
1096 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1100 FROM civicrm_action_schedule
1101 WHERE entity_value = %1";
1103 $query .= " AND used_for = %2";
1106 1 => [$entityId, 'Integer'],
1107 2 => [$used_for, 'String'],
1109 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1116 * Update mode column in civicrm_recurring_entity table for event related tabs.
1118 * @param int $entityId
1120 * @param string $linkedEntityTable
1121 * Linked entity table name for this event .
1122 * @param string $mainEntityTable
1126 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1128 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1129 if (!empty(self
::$_tableDAOMapper[$linkedEntityTable])) {
1130 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1133 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1136 $entityTable = $linkedEntityTable;
1138 'entity_id' => $entityId,
1139 'entity_table' => $mainEntityTable,
1142 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1143 if (!empty($defaults['id'])) {
1144 $result['entityId'] = $defaults['id'];
1145 $result['entityTable'] = $entityTable;
1152 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1154 * @param int $entityId
1156 * @param string $entityTable
1157 * @param string $mode
1158 * @param string $linkedEntityTable
1159 * Linked entity table name for this event .
1160 * @param string $priceSet
1161 * Price set of the event .
1165 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
1168 if (!empty($linkedEntityTable)) {
1169 $result = CRM_Core_BAO_RecurringEntity
::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1172 $dao = new CRM_Core_DAO_RecurringEntity();
1173 if (!empty($result)) {
1174 $dao->entity_id
= $result['entityId'];
1175 $dao->entity_table
= $result['entityTable'];
1178 $dao->entity_id
= $entityId;
1179 $dao->entity_table
= $entityTable;
1182 if ($dao->find(TRUE)) {
1188 //I am not sure about other fields, if mode = 3 apply for an event then other fields
1189 //should be save for all other series events or not so applying for price set only for now here.
1190 if (CRM_Core_BAO_RecurringEntity
::MODE_ALL_ENTITY_IN_SERIES
=== $mode) {
1191 //Step-1: Get all events of series
1192 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1193 foreach ($seriesEventRecords as $event) {
1194 //Step-2: Save price set in other series events
1195 //Remove existing priceset
1196 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1197 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1200 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1204 if (CRM_Core_BAO_RecurringEntity
::MODE_NEXT_ALL_ENTITY
=== $mode) {
1205 //Step-1: Get all events of series
1206 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1207 foreach ($seriesEventRecords as $event) {
1208 //Step-2: Save price set in other series events
1209 if ($entityId < $event["id"]) {
1210 //Remove existing priceset
1211 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1212 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1215 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1221 //CRM-20787 - Fix end
1222 $finalResult['status'] = 'Done';
1225 $finalResult['status'] = 'Error';
1228 return $finalResult;
1232 * Get next occurrence for the given date
1234 * @param \DateTime $occurDate
1235 * @param bool $strictly_after
1239 private function getNextOccurrence($occurDate, $strictly_after = TRUE) {
1241 return $this->recursion
->getNextOccurrence($occurDate, $strictly_after);
1243 catch (Exception
$exception) {
1244 CRM_Core_Session
::setStatus(ts($exception->getMessage()));