3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
34 require_once 'packages/When/When.php';
37 * Class CRM_Core_BAO_RecurringEntity.
39 class CRM_Core_BAO_RecurringEntity
extends CRM_Core_DAO_RecurringEntity
{
42 public $schedule = array();
43 public $scheduleId = NULL;
44 public $scheduleFormValues = array();
46 public $dateColumns = array();
47 public $overwriteColumns = array();
48 public $intervalDateColumns = array();
49 public $excludeDates = array();
51 public $linkedEntities = array();
53 public $isRecurringEntityRecord = TRUE;
55 protected $recursion = NULL;
56 protected $recursion_start_date = NULL;
58 public static $_entitiesToBeDeleted = array();
60 public static $status = NULL;
62 static $_recurringEntityHelper
64 'civicrm_event' => array(
65 'helper_class' => 'CRM_Event_DAO_Event',
66 'delete_func' => 'delete',
67 'pre_delete_func' => 'CRM_Event_Form_ManageEvent_Repeat::checkRegistrationForEvents',
69 'civicrm_activity' => array(
70 'helper_class' => 'CRM_Activity_DAO_Activity',
71 'delete_func' => 'delete',
72 'pre_delete_func' => '',
78 'civicrm_event' => array(
79 'dateColumns' => array('start_date'),
80 'excludeDateRangeColumns' => array('start_date', 'end_date'),
81 'intervalDateColumns' => array('end_date'),
83 'civicrm_activity' => array(
84 'dateColumns' => array('activity_date_time'),
88 static $_tableDAOMapper
90 'civicrm_event' => 'CRM_Event_DAO_Event',
91 'civicrm_price_set_entity' => 'CRM_Price_DAO_PriceSetEntity',
92 'civicrm_uf_join' => 'CRM_Core_DAO_UFJoin',
93 'civicrm_tell_friend' => 'CRM_Friend_DAO_Friend',
94 'civicrm_pcp_block' => 'CRM_PCP_DAO_PCPBlock',
95 'civicrm_activity' => 'CRM_Activity_DAO_Activity',
96 'civicrm_activity_contact' => 'CRM_Activity_DAO_ActivityContact',
99 static $_updateSkipFields
101 'civicrm_event' => array('start_date', 'end_date'),
102 'civicrm_tell_friend' => array('entity_id'),
103 'civicrm_pcp_block' => array('entity_id'),
104 'civicrm_activity' => array('activity_date_time'),
107 static $_linkedEntitiesInfo
109 'civicrm_tell_friend' => array(
110 'entity_id_col' => 'entity_id',
111 'entity_table_col' => 'entity_table',
113 'civicrm_price_set_entity' => array(
114 'entity_id_col' => 'entity_id',
115 'entity_table_col' => 'entity_table',
116 'is_multirecord' => TRUE,
118 'civicrm_uf_join' => array(
119 'entity_id_col' => 'entity_id',
120 'entity_table_col' => 'entity_table',
121 'is_multirecord' => TRUE,
123 'civicrm_pcp_block' => array(
124 'entity_id_col' => 'entity_id',
125 'entity_table_col' => 'entity_table',
129 //Define global CLASS CONSTANTS for recurring entity mode types
130 const MODE_THIS_ENTITY_ONLY
= 1;
131 const MODE_NEXT_ALL_ENTITY
= 2;
132 const MODE_ALL_ENTITY_IN_SERIES
= 3;
139 public static function getStatus() {
140 return self
::$status;
146 * @param string $status
148 public static function setStatus($status) {
149 self
::$status = $status;
153 * Save records in civicrm_recurring_entity table.
155 * @param array $params
156 * Reference array contains the values submitted by the form.
160 public static function add(&$params) {
161 if (!empty($params['id'])) {
162 CRM_Utils_Hook
::pre('edit', 'RecurringEntity', $params['id'], $params);
165 CRM_Utils_Hook
::pre('create', 'RecurringEntity', NULL, $params);
168 $daoRecurringEntity = new CRM_Core_DAO_RecurringEntity();
169 $daoRecurringEntity->copyValues($params);
170 $daoRecurringEntity->find(TRUE);
171 $result = $daoRecurringEntity->save();
173 if (!empty($params['id'])) {
174 CRM_Utils_Hook
::post('edit', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
177 CRM_Utils_Hook
::post('create', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
183 * Wrapper for the function add() to add entry in recurring entity
185 * @param int $parentId
187 * @param int $entityId
189 * @param string $entityTable
190 * Name of the entity table .
195 public static function quickAdd($parentId, $entityId, $entityTable) {
198 'parent_id' => $parentId,
199 'entity_id' => $entityId,
200 'entity_table' => $entityTable,
202 return self
::add($params);
206 * This function updates the mode column in the civicrm_recurring_entity table.
209 * 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.
211 public function mode($mode) {
212 if ($this->entity_id
&& $this->entity_table
) {
213 if ($this->find(TRUE)) {
217 $this->parent_id
= $this->entity_id
;
225 * This function generates all new entities based on object vars.
229 public function generate() {
230 $this->generateRecursiveDates();
232 return $this->generateEntities();
236 * This function builds a "When" object based on schedule/reminder params
241 public function generateRecursion() {
242 // return if already generated
243 if (is_a($this->recursion
, 'When')) {
244 return $this->recursion
;
247 if ($this->scheduleId
) {
249 $this->schedule
= $this->getScheduleParams($this->scheduleId
);
251 elseif (!empty($this->scheduleFormValues
)) {
252 $this->schedule
= $this->mapFormValuesToDB($this->scheduleFormValues
);
255 if (!empty($this->schedule
)) {
256 $this->recursion
= $this->getRecursionFromSchedule($this->schedule
);
258 return $this->recursion
;
262 * Generate new DAOs and along with entries in civicrm_recurring_entity table.
266 public function generateEntities() {
267 self
::setStatus(self
::RUNNING
);
269 $newEntities = array();
270 $findCriteria = array();
271 if (!empty($this->recursionDates
)) {
272 if ($this->entity_id
) {
273 $findCriteria = array('id' => $this->entity_id
);
275 // save an entry with initiating entity-id & entity-table
276 if ($this->entity_table
&& !$this->find(TRUE)) {
277 $this->parent_id
= $this->entity_id
;
281 if (empty($findCriteria)) {
282 CRM_Core_Error
::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
286 foreach ($this->recursionDates
as $key => $dateCols) {
287 $newCriteria = $dateCols;
288 foreach ($this->overwriteColumns
as $col => $val) {
289 $newCriteria[$col] = $val;
291 // create main entities
292 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
295 $this->isRecurringEntityRecord
298 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
299 $newCriteria = array();
300 $newEntities[$this->entity_table
][$count] = $obj->id
;
302 foreach ($this->linkedEntities
as $linkedInfo) {
303 foreach ($linkedInfo['linkedColumns'] as $col) {
304 $newCriteria[$col] = $obj->id
;
306 // create linked entities
307 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
308 $linkedInfo['findCriteria'],
310 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
313 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
314 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
322 self
::$status = NULL;
327 * This function iterates through when object criteria and
328 * generates recursive dates based on that
333 public function generateRecursiveDates() {
334 $this->generateRecursion();
336 $recursionDates = array();
337 if (is_a($this->recursion
, 'When')) {
338 $initialCount = CRM_Utils_Array
::value('start_action_offset', $this->schedule
);
340 $exRangeStart = $exRangeEnd = NULL;
341 if (!empty($this->excludeDateRangeColumns
)) {
342 $exRangeStart = $this->excludeDateRangeColumns
[0];
343 $exRangeEnd = $this->excludeDateRangeColumns
[1];
347 while ($result = $this->recursion
->next()) {
349 if ($result == $this->recursion_start_date
) {
350 // skip the recursion-start-date from the list we going to generate
353 $baseDate = CRM_Utils_Date
::processDate($result->format('Y-m-d H:i:s'));
355 foreach ($this->dateColumns
as $col) {
356 $recursionDates[$count][$col] = $baseDate;
358 foreach ($this->intervalDateColumns
as $col => $interval) {
359 $newDate = new DateTime($baseDate);
360 $newDate->add($interval);
361 $recursionDates[$count][$col] = CRM_Utils_Date
::processDate($newDate->format('Y-m-d H:i:s'));
364 $exRangeStartDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeStart, $recursionDates[$count]), NULL, FALSE, 'Ymd');
365 $exRangeEndDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeEnd, $recursionDates[$count]), NULL, FALSE, 'Ymd');
368 foreach ($this->excludeDates
as $exDate) {
369 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
370 if (!$exRangeStart) {
371 if ($exDate == $result->format('Ymd')) {
377 if (($exDate == $exRangeStartDate) ||
378 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
387 unset($recursionDates[$count]);
388 if ($initialCount && ($initialCount > 0)) {
389 // lets increase the counter, so we get correct number of occurrences
391 $this->recursion
->count($initialCount);
398 $this->recursionDates
= $recursionDates;
400 return $recursionDates;
404 * This function gets all the children for a particular parent entity.
406 * @param int $parentId
408 * @param string $entityTable
409 * Name of the entity table .
410 * @param bool $includeParent
411 * If true parent id is included in result set and vice versa .
413 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
414 * @param int $initiatorId
415 * The instance where this function is invoked from .
419 * an array of child ids
421 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
423 if (empty($parentId) ||
empty($entityTable)) {
428 $initiatorId = $parentId;
431 $queryParams = array(
432 1 => array($parentId, 'Integer'),
433 2 => array($entityTable, 'String'),
434 3 => array($initiatorId, 'Integer'),
438 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
442 FROM civicrm_recurring_entity
443 WHERE parent_id = %1 AND entity_table = %2";
444 if (!$includeParent) {
445 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
450 $query .= " AND entity_id = %3";
453 elseif ($mode == '2') {
454 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
455 if ($recurringEntityID) {
456 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
457 $query .= " ORDER BY id ASC"; // FIXME: change to order by dates
458 $queryParams[4] = array($recurringEntityID, 'Integer');
461 // something wrong, return empty
466 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
467 while ($dao->fetch()) {
468 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
469 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
475 * This function when passed an entity id checks if it has parent and
476 * returns all other entities that are connected to same parent.
478 * @param int $entityId
480 * @param string $entityTable
481 * Entity table name .
482 * @param bool $includeParent
483 * Include parent in result set .
485 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
489 * array of connected ids
491 static public function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
492 $parentId = self
::getParentFor($entityId, $entityTable);
494 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
500 * This function gets the parent for the entity id passed to it.
502 * @param int $entityId
504 * @param string $entityTable
505 * Entity table name .
506 * @param bool $includeParent
507 * Include parent in result set .
511 * unsigned $parentId Parent ID
513 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
514 if (empty($entityId) ||
empty($entityTable)) {
520 FROM civicrm_recurring_entity
521 WHERE entity_id = %1 AND entity_table = %2";
522 if (!$includeParent) {
523 $query .= " AND parent_id != %1";
526 = CRM_Core_DAO
::singleValueQuery($query,
528 1 => array($entityId, 'Integer'),
529 2 => array($entityTable, 'String'),
536 * Finds the position of this entity as well as total count of the repeating set
539 * @param $entityTable
542 static public function getPositionAndCount($entityId, $entityTable) {
543 $position = $count = 0;
547 FROM civicrm_recurring_entity
548 WHERE parent_id = (SELECT parent_id FROM civicrm_recurring_entity WHERE entity_id = %1 AND entity_table = %2) AND entity_table = %2";
550 $dao = CRM_Core_DAO
::executeQuery($query,
552 1 => array($entityId, 'Integer'),
553 2 => array($entityTable, 'String'),
557 while ($dao->fetch()) {
559 if ($dao->entity_id
<= $entityId) {
564 return array($position, $count);
570 * This function copies the information from parent entity and creates other entities with same information.
572 * @param string $entityTable
573 * Entity table name .
574 * @param array $fromCriteria
575 * Array of all the fields & values on which basis to copy .
576 * @param array $newParams
577 * Array of all the fields & values to be copied besides the other fields .
578 * @param bool $createRecurringEntity
579 * If to create a record in recurring_entity table .
584 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
585 $daoName = self
::$_tableDAOMapper[$entityTable];
587 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
589 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
591 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
592 $object = new $daoName();
593 foreach ($fromCriteria as $key => $value) {
594 $object->$key = $value;
598 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
604 * This function acts as a listener to dao->update whenever there is an update.
606 * It propagates any changes to all related entities present in recurring entity table
608 * @param object $event
609 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
611 static public function triggerUpdate($event) {
612 // if DB version is earlier than 4.6 skip any processing
613 static $currentVer = NULL;
615 $currentVer = CRM_Core_BAO_Domain
::version();
617 if (version_compare($currentVer, '4.6.alpha1') < 0) {
621 static $processedEntities = array();
622 $obj =& $event->object;
623 if (empty($obj->id
) ||
empty($obj->__table
)) {
626 $key = "{$obj->__table}_{$obj->id}";
628 if (array_key_exists($key, $processedEntities)) {
633 // get related entities
634 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
635 if (empty($repeatingEntities)) {
636 // return if its not a recurring entity parent
639 // mark being processed
640 $processedEntities[$key] = 1;
642 // to make sure we not copying to source itself
643 unset($repeatingEntities[$key]);
645 foreach ($repeatingEntities as $key => $val) {
646 $entityID = $val['id'];
647 $entityTable = $val['table'];
649 $processedEntities[$key] = 1;
651 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
652 $daoName = self
::$_tableDAOMapper[$entityTable];
655 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
656 $skipFields = self
::$_updateSkipFields[$entityTable];
657 foreach ($skipFields as $sfield) {
658 $skipData[$sfield] = NULL;
662 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
663 CRM_Core_DAO
::freeResult();
666 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
669 // done with processing. lets unset static var.
670 unset($processedEntities);
674 * This function acts as a listener to dao->save,
675 * and creates entries for linked entities in recurring entity table
677 * @param object $event
678 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
680 static public function triggerInsert($event) {
681 $obj =& $event->object;
682 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
686 // if DB version is earlier than 4.6 skip any processing
687 static $currentVer = NULL;
689 $currentVer = CRM_Core_BAO_Domain
::version();
691 if (version_compare($currentVer, '4.6.alpha1') < 0) {
695 static $processedEntities = array();
696 if (empty($obj->id
) ||
empty($obj->__table
)) {
699 $key = "{$obj->__table}_{$obj->id}";
701 if (array_key_exists($key, $processedEntities)) {
702 // already being processed. Exit recursive calls.
706 if (self
::getStatus() == self
::RUNNING
) {
707 // if recursion->generate() is doing some work, lets not intercept
711 // mark being processed
712 $processedEntities[$key] = 1;
714 // get related entities for table being saved
715 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
717 if (empty($hasaRecurringRecord)) {
718 // check if its a linked entity
719 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
720 !CRM_Utils_Array
::value('is_multirecord', self
::$_linkedEntitiesInfo[$obj->__table
])
722 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
723 $linkedDAO->id
= $obj->id
;
724 if ($linkedDAO->find(TRUE)) {
725 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
726 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
728 $pEntityID = $linkedDAO->$idCol;
729 $pEntityTable = $linkedDAO->$tableCol;
731 // find all parent recurring entity set
732 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
734 if (!empty($pRepeatingEntities)) {
735 // for each parent entity in the set, find out a similar linked entity,
736 // if doesn't exist create one, and also create entries in recurring_entity table
738 foreach ($pRepeatingEntities as $key => $val) {
739 if (array_key_exists($key, $processedEntities)) {
740 // this graph is already being processed
743 $processedEntities[$key] = 1;
746 // start with first entry with just itself
747 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
749 foreach ($pRepeatingEntities as $key => $val) {
750 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
751 $rlinkedDAO->$idCol = $val['id'];
752 $rlinkedDAO->$tableCol = $val['table'];
753 if ($rlinkedDAO->find(TRUE)) {
754 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
757 // linked entity doesn't exist. lets create them
758 $newCriteria = array(
759 $idCol => $val['id'],
760 $tableCol => $val['table'],
762 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
763 array('id' => $obj->id
),
767 if ($linkedObj->id
) {
768 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
777 // done with processing. lets unset static var.
778 unset($processedEntities);
782 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
784 * @param object $event
785 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
787 static public function triggerDelete($event) {
788 $obj =& $event->object;
790 // if DB version is earlier than 4.6 skip any processing
791 static $currentVer = NULL;
793 $currentVer = CRM_Core_BAO_Domain
::version();
795 if (version_compare($currentVer, '4.6.alpha1') < 0) {
799 static $processedEntities = array();
800 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
803 $key = "{$obj->__table}_{$obj->id}";
805 if (array_key_exists($key, $processedEntities)) {
810 // mark being processed
811 $processedEntities[$key] = 1;
813 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
815 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
820 * This function deletes main entity and related linked entities from recurring-entity table.
822 * @param int $entityId
824 * @param string $entityTable
825 * Name of the entity table
827 * @param bool $isDelLinkedEntities
829 * @return bool|\CRM_Core_DAO_RecurringEntity
832 static public function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
833 if (empty($entityId) ||
empty($entityTable)) {
836 $dao = new CRM_Core_DAO_RecurringEntity();
837 $dao->entity_id
= $entityId;
838 $dao->entity_table
= $entityTable;
839 if ($dao->find(TRUE)) {
840 // make sure its not a linked entity thats being deleted
841 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
842 // delete all linked entities from recurring entity table
843 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
844 $daoName = self
::$_tableDAOMapper[$linkedTable];
846 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
849 $linkedDao = new $daoName();
850 $linkedDao->{$linfo['entity_id_col']} = $entityId;
851 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
853 while ($linkedDao->fetch()) {
854 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
858 // delete main entity
859 return $dao->delete();
865 * This function maps values posted from form to civicrm_action_schedule columns.
867 * @param array $formParams
868 * And array of form values posted .
872 public function mapFormValuesToDB($formParams = array()) {
874 if (!empty($formParams['used_for'])) {
875 $dbParams['used_for'] = $formParams['used_for'];
878 if (!empty($formParams['entity_id'])) {
879 $dbParams['entity_value'] = $formParams['entity_id'];
882 if (!empty($formParams['repetition_start_date'])) {
883 if (!empty($formParams['repetition_start_date_display'])) {
884 $repetitionStartDate = $formParams['repetition_start_date_display'];
887 $repetitionStartDate = $formParams['repetition_start_date'];
889 if (!empty($formParams['repetition_start_date_time'])) {
890 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
892 $repetition_start_date = new DateTime($repetitionStartDate);
893 $dbParams['start_action_date'] = CRM_Utils_Date
::processDate($repetition_start_date->format('Y-m-d H:i:s'));
896 if (!empty($formParams['repetition_frequency_unit'])) {
897 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
900 if (!empty($formParams['repetition_frequency_interval'])) {
901 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
904 //For Repeats on:(weekly case)
905 if ($formParams['repetition_frequency_unit'] == 'week') {
906 if (!empty($formParams['start_action_condition'])) {
907 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
908 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
912 //For Repeats By:(monthly case)
913 if ($formParams['repetition_frequency_unit'] == 'month') {
914 if ($formParams['repeats_by'] == 1) {
915 if (!empty($formParams['limit_to'])) {
916 $dbParams['limit_to'] = $formParams['limit_to'];
919 if ($formParams['repeats_by'] == 2) {
920 if (CRM_Utils_Array
::value('entity_status_1', $formParams) && CRM_Utils_Array
::value('entity_status_2', $formParams)) {
921 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
926 //For "Ends" - After:
927 if ($formParams['ends'] == 1) {
928 if (!empty($formParams['start_action_offset'])) {
929 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
934 if ($formParams['ends'] == 2) {
935 if (!empty($formParams['repeat_absolute_date'])) {
936 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
943 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
945 * @param int $scheduleReminderId
946 * Primary key of civicrm_action_schedule table .
951 static public function getScheduleReminderDetailsById($scheduleReminderId) {
953 FROM civicrm_action_schedule WHERE 1";
954 if ($scheduleReminderId) {
958 $dao = CRM_Core_DAO
::executeQuery($query,
960 1 => array($scheduleReminderId, 'Integer'),
968 * wrapper of getScheduleReminderDetailsById function.
970 * @param int $scheduleReminderId
971 * Primary key of civicrm_action_schedule table .
975 public function getScheduleParams($scheduleReminderId) {
976 $scheduleReminderDetails = array();
977 if ($scheduleReminderId) {
978 //Get all the details from schedule reminder table
979 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
980 $scheduleReminderDetails = (array) $scheduleReminderDetails;
982 return $scheduleReminderDetails;
986 * This function takes criteria saved in civicrm_action_schedule table
987 * and creates recursion rule
989 * @param array $scheduleReminderDetails
990 * Array of repeat criteria saved in civicrm_action_schedule table .
995 public function getRecursionFromSchedule($scheduleReminderDetails = array()) {
997 //If there is some data for this id
998 if ($scheduleReminderDetails['repetition_frequency_unit']) {
999 if ($scheduleReminderDetails['start_action_date']) {
1000 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
1003 $currDate = date("Y-m-d H:i:s");
1005 $start = new DateTime($currDate);
1006 $this->recursion_start_date
= $start;
1007 if ($scheduleReminderDetails['repetition_frequency_unit']) {
1008 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
1009 if ($repetition_frequency_unit == "day") {
1010 $repetition_frequency_unit = "dai";
1012 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
1013 $r->recur($start, $repetition_frequency_unit);
1016 if ($scheduleReminderDetails['repetition_frequency_interval']) {
1017 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
1020 $r->errors
[] = 'Repeats every: is a required field';
1024 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
1025 if ($scheduleReminderDetails['start_action_condition']) {
1026 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
1027 $explodeStartActionCondition = explode(',', $startActionCondition);
1028 $buildRuleArray = array();
1029 foreach ($explodeStartActionCondition as $key => $val) {
1030 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
1032 $r->wkst('MO')->byday($buildRuleArray);
1037 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1038 if ($scheduleReminderDetails['entity_status']) {
1039 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1040 switch ($startActionDate[0]) {
1042 $startActionDate1 = 1;
1046 $startActionDate1 = 2;
1050 $startActionDate1 = 3;
1054 $startActionDate1 = 4;
1058 $startActionDate1 = -1;
1061 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1062 $r->byday(array($concatStartActionDateBits));
1064 elseif ($scheduleReminderDetails['limit_to']) {
1065 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
1070 if ($scheduleReminderDetails['start_action_offset']) {
1071 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1072 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1074 $r->count($scheduleReminderDetails['start_action_offset']);
1077 if (!empty($scheduleReminderDetails['absolute_date'])) {
1078 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1079 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1080 // and we always want the date to be included, and therefore appending 23:59
1081 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
1082 $r->until($endDate);
1085 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1086 $r->errors
[] = 'Ends: is a required field';
1090 $r->errors
[] = 'Repeats: is a required field';
1097 * This function gets time difference between the two datetime object.
1099 * @param DateTime $startDate
1101 * @param DateTime $endDate
1106 * DateTime object which contain time difference
1108 static public function getInterval($startDate, $endDate) {
1109 if ($startDate && $endDate) {
1110 $startDate = new DateTime($startDate);
1111 $endDate = new DateTime($endDate);
1112 return $startDate->diff($endDate);
1117 * This function gets all columns from civicrm_action_schedule on the basis of event id.
1119 * @param int $entityId
1121 * @param string $used_for
1122 * Specifies for which entity type it's used for .
1127 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1131 FROM civicrm_action_schedule
1132 WHERE entity_value = %1";
1134 $query .= " AND used_for = %2";
1137 1 => array($entityId, 'Integer'),
1138 2 => array($used_for, 'String'),
1140 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1147 * Update mode column in civicrm_recurring_entity table for event related tabs.
1149 * @param int $entityId
1151 * @param string $linkedEntityTable
1152 * Linked entity table name for this event .
1153 * @param string $mainEntityTable
1157 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1159 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1160 if (CRM_Utils_Array
::value($linkedEntityTable, self
::$_tableDAOMapper)) {
1161 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1164 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1167 $entityTable = $linkedEntityTable;
1169 'entity_id' => $entityId,
1170 'entity_table' => $mainEntityTable,
1172 $defaults = array();
1173 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1174 if (!empty($defaults['id'])) {
1175 $result['entityId'] = $defaults['id'];
1176 $result['entityTable'] = $entityTable;
1183 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1185 * @param int $entityId
1187 * @param string $entityTable
1188 * @param string $mode
1189 * @param string $linkedEntityTable
1190 * Linked entity table name for this event .
1191 * @param string $priceSet
1192 * Price set of the event .
1196 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
1197 $finalResult = array();
1199 if (!empty($linkedEntityTable)) {
1200 $result = CRM_Core_BAO_RecurringEntity
::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1203 $dao = new CRM_Core_DAO_RecurringEntity();
1204 if (!empty($result)) {
1205 $dao->entity_id
= $result['entityId'];
1206 $dao->entity_table
= $result['entityTable'];
1209 $dao->entity_id
= $entityId;
1210 $dao->entity_table
= $entityTable;
1213 if ($dao->find(TRUE)) {
1219 //I am not sure about other fields, if mode = 3 apply for an event then other fields
1220 //should be save for all other series events or not so applying for price set only for now here.
1221 if (CRM_Core_BAO_RecurringEntity
::MODE_ALL_ENTITY_IN_SERIES
=== $mode) {
1222 //Step-1: Get all events of series
1223 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1224 foreach ($seriesEventRecords as $event) {
1225 //Step-2: Save price set in other series events
1226 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {//Remove existing priceset
1227 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1229 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet); //Add new price set
1233 if (CRM_Core_BAO_RecurringEntity
::MODE_NEXT_ALL_ENTITY
=== $mode) {
1234 //Step-1: Get all events of series
1235 $seriesEventRecords = CRM_Core_BAO_RecurringEntity
::getEntitiesFor($entityId, $entityTable);
1236 foreach ($seriesEventRecords as $event) {
1237 //Step-2: Save price set in other series events
1238 if ($entityId < $event["id"]) {
1239 if (CRM_Price_BAO_PriceSet
::removeFrom($event['table'], $event['id'])) {//Remove existing priceset
1240 CRM_Core_BAO_Discount
::del($event['id'], $event['table']);
1242 CRM_Price_BAO_PriceSet
::addTo($event['table'], $event['id'], $priceSet); //Add new price set
1248 //CRM-20787 - Fix end
1249 $finalResult['status'] = 'Done';
1252 $finalResult['status'] = 'Error';
1255 return $finalResult;