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 * Save records in civicrm_recurring_entity table.
139 * @param array $params
140 * Reference array contains the values submitted by the form.
144 public static function add(&$params) {
145 if (!empty($params['id'])) {
146 CRM_Utils_Hook
::pre('edit', 'RecurringEntity', $params['id'], $params);
149 CRM_Utils_Hook
::pre('create', 'RecurringEntity', NULL, $params);
152 $daoRecurringEntity = new CRM_Core_DAO_RecurringEntity();
153 $daoRecurringEntity->copyValues($params);
154 $daoRecurringEntity->find(TRUE);
155 $result = $daoRecurringEntity->save();
157 if (!empty($params['id'])) {
158 CRM_Utils_Hook
::post('edit', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
161 CRM_Utils_Hook
::post('create', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
167 * Wrapper for the function add() to add entry in recurring entity
169 * @param int $parentId
171 * @param int $entityId
173 * @param string $entityTable
174 * Name of the entity table .
179 public static function quickAdd($parentId, $entityId, $entityTable) {
182 'parent_id' => $parentId,
183 'entity_id' => $entityId,
184 'entity_table' => $entityTable,
186 return self
::add($params);
190 * This function updates the mode column in the civicrm_recurring_entity table.
193 * 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.
195 public function mode($mode) {
196 if ($this->entity_id
&& $this->entity_table
) {
197 if ($this->find(TRUE)) {
201 $this->parent_id
= $this->entity_id
;
209 * This function generates all new entities based on object vars.
213 public function generate() {
214 $this->generateRecursiveDates();
216 return $this->generateEntities();
220 * This function builds a "When" object based on schedule/reminder params
225 public function generateRecursion() {
226 // return if already generated
227 if (is_a($this->recursion
, 'When\When')) {
228 return $this->recursion
;
231 if ($this->scheduleId
) {
233 $this->schedule
= $this->getScheduleParams($this->scheduleId
);
235 elseif (!empty($this->scheduleFormValues
)) {
236 $this->schedule
= $this->mapFormValuesToDB($this->scheduleFormValues
);
239 if (!empty($this->schedule
)) {
240 $this->recursion
= $this->getRecursionFromSchedule($this->schedule
);
242 return $this->recursion
;
246 * Generate new DAOs and along with entries in civicrm_recurring_entity table.
250 public function generateEntities() {
251 self
::setStatus(self
::RUNNING
);
255 if (!empty($this->recursionDates
)) {
256 if ($this->entity_id
) {
257 $findCriteria = ['id' => $this->entity_id
];
259 // save an entry with initiating entity-id & entity-table
260 if ($this->entity_table
&& !$this->find(TRUE)) {
261 $this->parent_id
= $this->entity_id
;
265 if (empty($findCriteria)) {
266 CRM_Core_Error
::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
270 foreach ($this->recursionDates
as $key => $dateCols) {
271 $newCriteria = $dateCols;
272 foreach ($this->overwriteColumns
as $col => $val) {
273 $newCriteria[$col] = $val;
275 // create main entities
276 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
279 $this->isRecurringEntityRecord
282 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
284 $newEntities[$this->entity_table
][$count] = $obj->id
;
286 foreach ($this->linkedEntities
as $linkedInfo) {
287 foreach ($linkedInfo['linkedColumns'] as $col) {
288 $newCriteria[$col] = $obj->id
;
290 // create linked entities
291 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
292 $linkedInfo['findCriteria'],
294 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
297 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
298 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
306 self
::$status = NULL;
311 * This function iterates through when object criteria and
312 * generates recursive dates based on that
317 public function generateRecursiveDates() {
318 $this->generateRecursion();
320 $recursionDates = [];
321 if (is_a($this->recursion
, 'When\When')) {
322 $initialCount = CRM_Utils_Array
::value('start_action_offset', $this->schedule
);
324 $exRangeStart = $exRangeEnd = NULL;
325 if (!empty($this->excludeDateRangeColumns
)) {
326 $exRangeStart = $this->excludeDateRangeColumns
[0];
327 $exRangeEnd = $this->excludeDateRangeColumns
[1];
330 if (CRM_Core_Config
::singleton()->userFramework
== 'UnitTests') {
331 $this->recursion
->RFC5545_COMPLIANT
= When
::IGNORE
;
334 $result = $this->recursion_start_date
;
335 while ($result = $this->getNextOccurrence($result)) {
337 if ($result == $this->recursion_start_date
) {
338 // skip the recursion-start-date from the list we going to generate
341 $baseDate = $result->format('YmdHis');
343 foreach ($this->dateColumns
as $col) {
344 $recursionDates[$count][$col] = $baseDate;
346 foreach ($this->intervalDateColumns
as $col => $interval) {
347 $newDate = new DateTime($baseDate);
348 $newDate->add($interval);
349 $recursionDates[$count][$col] = $newDate->format('YmdHis');
352 $exRangeStartDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeStart, $recursionDates[$count]), NULL, FALSE, 'Ymd');
353 $exRangeEndDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeEnd, $recursionDates[$count]), NULL, FALSE, 'Ymd');
356 foreach ($this->excludeDates
as $exDate) {
357 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
358 if (!$exRangeStart) {
359 if ($exDate == $result->format('Ymd')) {
365 if (($exDate == $exRangeStartDate) ||
366 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
375 unset($recursionDates[$count]);
376 if ($initialCount && ($initialCount > 0)) {
377 // lets increase the counter, so we get correct number of occurrences
379 $this->recursion
->count($initialCount);
386 $this->recursionDates
= $recursionDates;
388 return $recursionDates;
392 * This function gets all the children for a particular parent entity.
394 * @param int $parentId
396 * @param string $entityTable
397 * Name of the entity table .
398 * @param bool $includeParent
399 * If true parent id is included in result set and vice versa .
401 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
402 * @param int $initiatorId
403 * The instance where this function is invoked from .
407 * an array of child ids
409 public static function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
411 if (empty($parentId) ||
empty($entityTable)) {
416 $initiatorId = $parentId;
420 1 => [$parentId, 'Integer'],
421 2 => [$entityTable, 'String'],
422 3 => [$initiatorId, 'Integer'],
426 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
430 FROM civicrm_recurring_entity
431 WHERE parent_id = %1 AND entity_table = %2";
432 if (!$includeParent) {
433 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
438 $query .= " AND entity_id = %3";
441 elseif ($mode == '2') {
442 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
443 if ($recurringEntityID) {
444 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
445 // FIXME: change to order by dates
446 $query .= " ORDER BY id ASC";
447 $queryParams[4] = [$recurringEntityID, 'Integer'];
450 // something wrong, return empty
455 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
456 while ($dao->fetch()) {
457 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
458 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
464 * This function when passed an entity id checks if it has parent and
465 * returns all other entities that are connected to same parent.
467 * @param int $entityId
469 * @param string $entityTable
470 * Entity table name .
471 * @param bool $includeParent
472 * Include parent in result set .
474 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
478 * array of connected ids
480 public static function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
481 $parentId = self
::getParentFor($entityId, $entityTable);
483 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
489 * This function gets the parent for the entity id passed to it.
491 * @param int $entityId
493 * @param string $entityTable
494 * Entity table name .
495 * @param bool $includeParent
496 * Include parent in result set .
500 * unsigned $parentId Parent ID
502 public static function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
503 if (empty($entityId) ||
empty($entityTable)) {
509 FROM civicrm_recurring_entity
510 WHERE entity_id = %1 AND entity_table = %2";
511 if (!$includeParent) {
512 $query .= " AND parent_id != %1";
515 = CRM_Core_DAO
::singleValueQuery($query,
517 1 => [$entityId, 'Integer'],
518 2 => [$entityTable, 'String'],
525 * Finds the position of this entity as well as total count of the repeating set
528 * @param $entityTable
531 public static function getPositionAndCount($entityId, $entityTable) {
532 $position = $count = 0;
536 FROM civicrm_recurring_entity
537 WHERE parent_id = (SELECT parent_id FROM civicrm_recurring_entity WHERE entity_id = %1 AND entity_table = %2) AND entity_table = %2";
539 $dao = CRM_Core_DAO
::executeQuery($query,
541 1 => [$entityId, 'Integer'],
542 2 => [$entityTable, 'String'],
546 while ($dao->fetch()) {
548 if ($dao->entity_id
<= $entityId) {
553 return [$position, $count];
559 * This function copies the information from parent entity and creates other entities with same information.
561 * @param string $entityTable
562 * Entity table name .
563 * @param array $fromCriteria
564 * Array of all the fields & values on which basis to copy .
565 * @param array $newParams
566 * Array of all the fields & values to be copied besides the other fields .
567 * @param bool $createRecurringEntity
568 * If to create a record in recurring_entity table .
573 public static function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
574 $daoName = self
::$_tableDAOMapper[$entityTable];
576 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
578 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
580 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
581 $object = new $daoName();
582 foreach ($fromCriteria as $key => $value) {
583 $object->$key = $value;
587 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
590 CRM_Utils_Hook
::copy(CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject);
595 * This function acts as a listener to dao->update whenever there is an update.
597 * It propagates any changes to all related entities present in recurring entity table
599 * @param object $event
600 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
602 public static function triggerUpdate($event) {
603 // if DB version is earlier than 4.6 skip any processing
604 static $currentVer = NULL;
606 $currentVer = CRM_Core_BAO_Domain
::version();
608 if (version_compare($currentVer, '4.6.alpha1') < 0) {
612 static $processedEntities = [];
613 $obj =& $event->object;
614 if (empty($obj->id
) ||
empty($obj->__table
)) {
617 $key = "{$obj->__table}_{$obj->id}";
619 if (array_key_exists($key, $processedEntities)) {
624 // get related entities
625 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
626 if (empty($repeatingEntities)) {
627 // return if its not a recurring entity parent
630 // mark being processed
631 $processedEntities[$key] = 1;
633 // to make sure we not copying to source itself
634 unset($repeatingEntities[$key]);
636 foreach ($repeatingEntities as $key => $val) {
637 $entityID = $val['id'];
638 $entityTable = $val['table'];
640 $processedEntities[$key] = 1;
642 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
643 $daoName = self
::$_tableDAOMapper[$entityTable];
646 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
647 $skipFields = self
::$_updateSkipFields[$entityTable];
648 foreach ($skipFields as $sfield) {
649 $skipData[$sfield] = NULL;
653 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
656 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
659 // done with processing. lets unset static var.
660 unset($processedEntities);
664 * This function acts as a listener to dao->save,
665 * and creates entries for linked entities in recurring entity table
667 * @param object $event
668 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
670 public static function triggerInsert($event) {
671 $obj =& $event->object;
672 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
676 // if DB version is earlier than 4.6 skip any processing
677 static $currentVer = NULL;
679 $currentVer = CRM_Core_BAO_Domain
::version();
681 if (version_compare($currentVer, '4.6.alpha1') < 0) {
685 static $processedEntities = [];
686 if (empty($obj->id
) ||
empty($obj->__table
)) {
689 $key = "{$obj->__table}_{$obj->id}";
691 if (array_key_exists($key, $processedEntities)) {
692 // already being processed. Exit recursive calls.
696 if (self
::getStatus() == self
::RUNNING
) {
697 // if recursion->generate() is doing some work, lets not intercept
701 // mark being processed
702 $processedEntities[$key] = 1;
704 // get related entities for table being saved
705 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
707 if (empty($hasaRecurringRecord)) {
708 // check if its a linked entity
709 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
710 !CRM_Utils_Array
::value('is_multirecord', self
::$_linkedEntitiesInfo[$obj->__table
])
712 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
713 $linkedDAO->id
= $obj->id
;
714 if ($linkedDAO->find(TRUE)) {
715 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
716 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
718 $pEntityID = $linkedDAO->$idCol;
719 $pEntityTable = $linkedDAO->$tableCol;
721 // find all parent recurring entity set
722 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
724 if (!empty($pRepeatingEntities)) {
725 // for each parent entity in the set, find out a similar linked entity,
726 // if doesn't exist create one, and also create entries in recurring_entity table
728 foreach ($pRepeatingEntities as $key => $val) {
729 if (array_key_exists($key, $processedEntities)) {
730 // this graph is already being processed
733 $processedEntities[$key] = 1;
736 // start with first entry with just itself
737 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
739 foreach ($pRepeatingEntities as $key => $val) {
740 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
741 $rlinkedDAO->$idCol = $val['id'];
742 $rlinkedDAO->$tableCol = $val['table'];
743 if ($rlinkedDAO->find(TRUE)) {
744 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
747 // linked entity doesn't exist. lets create them
749 $idCol => $val['id'],
750 $tableCol => $val['table'],
752 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
757 if ($linkedObj->id
) {
758 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
767 // done with processing. lets unset static var.
768 unset($processedEntities);
772 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
774 * @param object $event
775 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
777 public static function triggerDelete($event) {
778 $obj =& $event->object;
780 // if DB version is earlier than 4.6 skip any processing
781 static $currentVer = NULL;
783 $currentVer = CRM_Core_BAO_Domain
::version();
785 if (version_compare($currentVer, '4.6.alpha1') < 0) {
789 static $processedEntities = [];
790 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
793 $key = "{$obj->__table}_{$obj->id}";
795 if (array_key_exists($key, $processedEntities)) {
800 // mark being processed
801 $processedEntities[$key] = 1;
803 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
805 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
810 * This function deletes main entity and related linked entities from recurring-entity table.
812 * @param int $entityId
814 * @param string $entityTable
815 * Name of the entity table
817 * @param bool $isDelLinkedEntities
819 * @return bool|\CRM_Core_DAO_RecurringEntity
822 public static function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
823 if (empty($entityId) ||
empty($entityTable)) {
826 $dao = new CRM_Core_DAO_RecurringEntity();
827 $dao->entity_id
= $entityId;
828 $dao->entity_table
= $entityTable;
829 if ($dao->find(TRUE)) {
830 // make sure its not a linked entity thats being deleted
831 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
832 // delete all linked entities from recurring entity table
833 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
834 $daoName = self
::$_tableDAOMapper[$linkedTable];
836 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
839 $linkedDao = new $daoName();
840 $linkedDao->{$linfo['entity_id_col']} = $entityId;
841 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
843 while ($linkedDao->fetch()) {
844 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
848 // delete main entity
849 return $dao->delete();
855 * This function maps values posted from form to civicrm_action_schedule columns.
857 * @param array $formParams
858 * And array of form values posted .
862 public function mapFormValuesToDB($formParams = []) {
864 if (!empty($formParams['used_for'])) {
865 $dbParams['used_for'] = $formParams['used_for'];
868 if (!empty($formParams['entity_id'])) {
869 $dbParams['entity_value'] = $formParams['entity_id'];
872 if (!empty($formParams['repetition_start_date'])) {
873 if (!empty($formParams['repetition_start_date_display'])) {
874 $repetitionStartDate = $formParams['repetition_start_date_display'];
877 $repetitionStartDate = $formParams['repetition_start_date'];
879 if (!empty($formParams['repetition_start_date_time'])) {
880 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
882 $repetition_start_date = new DateTime($repetitionStartDate);
883 $dbParams['start_action_date'] = $repetition_start_date->format('YmdHis');
886 if (!empty($formParams['repetition_frequency_unit'])) {
887 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
890 if (!empty($formParams['repetition_frequency_interval'])) {
891 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
894 //For Repeats on:(weekly case)
895 if ($formParams['repetition_frequency_unit'] == 'week') {
896 if (!empty($formParams['start_action_condition'])) {
897 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
898 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
902 //For Repeats By:(monthly case)
903 if ($formParams['repetition_frequency_unit'] == 'month') {
904 if ($formParams['repeats_by'] == 1) {
905 if (!empty($formParams['limit_to'])) {
906 $dbParams['limit_to'] = $formParams['limit_to'];
909 if ($formParams['repeats_by'] == 2) {
910 if (!empty($formParams['entity_status_1']) && !empty($formParams['entity_status_2'])) {
911 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
916 //For "Ends" - After:
917 if ($formParams['ends'] == 1) {
918 if (!empty($formParams['start_action_offset'])) {
919 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
924 if ($formParams['ends'] == 2) {
925 if (!empty($formParams['repeat_absolute_date'])) {
926 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
933 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
935 * @param int $scheduleReminderId
936 * Primary key of civicrm_action_schedule table .
941 public static function getScheduleReminderDetailsById($scheduleReminderId) {
943 FROM civicrm_action_schedule WHERE 1";
944 if ($scheduleReminderId) {
948 $dao = CRM_Core_DAO
::executeQuery($query,
950 1 => [$scheduleReminderId, 'Integer'],
958 * wrapper of getScheduleReminderDetailsById function.
960 * @param int $scheduleReminderId
961 * Primary key of civicrm_action_schedule table .
965 public function getScheduleParams($scheduleReminderId) {
966 $scheduleReminderDetails = [];
967 if ($scheduleReminderId) {
968 //Get all the details from schedule reminder table
969 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
970 $scheduleReminderDetails = (array) $scheduleReminderDetails;
972 return $scheduleReminderDetails;
976 * This function takes criteria saved in civicrm_action_schedule table
977 * and creates recursion rule
979 * @param array $scheduleReminderDetails
980 * Array of repeat criteria saved in civicrm_action_schedule table .
985 public function getRecursionFromSchedule($scheduleReminderDetails = []) {
987 //If there is some data for this id
988 if ($scheduleReminderDetails['repetition_frequency_unit']) {
989 if ($scheduleReminderDetails['start_action_date']) {
990 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
993 $currDate = date("Y-m-d H:i:s");
995 $start = new DateTime($currDate);
996 $this->recursion_start_date
= $start;
997 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
998 if ($repetition_frequency_unit == "day") {
999 $repetition_frequency_unit = "dai";
1001 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
1002 $r->startDate($start)
1003 ->exclusions([$start])
1004 ->freq($repetition_frequency_unit);
1006 if ($scheduleReminderDetails['repetition_frequency_interval']) {
1007 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
1010 $r->errors
[] = 'Repeats every: is a required field';
1014 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
1015 if ($scheduleReminderDetails['start_action_condition']) {
1016 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
1017 $explodeStartActionCondition = explode(',', $startActionCondition);
1018 $buildRuleArray = [];
1019 foreach ($explodeStartActionCondition as $key => $val) {
1020 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
1022 $r->wkst('MO')->byday($buildRuleArray);
1027 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1028 if ($scheduleReminderDetails['entity_status']) {
1029 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1030 switch ($startActionDate[0]) {
1032 $startActionDate1 = 1;
1036 $startActionDate1 = 2;
1040 $startActionDate1 = 3;
1044 $startActionDate1 = 4;
1048 $startActionDate1 = -1;
1051 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1052 $r->byday([$concatStartActionDateBits]);
1054 elseif ($scheduleReminderDetails['limit_to']) {
1055 $r->bymonthday([$scheduleReminderDetails['limit_to']]);
1060 if ($scheduleReminderDetails['start_action_offset']) {
1061 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1062 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1064 $r->count($scheduleReminderDetails['start_action_offset']);
1067 if (!empty($scheduleReminderDetails['absolute_date'])) {
1068 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1069 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1070 // and we always want the date to be included, and therefore appending 23:59
1071 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
1072 $r->until($endDate);
1075 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1076 $r->errors
[] = 'Ends: is a required field';
1080 $r->errors
[] = 'Repeats: is a required field';
1086 * This function gets time difference between the two datetime object.
1088 * @param DateTime $startDate
1090 * @param DateTime $endDate
1095 * DateTime object which contain time difference
1097 public static function getInterval($startDate, $endDate) {
1098 if ($startDate && $endDate) {
1099 $startDate = new DateTime($startDate);
1100 $endDate = new DateTime($endDate);
1101 return $startDate->diff($endDate);
1106 * This function gets all columns from civicrm_action_schedule on the basis of event id.
1108 * @param int $entityId
1110 * @param string $used_for
1111 * Specifies for which entity type it's used for .
1116 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1120 FROM civicrm_action_schedule
1121 WHERE entity_value = %1";
1123 $query .= " AND used_for = %2";
1126 1 => [$entityId, 'Integer'],
1127 2 => [$used_for, 'String'],
1129 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1136 * Update mode column in civicrm_recurring_entity table for event related tabs.
1138 * @param int $entityId
1140 * @param string $linkedEntityTable
1141 * Linked entity table name for this event .
1142 * @param string $mainEntityTable
1146 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1148 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1149 if (!empty(self
::$_tableDAOMapper[$linkedEntityTable])) {
1150 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1153 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1156 $entityTable = $linkedEntityTable;
1158 'entity_id' => $entityId,
1159 'entity_table' => $mainEntityTable,
1162 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1163 if (!empty($defaults['id'])) {
1164 $result['entityId'] = $defaults['id'];
1165 $result['entityTable'] = $entityTable;
1172 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1174 * @param int $entityId
1176 * @param string $entityTable
1177 * @param string $mode
1178 * @param string $linkedEntityTable
1179 * Linked entity table name for this event .
1180 * @param string $priceSet
1181 * Price set of the event .
1185 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
1188 if (!empty($linkedEntityTable)) {
1189 $result = CRM_Core_BAO_RecurringEntity
::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1192 $dao = new CRM_Core_DAO_RecurringEntity();
1193 if (!empty($result)) {
1194 $dao->entity_id
= $result['entityId'];
1195 $dao->entity_table
= $result['entityTable'];
1198 $dao->entity_id
= $entityId;
1199 $dao->entity_table
= $entityTable;
1202 if ($dao->find(TRUE)) {
1208 //I am not sure about other fields, if mode = 3 apply for an event then other fields
1209 //should be save for all other series events or not so applying for price set only for now here.
1210 if (CRM_Core_BAO_RecurringEntity
::MODE_ALL_ENTITY_IN_SERIES
=== $mode) {
1211 //Step-1: Get all events of series
1212 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1213 foreach ($seriesEventRecords as $event) {
1214 //Step-2: Save price set in other series events
1215 //Remove existing priceset
1216 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1217 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1220 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1224 if (CRM_Core_BAO_RecurringEntity
::MODE_NEXT_ALL_ENTITY
=== $mode) {
1225 //Step-1: Get all events of series
1226 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1227 foreach ($seriesEventRecords as $event) {
1228 //Step-2: Save price set in other series events
1229 if ($entityId < $event["id"]) {
1230 //Remove existing priceset
1231 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1232 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1235 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1241 //CRM-20787 - Fix end
1242 $finalResult['status'] = 'Done';
1245 $finalResult['status'] = 'Error';
1248 return $finalResult;
1252 * Get next occurrence for the given date
1254 * @param \DateTime $occurDate
1255 * @param bool $strictly_after
1259 private function getNextOccurrence($occurDate, $strictly_after = TRUE) {
1261 return $this->recursion
->getNextOccurrence($occurDate, $strictly_after);
1263 catch (Exception
$exception) {
1264 CRM_Core_Session
::setStatus(ts($exception->getMessage()));