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 // if DB version is earlier than 4.6 skip any processing
592 static $currentVer = NULL;
594 $currentVer = CRM_Core_BAO_Domain
::version();
596 if (version_compare($currentVer, '4.6.alpha1') < 0) {
600 static $processedEntities = [];
601 $obj =& $event->object;
602 if (empty($obj->id
) ||
empty($obj->__table
)) {
605 $key = "{$obj->__table}_{$obj->id}";
607 if (array_key_exists($key, $processedEntities)) {
612 // get related entities
613 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
614 if (empty($repeatingEntities)) {
615 // return if its not a recurring entity parent
618 // mark being processed
619 $processedEntities[$key] = 1;
621 // to make sure we not copying to source itself
622 unset($repeatingEntities[$key]);
624 foreach ($repeatingEntities as $key => $val) {
625 $entityID = $val['id'];
626 $entityTable = $val['table'];
628 $processedEntities[$key] = 1;
630 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
631 $daoName = self
::$_tableDAOMapper[$entityTable];
634 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
635 $skipFields = self
::$_updateSkipFields[$entityTable];
636 foreach ($skipFields as $sfield) {
637 $skipData[$sfield] = NULL;
641 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
644 throw new CRM_Core_Exception("DAO Mapper missing for $entityTable.");
647 // done with processing. lets unset static var.
648 unset($processedEntities);
652 * This function acts as a listener to dao->save,
653 * and creates entries for linked entities in recurring entity table
655 * @param object $event
656 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
658 public static function triggerInsert($event) {
659 $obj =& $event->object;
660 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
664 // if DB version is earlier than 4.6 skip any processing
665 static $currentVer = NULL;
667 $currentVer = CRM_Core_BAO_Domain
::version();
669 if (version_compare($currentVer, '4.6.alpha1') < 0) {
673 static $processedEntities = [];
674 if (empty($obj->id
) ||
empty($obj->__table
)) {
677 $key = "{$obj->__table}_{$obj->id}";
679 if (array_key_exists($key, $processedEntities)) {
680 // already being processed. Exit recursive calls.
684 if (self
::getStatus() == self
::RUNNING
) {
685 // if recursion->generate() is doing some work, lets not intercept
689 // mark being processed
690 $processedEntities[$key] = 1;
692 // get related entities for table being saved
693 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
695 if (empty($hasaRecurringRecord)) {
696 // check if its a linked entity
697 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
698 empty(self
::$_linkedEntitiesInfo[$obj->__table
]['is_multirecord'])
700 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
701 $linkedDAO->id
= $obj->id
;
702 if ($linkedDAO->find(TRUE)) {
703 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
704 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
706 $pEntityID = $linkedDAO->$idCol;
707 $pEntityTable = $linkedDAO->$tableCol;
709 // find all parent recurring entity set
710 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
712 if (!empty($pRepeatingEntities)) {
713 // for each parent entity in the set, find out a similar linked entity,
714 // if doesn't exist create one, and also create entries in recurring_entity table
716 foreach ($pRepeatingEntities as $key => $val) {
717 if (array_key_exists($key, $processedEntities)) {
718 // this graph is already being processed
721 $processedEntities[$key] = 1;
724 // start with first entry with just itself
725 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
727 foreach ($pRepeatingEntities as $key => $val) {
728 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
729 $rlinkedDAO->$idCol = $val['id'];
730 $rlinkedDAO->$tableCol = $val['table'];
731 if ($rlinkedDAO->find(TRUE)) {
732 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
735 // linked entity doesn't exist. lets create them
737 $idCol => $val['id'],
738 $tableCol => $val['table'],
740 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
745 if ($linkedObj->id
) {
746 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
755 // done with processing. lets unset static var.
756 unset($processedEntities);
760 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
762 * @param object $event
763 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
765 public static function triggerDelete($event) {
766 $obj =& $event->object;
768 // if DB version is earlier than 4.6 skip any processing
769 static $currentVer = NULL;
771 $currentVer = CRM_Core_BAO_Domain
::version();
773 if (version_compare($currentVer, '4.6.alpha1') < 0) {
777 static $processedEntities = [];
778 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
781 $key = "{$obj->__table}_{$obj->id}";
783 if (array_key_exists($key, $processedEntities)) {
788 // mark being processed
789 $processedEntities[$key] = 1;
791 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
793 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
798 * This function deletes main entity and related linked entities from recurring-entity table.
800 * @param int $entityId
802 * @param string $entityTable
803 * Name of the entity table
805 * @param bool $isDelLinkedEntities
807 * @return bool|\CRM_Core_DAO_RecurringEntity
810 public static function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
811 if (empty($entityId) ||
empty($entityTable)) {
814 $dao = new CRM_Core_DAO_RecurringEntity();
815 $dao->entity_id
= $entityId;
816 $dao->entity_table
= $entityTable;
817 if ($dao->find(TRUE)) {
818 // make sure its not a linked entity thats being deleted
819 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
820 // delete all linked entities from recurring entity table
821 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
822 $daoName = self
::$_tableDAOMapper[$linkedTable];
824 throw new CRM_Core_Exception("DAO Mapper missing for $linkedTable.");
827 $linkedDao = new $daoName();
828 $linkedDao->{$linfo['entity_id_col']} = $entityId;
829 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
831 while ($linkedDao->fetch()) {
832 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
836 // delete main entity
837 return $dao->delete();
843 * This function maps values posted from form to civicrm_action_schedule columns.
845 * @param array $formParams
846 * And array of form values posted .
850 public function mapFormValuesToDB($formParams = []) {
852 if (!empty($formParams['used_for'])) {
853 $dbParams['used_for'] = $formParams['used_for'];
856 if (!empty($formParams['entity_id'])) {
857 $dbParams['entity_value'] = $formParams['entity_id'];
860 if (!empty($formParams['repetition_start_date'])) {
861 if (!empty($formParams['repetition_start_date_display'])) {
862 $repetitionStartDate = $formParams['repetition_start_date_display'];
865 $repetitionStartDate = $formParams['repetition_start_date'];
867 if (!empty($formParams['repetition_start_date_time'])) {
868 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
870 $repetition_start_date = new DateTime($repetitionStartDate);
871 $dbParams['start_action_date'] = $repetition_start_date->format('YmdHis');
874 if (!empty($formParams['repetition_frequency_unit'])) {
875 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
878 if (!empty($formParams['repetition_frequency_interval'])) {
879 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
882 //For Repeats on:(weekly case)
883 if ($formParams['repetition_frequency_unit'] == 'week') {
884 if (!empty($formParams['start_action_condition'])) {
885 $repeats_on = $formParams['start_action_condition'] ??
NULL;
886 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
890 //For Repeats By:(monthly case)
891 if ($formParams['repetition_frequency_unit'] == 'month') {
892 if ($formParams['repeats_by'] == 1) {
893 if (!empty($formParams['limit_to'])) {
894 $dbParams['limit_to'] = $formParams['limit_to'];
897 if ($formParams['repeats_by'] == 2) {
898 if (!empty($formParams['entity_status_1']) && !empty($formParams['entity_status_2'])) {
899 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
904 //For "Ends" - After:
905 if ($formParams['ends'] == 1) {
906 if (!empty($formParams['start_action_offset'])) {
907 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
912 if ($formParams['ends'] == 2) {
913 if (!empty($formParams['repeat_absolute_date'])) {
914 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
921 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
923 * @param int $scheduleReminderId
924 * Primary key of civicrm_action_schedule table .
929 public static function getScheduleReminderDetailsById($scheduleReminderId) {
931 FROM civicrm_action_schedule WHERE 1";
932 if ($scheduleReminderId) {
936 $dao = CRM_Core_DAO
::executeQuery($query,
938 1 => [$scheduleReminderId, 'Integer'],
946 * wrapper of getScheduleReminderDetailsById function.
948 * @param int $scheduleReminderId
949 * Primary key of civicrm_action_schedule table .
953 public function getScheduleParams($scheduleReminderId) {
954 $scheduleReminderDetails = [];
955 if ($scheduleReminderId) {
956 //Get all the details from schedule reminder table
957 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
958 $scheduleReminderDetails = (array) $scheduleReminderDetails;
960 return $scheduleReminderDetails;
964 * This function takes criteria saved in civicrm_action_schedule table
965 * and creates recursion rule
967 * @param array $scheduleReminderDetails
968 * Array of repeat criteria saved in civicrm_action_schedule table .
973 public function getRecursionFromSchedule($scheduleReminderDetails = []) {
975 //If there is some data for this id
976 if ($scheduleReminderDetails['repetition_frequency_unit']) {
977 if ($scheduleReminderDetails['start_action_date']) {
978 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
981 $currDate = date("Y-m-d H:i:s");
983 $start = new DateTime($currDate);
984 $this->recursion_start_date
= $start;
985 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
986 if ($repetition_frequency_unit == "day") {
987 $repetition_frequency_unit = "dai";
989 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
990 $r->startDate($start)
991 ->exclusions([$start])
992 ->freq($repetition_frequency_unit);
994 if ($scheduleReminderDetails['repetition_frequency_interval']) {
995 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
998 $r->errors
[] = 'Repeats every: is a required field';
1002 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
1003 if ($scheduleReminderDetails['start_action_condition']) {
1004 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
1005 $explodeStartActionCondition = explode(',', $startActionCondition);
1006 $buildRuleArray = [];
1007 foreach ($explodeStartActionCondition as $key => $val) {
1008 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
1010 $r->wkst('MO')->byday($buildRuleArray);
1015 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1016 if ($scheduleReminderDetails['entity_status']) {
1017 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1018 switch ($startActionDate[0]) {
1020 $startActionDate1 = 1;
1024 $startActionDate1 = 2;
1028 $startActionDate1 = 3;
1032 $startActionDate1 = 4;
1036 $startActionDate1 = -1;
1039 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1040 $r->byday([$concatStartActionDateBits]);
1042 elseif ($scheduleReminderDetails['limit_to']) {
1043 $r->bymonthday([$scheduleReminderDetails['limit_to']]);
1048 if ($scheduleReminderDetails['start_action_offset']) {
1049 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1050 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1052 $r->count($scheduleReminderDetails['start_action_offset']);
1055 if (!empty($scheduleReminderDetails['absolute_date'])) {
1056 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1057 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1058 // and we always want the date to be included, and therefore appending 23:59
1059 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
1060 $r->until($endDate);
1063 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1064 $r->errors
[] = 'Ends: is a required field';
1068 $r->errors
[] = 'Repeats: is a required field';
1074 * This function gets time difference between the two datetime object.
1076 * @param DateTime $startDate
1078 * @param DateTime $endDate
1083 * DateTime object which contain time difference
1085 public static function getInterval($startDate, $endDate) {
1086 if ($startDate && $endDate) {
1087 $startDate = new DateTime($startDate);
1088 $endDate = new DateTime($endDate);
1089 return $startDate->diff($endDate);
1094 * This function gets all columns from civicrm_action_schedule on the basis of event id.
1096 * @param int $entityId
1098 * @param string $used_for
1099 * Specifies for which entity type it's used for .
1104 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1108 FROM civicrm_action_schedule
1109 WHERE entity_value = %1";
1111 $query .= " AND used_for = %2";
1114 1 => [$entityId, 'Integer'],
1115 2 => [$used_for, 'String'],
1117 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1124 * Update mode column in civicrm_recurring_entity table for event related tabs.
1126 * @param int $entityId
1128 * @param string $linkedEntityTable
1129 * Linked entity table name for this event .
1130 * @param string $mainEntityTable
1134 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1136 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1137 if (!empty(self
::$_tableDAOMapper[$linkedEntityTable])) {
1138 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1141 CRM_Core_Session
::setStatus(ts('Could not update mode for linked entities'));
1144 $entityTable = $linkedEntityTable;
1146 'entity_id' => $entityId,
1147 'entity_table' => $mainEntityTable,
1150 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1151 if (!empty($defaults['id'])) {
1152 $result['entityId'] = $defaults['id'];
1153 $result['entityTable'] = $entityTable;
1160 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1162 * @param int $entityId
1164 * @param string $entityTable
1165 * @param string $mode
1166 * @param string $linkedEntityTable
1167 * Linked entity table name for this event .
1168 * @param string $priceSet
1169 * Price set of the event .
1173 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
1176 if (!empty($linkedEntityTable)) {
1177 $result = CRM_Core_BAO_RecurringEntity
::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1180 $dao = new CRM_Core_DAO_RecurringEntity();
1181 if (!empty($result)) {
1182 $dao->entity_id
= $result['entityId'];
1183 $dao->entity_table
= $result['entityTable'];
1186 $dao->entity_id
= $entityId;
1187 $dao->entity_table
= $entityTable;
1190 if ($dao->find(TRUE)) {
1196 //I am not sure about other fields, if mode = 3 apply for an event then other fields
1197 //should be save for all other series events or not so applying for price set only for now here.
1198 if (CRM_Core_BAO_RecurringEntity
::MODE_ALL_ENTITY_IN_SERIES
=== $mode) {
1199 //Step-1: Get all events of series
1200 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1201 foreach ($seriesEventRecords as $event) {
1202 //Step-2: Save price set in other series events
1203 //Remove existing priceset
1204 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1205 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1208 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1212 if (CRM_Core_BAO_RecurringEntity
::MODE_NEXT_ALL_ENTITY
=== $mode) {
1213 //Step-1: Get all events of series
1214 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1215 foreach ($seriesEventRecords as $event) {
1216 //Step-2: Save price set in other series events
1217 if ($entityId < $event["id"]) {
1218 //Remove existing priceset
1219 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1220 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1223 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1229 //CRM-20787 - Fix end
1230 $finalResult['status'] = 'Done';
1233 $finalResult['status'] = 'Error';
1236 return $finalResult;
1240 * Get next occurrence for the given date
1242 * @param \DateTime $occurDate
1243 * @param bool $strictly_after
1247 private function getNextOccurrence($occurDate, $strictly_after = TRUE) {
1249 return $this->recursion
->getNextOccurrence($occurDate, $strictly_after);
1251 catch (Exception
$exception) {
1252 CRM_Core_Session
::setStatus(ts($exception->getMessage()));