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.
228 public function generateEntities() {
229 self
::setStatus(self
::RUNNING
);
233 if (!empty($this->recursionDates
)) {
234 if ($this->entity_id
) {
235 $findCriteria = ['id' => $this->entity_id
];
237 // save an entry with initiating entity-id & entity-table
238 if ($this->entity_table
&& !$this->find(TRUE)) {
239 $this->parent_id
= $this->entity_id
;
243 if (empty($findCriteria)) {
244 CRM_Core_Error
::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
248 foreach ($this->recursionDates
as $key => $dateCols) {
249 $newCriteria = $dateCols;
250 foreach ($this->overwriteColumns
as $col => $val) {
251 $newCriteria[$col] = $val;
253 // create main entities
254 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
257 $this->isRecurringEntityRecord
260 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
262 $newEntities[$this->entity_table
][$count] = $obj->id
;
264 foreach ($this->linkedEntities
as $linkedInfo) {
265 foreach ($linkedInfo['linkedColumns'] as $col) {
266 $newCriteria[$col] = $obj->id
;
268 // create linked entities
269 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
270 $linkedInfo['findCriteria'],
272 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
275 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
276 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
284 self
::$status = NULL;
289 * This function iterates through when object criteria and
290 * generates recursive dates based on that
295 public function generateRecursiveDates() {
296 $this->generateRecursion();
298 $recursionDates = [];
299 if (is_a($this->recursion
, 'When\When')) {
300 $initialCount = $this->schedule
['start_action_offset'] ??
NULL;
302 $exRangeStart = $exRangeEnd = NULL;
303 if (!empty($this->excludeDateRangeColumns
)) {
304 $exRangeStart = $this->excludeDateRangeColumns
[0];
305 $exRangeEnd = $this->excludeDateRangeColumns
[1];
308 if (CRM_Core_Config
::singleton()->userFramework
== 'UnitTests') {
309 $this->recursion
->RFC5545_COMPLIANT
= When
::IGNORE
;
312 $result = $this->recursion_start_date
;
313 while ($result = $this->getNextOccurrence($result)) {
315 if ($result == $this->recursion_start_date
) {
316 // skip the recursion-start-date from the list we going to generate
319 $baseDate = $result->format('YmdHis');
321 foreach ($this->dateColumns
as $col) {
322 $recursionDates[$count][$col] = $baseDate;
324 foreach ($this->intervalDateColumns
as $col => $interval) {
325 $newDate = new DateTime($baseDate);
326 $newDate->add($interval);
327 $recursionDates[$count][$col] = $newDate->format('YmdHis');
330 $exRangeStartDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeStart, $recursionDates[$count]), NULL, FALSE, 'Ymd');
331 $exRangeEndDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeEnd, $recursionDates[$count]), NULL, FALSE, 'Ymd');
334 foreach ($this->excludeDates
as $exDate) {
335 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
336 if (!$exRangeStart) {
337 if ($exDate == $result->format('Ymd')) {
343 if (($exDate == $exRangeStartDate) ||
344 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
353 unset($recursionDates[$count]);
354 if ($initialCount && ($initialCount > 0)) {
355 // lets increase the counter, so we get correct number of occurrences
357 $this->recursion
->count($initialCount);
364 $this->recursionDates
= $recursionDates;
366 return $recursionDates;
370 * This function gets all the children for a particular parent entity.
372 * @param int $parentId
374 * @param string $entityTable
375 * Name of the entity table .
376 * @param bool $includeParent
377 * If true parent id is included in result set and vice versa .
379 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
380 * @param int $initiatorId
381 * The instance where this function is invoked from .
385 * an array of child ids
387 public static function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
389 if (empty($parentId) ||
empty($entityTable)) {
394 $initiatorId = $parentId;
398 1 => [$parentId, 'Integer'],
399 2 => [$entityTable, 'String'],
400 3 => [$initiatorId, 'Integer'],
404 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
408 FROM civicrm_recurring_entity
409 WHERE parent_id = %1 AND entity_table = %2";
410 if (!$includeParent) {
411 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
416 $query .= " AND entity_id = %3";
419 elseif ($mode == '2') {
420 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
421 if ($recurringEntityID) {
422 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
423 // FIXME: change to order by dates
424 $query .= " ORDER BY id ASC";
425 $queryParams[4] = [$recurringEntityID, 'Integer'];
428 // something wrong, return empty
433 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
434 while ($dao->fetch()) {
435 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
436 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
442 * This function when passed an entity id checks if it has parent and
443 * returns all other entities that are connected to same parent.
445 * @param int $entityId
447 * @param string $entityTable
448 * Entity table name .
449 * @param bool $includeParent
450 * Include parent in result set .
452 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
456 * array of connected ids
458 public static function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
459 $parentId = self
::getParentFor($entityId, $entityTable);
461 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
467 * This function gets the parent for the entity id passed to it.
469 * @param int $entityId
471 * @param string $entityTable
472 * Entity table name .
473 * @param bool $includeParent
474 * Include parent in result set .
478 * unsigned $parentId Parent ID
480 public static function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
481 if (empty($entityId) ||
empty($entityTable)) {
487 FROM civicrm_recurring_entity
488 WHERE entity_id = %1 AND entity_table = %2";
489 if (!$includeParent) {
490 $query .= " AND parent_id != %1";
493 = CRM_Core_DAO
::singleValueQuery($query,
495 1 => [$entityId, 'Integer'],
496 2 => [$entityTable, 'String'],
503 * Finds the position of this entity as well as total count of the repeating set
506 * @param $entityTable
509 public static function getPositionAndCount($entityId, $entityTable) {
510 $position = $count = 0;
514 FROM civicrm_recurring_entity
515 WHERE parent_id = (SELECT parent_id FROM civicrm_recurring_entity WHERE entity_id = %1 AND entity_table = %2) AND entity_table = %2";
517 $dao = CRM_Core_DAO
::executeQuery($query,
519 1 => [$entityId, 'Integer'],
520 2 => [$entityTable, 'String'],
524 while ($dao->fetch()) {
526 if ($dao->entity_id
<= $entityId) {
531 return [$position, $count];
537 * This function copies the information from parent entity and creates other entities with same information.
539 * @param string $entityTable
540 * Entity table name .
541 * @param array $fromCriteria
542 * Array of all the fields & values on which basis to copy .
543 * @param array $newParams
544 * Array of all the fields & values to be copied besides the other fields .
545 * @param bool $createRecurringEntity
546 * If to create a record in recurring_entity table .
551 public static function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
552 $daoName = self
::$_tableDAOMapper[$entityTable];
554 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
556 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
558 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
559 $object = new $daoName();
560 foreach ($fromCriteria as $key => $value) {
561 $object->$key = $value;
565 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
568 CRM_Utils_Hook
::copy(CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject);
573 * This function acts as a listener to dao->update whenever there is an update.
575 * It propagates any changes to all related entities present in recurring entity table
577 * @param object $event
578 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
580 public static function triggerUpdate($event) {
581 // if DB version is earlier than 4.6 skip any processing
582 static $currentVer = NULL;
584 $currentVer = CRM_Core_BAO_Domain
::version();
586 if (version_compare($currentVer, '4.6.alpha1') < 0) {
590 static $processedEntities = [];
591 $obj =& $event->object;
592 if (empty($obj->id
) ||
empty($obj->__table
)) {
595 $key = "{$obj->__table}_{$obj->id}";
597 if (array_key_exists($key, $processedEntities)) {
602 // get related entities
603 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
604 if (empty($repeatingEntities)) {
605 // return if its not a recurring entity parent
608 // mark being processed
609 $processedEntities[$key] = 1;
611 // to make sure we not copying to source itself
612 unset($repeatingEntities[$key]);
614 foreach ($repeatingEntities as $key => $val) {
615 $entityID = $val['id'];
616 $entityTable = $val['table'];
618 $processedEntities[$key] = 1;
620 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
621 $daoName = self
::$_tableDAOMapper[$entityTable];
624 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
625 $skipFields = self
::$_updateSkipFields[$entityTable];
626 foreach ($skipFields as $sfield) {
627 $skipData[$sfield] = NULL;
631 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
634 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
637 // done with processing. lets unset static var.
638 unset($processedEntities);
642 * This function acts as a listener to dao->save,
643 * and creates entries for linked entities in recurring entity table
645 * @param object $event
646 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
648 public static function triggerInsert($event) {
649 $obj =& $event->object;
650 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
654 // if DB version is earlier than 4.6 skip any processing
655 static $currentVer = NULL;
657 $currentVer = CRM_Core_BAO_Domain
::version();
659 if (version_compare($currentVer, '4.6.alpha1') < 0) {
663 static $processedEntities = [];
664 if (empty($obj->id
) ||
empty($obj->__table
)) {
667 $key = "{$obj->__table}_{$obj->id}";
669 if (array_key_exists($key, $processedEntities)) {
670 // already being processed. Exit recursive calls.
674 if (self
::getStatus() == self
::RUNNING
) {
675 // if recursion->generate() is doing some work, lets not intercept
679 // mark being processed
680 $processedEntities[$key] = 1;
682 // get related entities for table being saved
683 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
685 if (empty($hasaRecurringRecord)) {
686 // check if its a linked entity
687 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
688 !CRM_Utils_Array
::value('is_multirecord', self
::$_linkedEntitiesInfo[$obj->__table
])
690 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
691 $linkedDAO->id
= $obj->id
;
692 if ($linkedDAO->find(TRUE)) {
693 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
694 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
696 $pEntityID = $linkedDAO->$idCol;
697 $pEntityTable = $linkedDAO->$tableCol;
699 // find all parent recurring entity set
700 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
702 if (!empty($pRepeatingEntities)) {
703 // for each parent entity in the set, find out a similar linked entity,
704 // if doesn't exist create one, and also create entries in recurring_entity table
706 foreach ($pRepeatingEntities as $key => $val) {
707 if (array_key_exists($key, $processedEntities)) {
708 // this graph is already being processed
711 $processedEntities[$key] = 1;
714 // start with first entry with just itself
715 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
717 foreach ($pRepeatingEntities as $key => $val) {
718 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
719 $rlinkedDAO->$idCol = $val['id'];
720 $rlinkedDAO->$tableCol = $val['table'];
721 if ($rlinkedDAO->find(TRUE)) {
722 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
725 // linked entity doesn't exist. lets create them
727 $idCol => $val['id'],
728 $tableCol => $val['table'],
730 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
735 if ($linkedObj->id
) {
736 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
745 // done with processing. lets unset static var.
746 unset($processedEntities);
750 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
752 * @param object $event
753 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
755 public static function triggerDelete($event) {
756 $obj =& $event->object;
758 // if DB version is earlier than 4.6 skip any processing
759 static $currentVer = NULL;
761 $currentVer = CRM_Core_BAO_Domain
::version();
763 if (version_compare($currentVer, '4.6.alpha1') < 0) {
767 static $processedEntities = [];
768 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
771 $key = "{$obj->__table}_{$obj->id}";
773 if (array_key_exists($key, $processedEntities)) {
778 // mark being processed
779 $processedEntities[$key] = 1;
781 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
783 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
788 * This function deletes main entity and related linked entities from recurring-entity table.
790 * @param int $entityId
792 * @param string $entityTable
793 * Name of the entity table
795 * @param bool $isDelLinkedEntities
797 * @return bool|\CRM_Core_DAO_RecurringEntity
800 public static function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
801 if (empty($entityId) ||
empty($entityTable)) {
804 $dao = new CRM_Core_DAO_RecurringEntity();
805 $dao->entity_id
= $entityId;
806 $dao->entity_table
= $entityTable;
807 if ($dao->find(TRUE)) {
808 // make sure its not a linked entity thats being deleted
809 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
810 // delete all linked entities from recurring entity table
811 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
812 $daoName = self
::$_tableDAOMapper[$linkedTable];
814 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
817 $linkedDao = new $daoName();
818 $linkedDao->{$linfo['entity_id_col']} = $entityId;
819 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
821 while ($linkedDao->fetch()) {
822 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
826 // delete main entity
827 return $dao->delete();
833 * This function maps values posted from form to civicrm_action_schedule columns.
835 * @param array $formParams
836 * And array of form values posted .
840 public function mapFormValuesToDB($formParams = []) {
842 if (!empty($formParams['used_for'])) {
843 $dbParams['used_for'] = $formParams['used_for'];
846 if (!empty($formParams['entity_id'])) {
847 $dbParams['entity_value'] = $formParams['entity_id'];
850 if (!empty($formParams['repetition_start_date'])) {
851 if (!empty($formParams['repetition_start_date_display'])) {
852 $repetitionStartDate = $formParams['repetition_start_date_display'];
855 $repetitionStartDate = $formParams['repetition_start_date'];
857 if (!empty($formParams['repetition_start_date_time'])) {
858 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
860 $repetition_start_date = new DateTime($repetitionStartDate);
861 $dbParams['start_action_date'] = $repetition_start_date->format('YmdHis');
864 if (!empty($formParams['repetition_frequency_unit'])) {
865 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
868 if (!empty($formParams['repetition_frequency_interval'])) {
869 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
872 //For Repeats on:(weekly case)
873 if ($formParams['repetition_frequency_unit'] == 'week') {
874 if (!empty($formParams['start_action_condition'])) {
875 $repeats_on = $formParams['start_action_condition'] ??
NULL;
876 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
880 //For Repeats By:(monthly case)
881 if ($formParams['repetition_frequency_unit'] == 'month') {
882 if ($formParams['repeats_by'] == 1) {
883 if (!empty($formParams['limit_to'])) {
884 $dbParams['limit_to'] = $formParams['limit_to'];
887 if ($formParams['repeats_by'] == 2) {
888 if (!empty($formParams['entity_status_1']) && !empty($formParams['entity_status_2'])) {
889 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
894 //For "Ends" - After:
895 if ($formParams['ends'] == 1) {
896 if (!empty($formParams['start_action_offset'])) {
897 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
902 if ($formParams['ends'] == 2) {
903 if (!empty($formParams['repeat_absolute_date'])) {
904 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
911 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
913 * @param int $scheduleReminderId
914 * Primary key of civicrm_action_schedule table .
919 public static function getScheduleReminderDetailsById($scheduleReminderId) {
921 FROM civicrm_action_schedule WHERE 1";
922 if ($scheduleReminderId) {
926 $dao = CRM_Core_DAO
::executeQuery($query,
928 1 => [$scheduleReminderId, 'Integer'],
936 * wrapper of getScheduleReminderDetailsById function.
938 * @param int $scheduleReminderId
939 * Primary key of civicrm_action_schedule table .
943 public function getScheduleParams($scheduleReminderId) {
944 $scheduleReminderDetails = [];
945 if ($scheduleReminderId) {
946 //Get all the details from schedule reminder table
947 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
948 $scheduleReminderDetails = (array) $scheduleReminderDetails;
950 return $scheduleReminderDetails;
954 * This function takes criteria saved in civicrm_action_schedule table
955 * and creates recursion rule
957 * @param array $scheduleReminderDetails
958 * Array of repeat criteria saved in civicrm_action_schedule table .
963 public function getRecursionFromSchedule($scheduleReminderDetails = []) {
965 //If there is some data for this id
966 if ($scheduleReminderDetails['repetition_frequency_unit']) {
967 if ($scheduleReminderDetails['start_action_date']) {
968 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
971 $currDate = date("Y-m-d H:i:s");
973 $start = new DateTime($currDate);
974 $this->recursion_start_date
= $start;
975 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
976 if ($repetition_frequency_unit == "day") {
977 $repetition_frequency_unit = "dai";
979 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
980 $r->startDate($start)
981 ->exclusions([$start])
982 ->freq($repetition_frequency_unit);
984 if ($scheduleReminderDetails['repetition_frequency_interval']) {
985 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
988 $r->errors
[] = 'Repeats every: is a required field';
992 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
993 if ($scheduleReminderDetails['start_action_condition']) {
994 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
995 $explodeStartActionCondition = explode(',', $startActionCondition);
996 $buildRuleArray = [];
997 foreach ($explodeStartActionCondition as $key => $val) {
998 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
1000 $r->wkst('MO')->byday($buildRuleArray);
1005 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1006 if ($scheduleReminderDetails['entity_status']) {
1007 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1008 switch ($startActionDate[0]) {
1010 $startActionDate1 = 1;
1014 $startActionDate1 = 2;
1018 $startActionDate1 = 3;
1022 $startActionDate1 = 4;
1026 $startActionDate1 = -1;
1029 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1030 $r->byday([$concatStartActionDateBits]);
1032 elseif ($scheduleReminderDetails['limit_to']) {
1033 $r->bymonthday([$scheduleReminderDetails['limit_to']]);
1038 if ($scheduleReminderDetails['start_action_offset']) {
1039 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1040 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1042 $r->count($scheduleReminderDetails['start_action_offset']);
1045 if (!empty($scheduleReminderDetails['absolute_date'])) {
1046 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1047 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1048 // and we always want the date to be included, and therefore appending 23:59
1049 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
1050 $r->until($endDate);
1053 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1054 $r->errors
[] = 'Ends: is a required field';
1058 $r->errors
[] = 'Repeats: is a required field';
1064 * This function gets time difference between the two datetime object.
1066 * @param DateTime $startDate
1068 * @param DateTime $endDate
1073 * DateTime object which contain time difference
1075 public static function getInterval($startDate, $endDate) {
1076 if ($startDate && $endDate) {
1077 $startDate = new DateTime($startDate);
1078 $endDate = new DateTime($endDate);
1079 return $startDate->diff($endDate);
1084 * This function gets all columns from civicrm_action_schedule on the basis of event id.
1086 * @param int $entityId
1088 * @param string $used_for
1089 * Specifies for which entity type it's used for .
1094 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1098 FROM civicrm_action_schedule
1099 WHERE entity_value = %1";
1101 $query .= " AND used_for = %2";
1104 1 => [$entityId, 'Integer'],
1105 2 => [$used_for, 'String'],
1107 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1114 * Update mode column in civicrm_recurring_entity table for event related tabs.
1116 * @param int $entityId
1118 * @param string $linkedEntityTable
1119 * Linked entity table name for this event .
1120 * @param string $mainEntityTable
1124 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1126 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1127 if (!empty(self
::$_tableDAOMapper[$linkedEntityTable])) {
1128 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1131 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1134 $entityTable = $linkedEntityTable;
1136 'entity_id' => $entityId,
1137 'entity_table' => $mainEntityTable,
1140 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1141 if (!empty($defaults['id'])) {
1142 $result['entityId'] = $defaults['id'];
1143 $result['entityTable'] = $entityTable;
1150 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1152 * @param int $entityId
1154 * @param string $entityTable
1155 * @param string $mode
1156 * @param string $linkedEntityTable
1157 * Linked entity table name for this event .
1158 * @param string $priceSet
1159 * Price set of the event .
1163 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
1166 if (!empty($linkedEntityTable)) {
1167 $result = CRM_Core_BAO_RecurringEntity
::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1170 $dao = new CRM_Core_DAO_RecurringEntity();
1171 if (!empty($result)) {
1172 $dao->entity_id
= $result['entityId'];
1173 $dao->entity_table
= $result['entityTable'];
1176 $dao->entity_id
= $entityId;
1177 $dao->entity_table
= $entityTable;
1180 if ($dao->find(TRUE)) {
1186 //I am not sure about other fields, if mode = 3 apply for an event then other fields
1187 //should be save for all other series events or not so applying for price set only for now here.
1188 if (CRM_Core_BAO_RecurringEntity
::MODE_ALL_ENTITY_IN_SERIES
=== $mode) {
1189 //Step-1: Get all events of series
1190 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1191 foreach ($seriesEventRecords as $event) {
1192 //Step-2: Save price set in other series events
1193 //Remove existing priceset
1194 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1195 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1198 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1202 if (CRM_Core_BAO_RecurringEntity
::MODE_NEXT_ALL_ENTITY
=== $mode) {
1203 //Step-1: Get all events of series
1204 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1205 foreach ($seriesEventRecords as $event) {
1206 //Step-2: Save price set in other series events
1207 if ($entityId < $event["id"]) {
1208 //Remove existing priceset
1209 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1210 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1213 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1219 //CRM-20787 - Fix end
1220 $finalResult['status'] = 'Done';
1223 $finalResult['status'] = 'Error';
1226 return $finalResult;
1230 * Get next occurrence for the given date
1232 * @param \DateTime $occurDate
1233 * @param bool $strictly_after
1237 private function getNextOccurrence($occurDate, $strictly_after = TRUE) {
1239 return $this->recursion
->getNextOccurrence($occurDate, $strictly_after);
1241 catch (Exception
$exception) {
1242 CRM_Core_Session
::setStatus(ts($exception->getMessage()));