3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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',
134 public static function getStatus() {
135 return self
::$status;
141 * @param string $status
143 public static function setStatus($status) {
144 self
::$status = $status;
148 * Save records in civicrm_recurring_entity table.
150 * @param array $params
151 * Reference array contains the values submitted by the form.
155 public static function add(&$params) {
156 if (!empty($params['id'])) {
157 CRM_Utils_Hook
::pre('edit', 'RecurringEntity', $params['id'], $params);
160 CRM_Utils_Hook
::pre('create', 'RecurringEntity', NULL, $params);
163 $daoRecurringEntity = new CRM_Core_DAO_RecurringEntity();
164 $daoRecurringEntity->copyValues($params);
165 $daoRecurringEntity->find(TRUE);
166 $result = $daoRecurringEntity->save();
168 if (!empty($params['id'])) {
169 CRM_Utils_Hook
::post('edit', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
172 CRM_Utils_Hook
::post('create', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
178 * Wrapper for the function add() to add entry in recurring entity
180 * @param int $parentId
182 * @param int $entityId
184 * @param string $entityTable
185 * Name of the entity table .
190 public static function quickAdd($parentId, $entityId, $entityTable) {
193 'parent_id' => $parentId,
194 'entity_id' => $entityId,
195 'entity_table' => $entityTable,
197 return self
::add($params);
201 * This function updates the mode column in the civicrm_recurring_entity table.
204 * 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.
206 public function mode($mode) {
207 if ($this->entity_id
&& $this->entity_table
) {
208 if ($this->find(TRUE)) {
212 $this->parent_id
= $this->entity_id
;
220 * This function generates all new entities based on object vars.
224 public function generate() {
225 $this->generateRecursiveDates();
227 return $this->generateEntities();
231 * This function builds a "When" object based on schedule/reminder params
236 public function generateRecursion() {
237 // return if already generated
238 if (is_a($this->recursion
, 'When')) {
239 return $this->recursion
;
242 if ($this->scheduleId
) {
244 $this->schedule
= $this->getScheduleParams($this->scheduleId
);
246 elseif (!empty($this->scheduleFormValues
)) {
247 $this->schedule
= $this->mapFormValuesToDB($this->scheduleFormValues
);
250 if (!empty($this->schedule
)) {
251 $this->recursion
= $this->getRecursionFromSchedule($this->schedule
);
253 return $this->recursion
;
257 * Generate new DAOs and along with entries in civicrm_recurring_entity table.
261 public function generateEntities() {
262 self
::setStatus(self
::RUNNING
);
264 $newEntities = array();
265 $findCriteria = array();
266 if (!empty($this->recursionDates
)) {
267 if ($this->entity_id
) {
268 $findCriteria = array('id' => $this->entity_id
);
270 // save an entry with initiating entity-id & entity-table
271 if ($this->entity_table
&& !$this->find(TRUE)) {
272 $this->parent_id
= $this->entity_id
;
276 if (empty($findCriteria)) {
277 CRM_Core_Error
::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
281 foreach ($this->recursionDates
as $key => $dateCols) {
282 $newCriteria = $dateCols;
283 foreach ($this->overwriteColumns
as $col => $val) {
284 $newCriteria[$col] = $val;
286 // create main entities
287 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
290 $this->isRecurringEntityRecord
293 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
294 $newCriteria = array();
295 $newEntities[$this->entity_table
][$count] = $obj->id
;
297 foreach ($this->linkedEntities
as $linkedInfo) {
298 foreach ($linkedInfo['linkedColumns'] as $col) {
299 $newCriteria[$col] = $obj->id
;
301 // create linked entities
302 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
303 $linkedInfo['findCriteria'],
305 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
308 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
309 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
317 self
::$status = NULL;
322 * This function iterates through when object criteria and
323 * generates recursive dates based on that
328 public function generateRecursiveDates() {
329 $this->generateRecursion();
331 $recursionDates = array();
332 if (is_a($this->recursion
, 'When')) {
333 $initialCount = CRM_Utils_Array
::value('start_action_offset', $this->schedule
);
335 $exRangeStart = $exRangeEnd = NULL;
336 if (!empty($this->excludeDateRangeColumns
)) {
337 $exRangeStart = $this->excludeDateRangeColumns
[0];
338 $exRangeEnd = $this->excludeDateRangeColumns
[1];
342 while ($result = $this->recursion
->next()) {
344 if ($result == $this->recursion_start_date
) {
345 // skip the recursion-start-date from the list we going to generate
348 $baseDate = CRM_Utils_Date
::processDate($result->format('Y-m-d H:i:s'));
350 foreach ($this->dateColumns
as $col) {
351 $recursionDates[$count][$col] = $baseDate;
353 foreach ($this->intervalDateColumns
as $col => $interval) {
354 $newDate = new DateTime($baseDate);
355 $newDate->add($interval);
356 $recursionDates[$count][$col] = CRM_Utils_Date
::processDate($newDate->format('Y-m-d H:i:s'));
359 $exRangeStartDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeStart, $recursionDates[$count]), NULL, FALSE, 'Ymd');
360 $exRangeEndDate = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($exRangeEnd, $recursionDates[$count]), NULL, FALSE, 'Ymd');
363 foreach ($this->excludeDates
as $exDate) {
364 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
365 if (!$exRangeStart) {
366 if ($exDate == $result->format('Ymd')) {
372 if (($exDate == $exRangeStartDate) ||
373 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
382 unset($recursionDates[$count]);
383 if ($initialCount && ($initialCount > 0)) {
384 // lets increase the counter, so we get correct number of occurrences
386 $this->recursion
->count($initialCount);
393 $this->recursionDates
= $recursionDates;
395 return $recursionDates;
399 * This function gets all the children for a particular parent entity.
401 * @param int $parentId
403 * @param string $entityTable
404 * Name of the entity table .
405 * @param bool $includeParent
406 * If true parent id is included in result set and vice versa .
408 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
409 * @param int $initiatorId
410 * The instance where this function is invoked from .
414 * an array of child ids
416 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
418 if (empty($parentId) ||
empty($entityTable)) {
423 $initiatorId = $parentId;
426 $queryParams = array(
427 1 => array($parentId, 'Integer'),
428 2 => array($entityTable, 'String'),
429 3 => array($initiatorId, 'Integer'),
433 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
437 FROM civicrm_recurring_entity
438 WHERE parent_id = %1 AND entity_table = %2";
439 if (!$includeParent) {
440 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
445 $query .= " AND entity_id = %3";
448 elseif ($mode == '2') {
449 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
450 if ($recurringEntityID) {
451 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
452 $query .= " ORDER BY id ASC"; // FIXME: change to order by dates
453 $queryParams[4] = array($recurringEntityID, 'Integer');
456 // something wrong, return empty
461 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
462 while ($dao->fetch()) {
463 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
464 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
470 * This function when passed an entity id checks if it has parent and
471 * returns all other entities that are connected to same parent.
473 * @param int $entityId
475 * @param string $entityTable
476 * Entity table name .
477 * @param bool $includeParent
478 * Include parent in result set .
480 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
484 * array of connected ids
486 static public function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
487 $parentId = self
::getParentFor($entityId, $entityTable);
489 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
495 * This function gets the parent for the entity id passed to it.
497 * @param int $entityId
499 * @param string $entityTable
500 * Entity table name .
501 * @param bool $includeParent
502 * Include parent in result set .
506 * unsigned $parentId Parent ID
508 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
509 if (empty($entityId) ||
empty($entityTable)) {
515 FROM civicrm_recurring_entity
516 WHERE entity_id = %1 AND entity_table = %2";
517 if (!$includeParent) {
518 $query .= " AND parent_id != %1";
521 = CRM_Core_DAO
::singleValueQuery($query,
523 1 => array($entityId, 'Integer'),
524 2 => array($entityTable, 'String'),
531 * Finds the position of this entity as well as total count of the repeating set
534 * @param $entityTable
537 static public function getPositionAndCount($entityId, $entityTable) {
538 $position = $count = 0;
542 FROM civicrm_recurring_entity
543 WHERE parent_id = (SELECT parent_id FROM civicrm_recurring_entity WHERE entity_id = %1 AND entity_table = %2) AND entity_table = %2";
545 $dao = CRM_Core_DAO
::executeQuery($query,
547 1 => array($entityId, 'Integer'),
548 2 => array($entityTable, 'String'),
552 while ($dao->fetch()) {
554 if ($dao->entity_id
<= $entityId) {
559 return array($position, $count);
565 * This function copies the information from parent entity and creates other entities with same information.
567 * @param string $entityTable
568 * Entity table name .
569 * @param array $fromCriteria
570 * Array of all the fields & values on which basis to copy .
571 * @param array $newParams
572 * Array of all the fields & values to be copied besides the other fields .
573 * @param bool $createRecurringEntity
574 * If to create a record in recurring_entity table .
579 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
580 $daoName = self
::$_tableDAOMapper[$entityTable];
582 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
584 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
586 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
587 $object = new $daoName();
588 foreach ($fromCriteria as $key => $value) {
589 $object->$key = $value;
593 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
599 * This function acts as a listener to dao->update whenever there is an update.
601 * It propagates any changes to all related entities present in recurring entity table
603 * @param object $event
604 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
606 static public function triggerUpdate($event) {
607 // if DB version is earlier than 4.6 skip any processing
608 static $currentVer = NULL;
610 $currentVer = CRM_Core_BAO_Domain
::version();
612 if (version_compare($currentVer, '4.6.alpha1') < 0) {
616 static $processedEntities = array();
617 $obj =& $event->object;
618 if (empty($obj->id
) ||
empty($obj->__table
)) {
621 $key = "{$obj->__table}_{$obj->id}";
623 if (array_key_exists($key, $processedEntities)) {
628 // get related entities
629 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
630 if (empty($repeatingEntities)) {
631 // return if its not a recurring entity parent
634 // mark being processed
635 $processedEntities[$key] = 1;
637 // to make sure we not copying to source itself
638 unset($repeatingEntities[$key]);
640 foreach ($repeatingEntities as $key => $val) {
641 $entityID = $val['id'];
642 $entityTable = $val['table'];
644 $processedEntities[$key] = 1;
646 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
647 $daoName = self
::$_tableDAOMapper[$entityTable];
650 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
651 $skipFields = self
::$_updateSkipFields[$entityTable];
652 foreach ($skipFields as $sfield) {
653 $skipData[$sfield] = NULL;
657 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
658 CRM_Core_DAO
::freeResult();
661 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
664 // done with processing. lets unset static var.
665 unset($processedEntities);
669 * This function acts as a listener to dao->save,
670 * and creates entries for linked entities in recurring entity table
672 * @param object $event
673 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
675 static public function triggerInsert($event) {
676 $obj =& $event->object;
677 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
681 // if DB version is earlier than 4.6 skip any processing
682 static $currentVer = NULL;
684 $currentVer = CRM_Core_BAO_Domain
::version();
686 if (version_compare($currentVer, '4.6.alpha1') < 0) {
690 static $processedEntities = array();
691 if (empty($obj->id
) ||
empty($obj->__table
)) {
694 $key = "{$obj->__table}_{$obj->id}";
696 if (array_key_exists($key, $processedEntities)) {
697 // already being processed. Exit recursive calls.
701 if (self
::getStatus() == self
::RUNNING
) {
702 // if recursion->generate() is doing some work, lets not intercept
706 // mark being processed
707 $processedEntities[$key] = 1;
709 // get related entities for table being saved
710 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
712 if (empty($hasaRecurringRecord)) {
713 // check if its a linked entity
714 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
715 !CRM_Utils_Array
::value('is_multirecord', self
::$_linkedEntitiesInfo[$obj->__table
])
717 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
718 $linkedDAO->id
= $obj->id
;
719 if ($linkedDAO->find(TRUE)) {
720 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
721 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
723 $pEntityID = $linkedDAO->$idCol;
724 $pEntityTable = $linkedDAO->$tableCol;
726 // find all parent recurring entity set
727 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
729 if (!empty($pRepeatingEntities)) {
730 // for each parent entity in the set, find out a similar linked entity,
731 // if doesn't exist create one, and also create entries in recurring_entity table
733 foreach ($pRepeatingEntities as $key => $val) {
734 if (array_key_exists($key, $processedEntities)) {
735 // this graph is already being processed
738 $processedEntities[$key] = 1;
741 // start with first entry with just itself
742 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
744 foreach ($pRepeatingEntities as $key => $val) {
745 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
746 $rlinkedDAO->$idCol = $val['id'];
747 $rlinkedDAO->$tableCol = $val['table'];
748 if ($rlinkedDAO->find(TRUE)) {
749 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
752 // linked entity doesn't exist. lets create them
753 $newCriteria = array(
754 $idCol => $val['id'],
755 $tableCol => $val['table'],
757 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
758 array('id' => $obj->id
),
762 if ($linkedObj->id
) {
763 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
772 // done with processing. lets unset static var.
773 unset($processedEntities);
777 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
779 * @param object $event
780 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
782 static public function triggerDelete($event) {
783 $obj =& $event->object;
785 // if DB version is earlier than 4.6 skip any processing
786 static $currentVer = NULL;
788 $currentVer = CRM_Core_BAO_Domain
::version();
790 if (version_compare($currentVer, '4.6.alpha1') < 0) {
794 static $processedEntities = array();
795 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
798 $key = "{$obj->__table}_{$obj->id}";
800 if (array_key_exists($key, $processedEntities)) {
805 // mark being processed
806 $processedEntities[$key] = 1;
808 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
810 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
815 * This function deletes main entity and related linked entities from recurring-entity table.
817 * @param int $entityId
819 * @param string $entityTable
820 * Name of the entity table
822 * @param bool $isDelLinkedEntities
824 * @return bool|\CRM_Core_DAO_RecurringEntity
827 static public function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
828 if (empty($entityId) ||
empty($entityTable)) {
831 $dao = new CRM_Core_DAO_RecurringEntity();
832 $dao->entity_id
= $entityId;
833 $dao->entity_table
= $entityTable;
834 if ($dao->find(TRUE)) {
835 // make sure its not a linked entity thats being deleted
836 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
837 // delete all linked entities from recurring entity table
838 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
839 $daoName = self
::$_tableDAOMapper[$linkedTable];
841 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
844 $linkedDao = new $daoName();
845 $linkedDao->$linfo['entity_id_col'] = $entityId;
846 $linkedDao->$linfo['entity_table_col'] = $entityTable;
848 while ($linkedDao->fetch()) {
849 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
853 // delete main entity
854 return $dao->delete();
860 * This function maps values posted from form to civicrm_action_schedule columns.
862 * @param array $formParams
863 * And array of form values posted .
867 public function mapFormValuesToDB($formParams = array()) {
869 if (!empty($formParams['used_for'])) {
870 $dbParams['used_for'] = $formParams['used_for'];
873 if (!empty($formParams['entity_id'])) {
874 $dbParams['entity_value'] = $formParams['entity_id'];
877 if (!empty($formParams['repetition_start_date'])) {
878 if (!empty($formParams['repetition_start_date_display'])) {
879 $repetitionStartDate = $formParams['repetition_start_date_display'];
882 $repetitionStartDate = $formParams['repetition_start_date'];
884 if (!empty($formParams['repetition_start_date_time'])) {
885 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
887 $repetition_start_date = new DateTime($repetitionStartDate);
888 $dbParams['start_action_date'] = CRM_Utils_Date
::processDate($repetition_start_date->format('Y-m-d H:i:s'));
891 if (!empty($formParams['repetition_frequency_unit'])) {
892 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
895 if (!empty($formParams['repetition_frequency_interval'])) {
896 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
899 //For Repeats on:(weekly case)
900 if ($formParams['repetition_frequency_unit'] == 'week') {
901 if (!empty($formParams['start_action_condition'])) {
902 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
903 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
907 //For Repeats By:(monthly case)
908 if ($formParams['repetition_frequency_unit'] == 'month') {
909 if ($formParams['repeats_by'] == 1) {
910 if (!empty($formParams['limit_to'])) {
911 $dbParams['limit_to'] = $formParams['limit_to'];
914 if ($formParams['repeats_by'] == 2) {
915 if (CRM_Utils_Array
::value('entity_status_1', $formParams) && CRM_Utils_Array
::value('entity_status_2', $formParams)) {
916 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
921 //For "Ends" - After:
922 if ($formParams['ends'] == 1) {
923 if (!empty($formParams['start_action_offset'])) {
924 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
929 if ($formParams['ends'] == 2) {
930 if (!empty($formParams['repeat_absolute_date'])) {
931 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
938 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
940 * @param int $scheduleReminderId
941 * Primary key of civicrm_action_schedule table .
946 static public function getScheduleReminderDetailsById($scheduleReminderId) {
948 FROM civicrm_action_schedule WHERE 1";
949 if ($scheduleReminderId) {
953 $dao = CRM_Core_DAO
::executeQuery($query,
955 1 => array($scheduleReminderId, 'Integer'),
963 * wrapper of getScheduleReminderDetailsById function.
965 * @param int $scheduleReminderId
966 * Primary key of civicrm_action_schedule table .
970 public function getScheduleParams($scheduleReminderId) {
971 $scheduleReminderDetails = array();
972 if ($scheduleReminderId) {
973 //Get all the details from schedule reminder table
974 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
975 $scheduleReminderDetails = (array) $scheduleReminderDetails;
977 return $scheduleReminderDetails;
981 * This function takes criteria saved in civicrm_action_schedule table
982 * and creates recursion rule
984 * @param array $scheduleReminderDetails
985 * Array of repeat criteria saved in civicrm_action_schedule table .
990 public function getRecursionFromSchedule($scheduleReminderDetails = array()) {
992 //If there is some data for this id
993 if ($scheduleReminderDetails['repetition_frequency_unit']) {
994 if ($scheduleReminderDetails['start_action_date']) {
995 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
998 $currDate = date("Y-m-d H:i:s");
1000 $start = new DateTime($currDate);
1001 $this->recursion_start_date
= $start;
1002 if ($scheduleReminderDetails['repetition_frequency_unit']) {
1003 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
1004 if ($repetition_frequency_unit == "day") {
1005 $repetition_frequency_unit = "dai";
1007 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
1008 $r->recur($start, $repetition_frequency_unit);
1011 if ($scheduleReminderDetails['repetition_frequency_interval']) {
1012 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
1015 $r->errors
[] = 'Repeats every: is a required field';
1019 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
1020 if ($scheduleReminderDetails['start_action_condition']) {
1021 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
1022 $explodeStartActionCondition = explode(',', $startActionCondition);
1023 $buildRuleArray = array();
1024 foreach ($explodeStartActionCondition as $key => $val) {
1025 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
1027 $r->wkst('MO')->byday($buildRuleArray);
1032 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1033 if ($scheduleReminderDetails['entity_status']) {
1034 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1035 switch ($startActionDate[0]) {
1037 $startActionDate1 = 1;
1041 $startActionDate1 = 2;
1045 $startActionDate1 = 3;
1049 $startActionDate1 = 4;
1053 $startActionDate1 = -1;
1056 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1057 $r->byday(array($concatStartActionDateBits));
1059 elseif ($scheduleReminderDetails['limit_to']) {
1060 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
1065 if ($scheduleReminderDetails['start_action_offset']) {
1066 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1067 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1069 $r->count($scheduleReminderDetails['start_action_offset']);
1072 if (!empty($scheduleReminderDetails['absolute_date'])) {
1073 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1074 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1075 // and we always want the date to be included, and therefore appending 23:59
1076 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
1077 $r->until($endDate);
1080 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1081 $r->errors
[] = 'Ends: is a required field';
1085 $r->errors
[] = 'Repeats: is a required field';
1092 * This function gets time difference between the two datetime object.
1094 * @param DateTime $startDate
1096 * @param DateTime $endDate
1101 * DateTime object which contain time difference
1103 static public function getInterval($startDate, $endDate) {
1104 if ($startDate && $endDate) {
1105 $startDate = new DateTime($startDate);
1106 $endDate = new DateTime($endDate);
1107 return $startDate->diff($endDate);
1112 * This function gets all columns from civicrm_action_schedule on the basis of event id.
1114 * @param int $entityId
1116 * @param string $used_for
1117 * Specifies for which entity type it's used for .
1122 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1126 FROM civicrm_action_schedule
1127 WHERE entity_value = %1";
1129 $query .= " AND used_for = %2";
1132 1 => array($entityId, 'Integer'),
1133 2 => array($used_for, 'String'),
1135 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1142 * Update mode column in civicrm_recurring_entity table for event related tabs.
1144 * @param int $entityId
1146 * @param string $linkedEntityTable
1147 * Linked entity table name for this event .
1148 * @param string $mainEntityTable
1152 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1154 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1155 if (CRM_Utils_Array
::value($linkedEntityTable, self
::$_tableDAOMapper)) {
1156 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1159 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1162 $entityTable = $linkedEntityTable;
1164 'entity_id' => $entityId,
1165 'entity_table' => $mainEntityTable,
1167 $defaults = array();
1168 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1169 if (!empty($defaults['id'])) {
1170 $result['entityId'] = $defaults['id'];
1171 $result['entityTable'] = $entityTable;