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);
593 * This function acts as a listener to dao->update whenever there is an update.
595 * It propagates any changes to all related entities present in recurring entity table
597 * @param object $event
598 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
600 public static function triggerUpdate($event) {
601 // if DB version is earlier than 4.6 skip any processing
602 static $currentVer = NULL;
604 $currentVer = CRM_Core_BAO_Domain
::version();
606 if (version_compare($currentVer, '4.6.alpha1') < 0) {
610 static $processedEntities = [];
611 $obj =& $event->object;
612 if (empty($obj->id
) ||
empty($obj->__table
)) {
615 $key = "{$obj->__table}_{$obj->id}";
617 if (array_key_exists($key, $processedEntities)) {
622 // get related entities
623 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
624 if (empty($repeatingEntities)) {
625 // return if its not a recurring entity parent
628 // mark being processed
629 $processedEntities[$key] = 1;
631 // to make sure we not copying to source itself
632 unset($repeatingEntities[$key]);
634 foreach ($repeatingEntities as $key => $val) {
635 $entityID = $val['id'];
636 $entityTable = $val['table'];
638 $processedEntities[$key] = 1;
640 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
641 $daoName = self
::$_tableDAOMapper[$entityTable];
644 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
645 $skipFields = self
::$_updateSkipFields[$entityTable];
646 foreach ($skipFields as $sfield) {
647 $skipData[$sfield] = NULL;
651 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
654 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
657 // done with processing. lets unset static var.
658 unset($processedEntities);
662 * This function acts as a listener to dao->save,
663 * and creates entries for linked entities in recurring entity table
665 * @param object $event
666 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
668 public static function triggerInsert($event) {
669 $obj =& $event->object;
670 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
674 // if DB version is earlier than 4.6 skip any processing
675 static $currentVer = NULL;
677 $currentVer = CRM_Core_BAO_Domain
::version();
679 if (version_compare($currentVer, '4.6.alpha1') < 0) {
683 static $processedEntities = [];
684 if (empty($obj->id
) ||
empty($obj->__table
)) {
687 $key = "{$obj->__table}_{$obj->id}";
689 if (array_key_exists($key, $processedEntities)) {
690 // already being processed. Exit recursive calls.
694 if (self
::getStatus() == self
::RUNNING
) {
695 // if recursion->generate() is doing some work, lets not intercept
699 // mark being processed
700 $processedEntities[$key] = 1;
702 // get related entities for table being saved
703 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
705 if (empty($hasaRecurringRecord)) {
706 // check if its a linked entity
707 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
708 !CRM_Utils_Array
::value('is_multirecord', self
::$_linkedEntitiesInfo[$obj->__table
])
710 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
711 $linkedDAO->id
= $obj->id
;
712 if ($linkedDAO->find(TRUE)) {
713 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
714 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
716 $pEntityID = $linkedDAO->$idCol;
717 $pEntityTable = $linkedDAO->$tableCol;
719 // find all parent recurring entity set
720 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
722 if (!empty($pRepeatingEntities)) {
723 // for each parent entity in the set, find out a similar linked entity,
724 // if doesn't exist create one, and also create entries in recurring_entity table
726 foreach ($pRepeatingEntities as $key => $val) {
727 if (array_key_exists($key, $processedEntities)) {
728 // this graph is already being processed
731 $processedEntities[$key] = 1;
734 // start with first entry with just itself
735 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
737 foreach ($pRepeatingEntities as $key => $val) {
738 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
739 $rlinkedDAO->$idCol = $val['id'];
740 $rlinkedDAO->$tableCol = $val['table'];
741 if ($rlinkedDAO->find(TRUE)) {
742 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
745 // linked entity doesn't exist. lets create them
747 $idCol => $val['id'],
748 $tableCol => $val['table'],
750 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
755 if ($linkedObj->id
) {
756 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
765 // done with processing. lets unset static var.
766 unset($processedEntities);
770 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
772 * @param object $event
773 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
775 public static function triggerDelete($event) {
776 $obj =& $event->object;
778 // if DB version is earlier than 4.6 skip any processing
779 static $currentVer = NULL;
781 $currentVer = CRM_Core_BAO_Domain
::version();
783 if (version_compare($currentVer, '4.6.alpha1') < 0) {
787 static $processedEntities = [];
788 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
791 $key = "{$obj->__table}_{$obj->id}";
793 if (array_key_exists($key, $processedEntities)) {
798 // mark being processed
799 $processedEntities[$key] = 1;
801 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
803 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
808 * This function deletes main entity and related linked entities from recurring-entity table.
810 * @param int $entityId
812 * @param string $entityTable
813 * Name of the entity table
815 * @param bool $isDelLinkedEntities
817 * @return bool|\CRM_Core_DAO_RecurringEntity
820 public static function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
821 if (empty($entityId) ||
empty($entityTable)) {
824 $dao = new CRM_Core_DAO_RecurringEntity();
825 $dao->entity_id
= $entityId;
826 $dao->entity_table
= $entityTable;
827 if ($dao->find(TRUE)) {
828 // make sure its not a linked entity thats being deleted
829 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
830 // delete all linked entities from recurring entity table
831 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
832 $daoName = self
::$_tableDAOMapper[$linkedTable];
834 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
837 $linkedDao = new $daoName();
838 $linkedDao->{$linfo['entity_id_col']} = $entityId;
839 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
841 while ($linkedDao->fetch()) {
842 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
846 // delete main entity
847 return $dao->delete();
853 * This function maps values posted from form to civicrm_action_schedule columns.
855 * @param array $formParams
856 * And array of form values posted .
860 public function mapFormValuesToDB($formParams = []) {
862 if (!empty($formParams['used_for'])) {
863 $dbParams['used_for'] = $formParams['used_for'];
866 if (!empty($formParams['entity_id'])) {
867 $dbParams['entity_value'] = $formParams['entity_id'];
870 if (!empty($formParams['repetition_start_date'])) {
871 if (!empty($formParams['repetition_start_date_display'])) {
872 $repetitionStartDate = $formParams['repetition_start_date_display'];
875 $repetitionStartDate = $formParams['repetition_start_date'];
877 if (!empty($formParams['repetition_start_date_time'])) {
878 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
880 $repetition_start_date = new DateTime($repetitionStartDate);
881 $dbParams['start_action_date'] = $repetition_start_date->format('YmdHis');
884 if (!empty($formParams['repetition_frequency_unit'])) {
885 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
888 if (!empty($formParams['repetition_frequency_interval'])) {
889 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
892 //For Repeats on:(weekly case)
893 if ($formParams['repetition_frequency_unit'] == 'week') {
894 if (!empty($formParams['start_action_condition'])) {
895 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
896 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
900 //For Repeats By:(monthly case)
901 if ($formParams['repetition_frequency_unit'] == 'month') {
902 if ($formParams['repeats_by'] == 1) {
903 if (!empty($formParams['limit_to'])) {
904 $dbParams['limit_to'] = $formParams['limit_to'];
907 if ($formParams['repeats_by'] == 2) {
908 if (!empty($formParams['entity_status_1']) && !empty($formParams['entity_status_2'])) {
909 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
914 //For "Ends" - After:
915 if ($formParams['ends'] == 1) {
916 if (!empty($formParams['start_action_offset'])) {
917 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
922 if ($formParams['ends'] == 2) {
923 if (!empty($formParams['repeat_absolute_date'])) {
924 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
931 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
933 * @param int $scheduleReminderId
934 * Primary key of civicrm_action_schedule table .
939 public static function getScheduleReminderDetailsById($scheduleReminderId) {
941 FROM civicrm_action_schedule WHERE 1";
942 if ($scheduleReminderId) {
946 $dao = CRM_Core_DAO
::executeQuery($query,
948 1 => [$scheduleReminderId, 'Integer'],
956 * wrapper of getScheduleReminderDetailsById function.
958 * @param int $scheduleReminderId
959 * Primary key of civicrm_action_schedule table .
963 public function getScheduleParams($scheduleReminderId) {
964 $scheduleReminderDetails = [];
965 if ($scheduleReminderId) {
966 //Get all the details from schedule reminder table
967 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
968 $scheduleReminderDetails = (array) $scheduleReminderDetails;
970 return $scheduleReminderDetails;
974 * This function takes criteria saved in civicrm_action_schedule table
975 * and creates recursion rule
977 * @param array $scheduleReminderDetails
978 * Array of repeat criteria saved in civicrm_action_schedule table .
983 public function getRecursionFromSchedule($scheduleReminderDetails = []) {
985 //If there is some data for this id
986 if ($scheduleReminderDetails['repetition_frequency_unit']) {
987 if ($scheduleReminderDetails['start_action_date']) {
988 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
991 $currDate = date("Y-m-d H:i:s");
993 $start = new DateTime($currDate);
994 $this->recursion_start_date
= $start;
995 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
996 if ($repetition_frequency_unit == "day") {
997 $repetition_frequency_unit = "dai";
999 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
1000 $r->startDate($start)
1001 ->exclusions([$start])
1002 ->freq($repetition_frequency_unit);
1004 if ($scheduleReminderDetails['repetition_frequency_interval']) {
1005 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
1008 $r->errors
[] = 'Repeats every: is a required field';
1012 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
1013 if ($scheduleReminderDetails['start_action_condition']) {
1014 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
1015 $explodeStartActionCondition = explode(',', $startActionCondition);
1016 $buildRuleArray = [];
1017 foreach ($explodeStartActionCondition as $key => $val) {
1018 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
1020 $r->wkst('MO')->byday($buildRuleArray);
1025 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1026 if ($scheduleReminderDetails['entity_status']) {
1027 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1028 switch ($startActionDate[0]) {
1030 $startActionDate1 = 1;
1034 $startActionDate1 = 2;
1038 $startActionDate1 = 3;
1042 $startActionDate1 = 4;
1046 $startActionDate1 = -1;
1049 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1050 $r->byday([$concatStartActionDateBits]);
1052 elseif ($scheduleReminderDetails['limit_to']) {
1053 $r->bymonthday([$scheduleReminderDetails['limit_to']]);
1058 if ($scheduleReminderDetails['start_action_offset']) {
1059 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1060 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1062 $r->count($scheduleReminderDetails['start_action_offset']);
1065 if (!empty($scheduleReminderDetails['absolute_date'])) {
1066 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1067 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1068 // and we always want the date to be included, and therefore appending 23:59
1069 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
1070 $r->until($endDate);
1073 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1074 $r->errors
[] = 'Ends: is a required field';
1078 $r->errors
[] = 'Repeats: is a required field';
1084 * This function gets time difference between the two datetime object.
1086 * @param DateTime $startDate
1088 * @param DateTime $endDate
1093 * DateTime object which contain time difference
1095 public static function getInterval($startDate, $endDate) {
1096 if ($startDate && $endDate) {
1097 $startDate = new DateTime($startDate);
1098 $endDate = new DateTime($endDate);
1099 return $startDate->diff($endDate);
1104 * This function gets all columns from civicrm_action_schedule on the basis of event id.
1106 * @param int $entityId
1108 * @param string $used_for
1109 * Specifies for which entity type it's used for .
1114 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1118 FROM civicrm_action_schedule
1119 WHERE entity_value = %1";
1121 $query .= " AND used_for = %2";
1124 1 => [$entityId, 'Integer'],
1125 2 => [$used_for, 'String'],
1127 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1134 * Update mode column in civicrm_recurring_entity table for event related tabs.
1136 * @param int $entityId
1138 * @param string $linkedEntityTable
1139 * Linked entity table name for this event .
1140 * @param string $mainEntityTable
1144 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1146 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1147 if (CRM_Utils_Array
::value($linkedEntityTable, self
::$_tableDAOMapper)) {
1148 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1151 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1154 $entityTable = $linkedEntityTable;
1156 'entity_id' => $entityId,
1157 'entity_table' => $mainEntityTable,
1160 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1161 if (!empty($defaults['id'])) {
1162 $result['entityId'] = $defaults['id'];
1163 $result['entityTable'] = $entityTable;
1170 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1172 * @param int $entityId
1174 * @param string $entityTable
1175 * @param string $mode
1176 * @param string $linkedEntityTable
1177 * Linked entity table name for this event .
1178 * @param string $priceSet
1179 * Price set of the event .
1183 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
1186 if (!empty($linkedEntityTable)) {
1187 $result = CRM_Core_BAO_RecurringEntity
::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1190 $dao = new CRM_Core_DAO_RecurringEntity();
1191 if (!empty($result)) {
1192 $dao->entity_id
= $result['entityId'];
1193 $dao->entity_table
= $result['entityTable'];
1196 $dao->entity_id
= $entityId;
1197 $dao->entity_table
= $entityTable;
1200 if ($dao->find(TRUE)) {
1206 //I am not sure about other fields, if mode = 3 apply for an event then other fields
1207 //should be save for all other series events or not so applying for price set only for now here.
1208 if (CRM_Core_BAO_RecurringEntity
::MODE_ALL_ENTITY_IN_SERIES
=== $mode) {
1209 //Step-1: Get all events of series
1210 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1211 foreach ($seriesEventRecords as $event) {
1212 //Step-2: Save price set in other series events
1213 //Remove existing priceset
1214 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1215 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1218 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1222 if (CRM_Core_BAO_RecurringEntity
::MODE_NEXT_ALL_ENTITY
=== $mode) {
1223 //Step-1: Get all events of series
1224 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1225 foreach ($seriesEventRecords as $event) {
1226 //Step-2: Save price set in other series events
1227 if ($entityId < $event["id"]) {
1228 //Remove existing priceset
1229 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {
1230 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1233 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet);
1239 //CRM-20787 - Fix end
1240 $finalResult['status'] = 'Done';
1243 $finalResult['status'] = 'Error';
1246 return $finalResult;
1250 * Get next occurrence for the given date
1252 * @param \DateTime $occurDate
1253 * @param bool $strictly_after
1257 private function getNextOccurrence($occurDate, $strictly_after = TRUE) {
1259 return $this->recursion
->getNextOccurrence($occurDate, $strictly_after);
1261 catch (Exception
$exception) {
1262 CRM_Core_Session
::setStatus(ts($exception->getMessage()));