3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
36 require_once 'packages/When/When.php';
38 class CRM_Core_BAO_RecurringEntity
extends CRM_Core_DAO_RecurringEntity
{
41 public $schedule = array();
42 public $scheduleId = NULL;
43 public $scheduleFormValues = array();
45 public $dateColumns = array();
46 public $overwriteColumns = array();
47 public $intervalDateColumns = array();
48 public $excludeDates = array();
50 public $linkedEntities = array();
52 public $isRecurringEntityRecord = TRUE;
54 protected $recursion = NULL;
55 protected $recursion_start_date = NULL;
57 public static $_entitiesToBeDeleted = array();
59 public static $status = NULL;
61 static $_recurringEntityHelper =
63 'civicrm_event' => array(
64 'helper_class' => 'CRM_Event_DAO_Event',
65 'delete_func' => 'delete',
66 'pre_delete_func' => 'CRM_Event_Form_ManageEvent_Repeat::checkRegistrationForEvents'
68 'civicrm_activity' => array(
69 'helper_class' => 'CRM_Activity_DAO_Activity',
70 'delete_func' => 'delete',
71 'pre_delete_func' => ''
75 static $_dateColumns =
77 'civicrm_event' => array(
78 'dateColumns' => array('start_date'),
79 'excludeDateRangeColumns' => array('start_date', 'end_date'),
80 'intervalDateColumns' => array('end_date')
82 'civicrm_activity' => array(
83 'dateColumns' => array('activity_date_time'),
87 static $_tableDAOMapper =
89 'civicrm_event' => 'CRM_Event_DAO_Event',
90 'civicrm_price_set_entity' => 'CRM_Price_DAO_PriceSetEntity',
91 'civicrm_uf_join' => 'CRM_Core_DAO_UFJoin',
92 'civicrm_tell_friend' => 'CRM_Friend_DAO_Friend',
93 'civicrm_pcp_block' => 'CRM_PCP_DAO_PCPBlock',
94 'civicrm_activity' => 'CRM_Activity_DAO_Activity',
95 'civicrm_activity_contact' => 'CRM_Activity_DAO_ActivityContact',
98 static $_updateSkipFields =
100 'civicrm_event' => array('start_date', 'end_date'),
101 'civicrm_tell_friend' => array('entity_id'),
102 'civicrm_pcp_block' => array('entity_id'),
103 'civicrm_activity' => array('activity_date_time'),
106 static $_linkedEntitiesInfo =
108 'civicrm_tell_friend' => array(
109 'entity_id_col' => 'entity_id',
110 'entity_table_col' => 'entity_table'
112 'civicrm_price_set_entity' => array(
113 'entity_id_col' => 'entity_id',
114 'entity_table_col' => 'entity_table',
115 'is_multirecord' => TRUE,
117 'civicrm_uf_join' => array(
118 'entity_id_col' => 'entity_id',
119 'entity_table_col' => 'entity_table',
120 'is_multirecord' => TRUE,
122 'civicrm_pcp_block' => array(
123 'entity_id_col' => 'entity_id',
124 'entity_table_col' => 'entity_table'
128 public static function getStatus() {
129 return self
::$status;
132 public static function setStatus($status) {
133 self
::$status = $status;
136 * Save records in civicrm_recujrring_entity table
138 * @param array $params
139 * Reference array contains the values submitted by the form .
145 public static function add(&$params) {
146 if (CRM_Utils_Array
::value('id', $params)) {
147 CRM_Utils_Hook
::pre('edit', 'RecurringEntity', $params['id'], $params);
150 CRM_Utils_Hook
::pre('create', 'RecurringEntity', NULL, $params);
153 $daoRecurringEntity = new CRM_Core_DAO_RecurringEntity();
154 $daoRecurringEntity->copyValues($params);
155 $daoRecurringEntity->find(TRUE);
156 $result = $daoRecurringEntity->save();
158 if (CRM_Utils_Array
::value('id', $params)) {
159 CRM_Utils_Hook
::post('edit', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
162 CRM_Utils_Hook
::post('create', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
168 * Wrapper for the function add() to add entry in recurring entity
170 * @param int $parentId
172 * @param int $entityId
174 * @param string $entityTable
175 * Name of the entity table .
181 public static function quickAdd($parentId, $entityId, $entityTable) {
184 'parent_id' => $parentId,
185 'entity_id' => $entityId,
186 'entity_table' => $entityTable
188 return self
::add($params);
192 * This function updates the mode column in the civicrm_recurring_entity table
195 * 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 .
200 public function mode($mode) {
201 if ($this->entity_id
&& $this->entity_table
) {
202 if ($this->find(TRUE)) {
206 $this->parent_id
= $this->entity_id
;
214 * This function generates all new entities based on object vars
218 public function generate() {
219 $this->generateRecursiveDates();
221 return $this->generateEntities();
225 * This function builds a "When" object based on schedule/reminder params
230 public function generateRecursion() {
231 // return if already generated
232 if (is_a($this->recursion
, 'When')) {
233 return $this->recursion
;
236 if ($this->scheduleId
) {
238 $this->schedule
= $this->getScheduleParams($this->scheduleId
);
240 elseif (!empty($this->scheduleFormValues
)) {
241 $this->schedule
= $this->mapFormValuesToDB($this->scheduleFormValues
);
244 if (!empty($this->schedule
)) {
245 $this->recursion
= $this->getRecursionFromSchedule($this->schedule
);
247 return $this->recursion
;
251 * Generate new DAOs and along with entries in civicrm_recurring_entity table
255 public function generateEntities() {
256 self
::setStatus(self
::RUNNING
);
258 $newEntities = array();
259 $findCriteria = array();
260 if (!empty($this->recursionDates
)) {
261 if ($this->entity_id
) {
262 $findCriteria = array('id' => $this->entity_id
);
264 // save an entry with initiating entity-id & entity-table
265 if ($this->entity_table
&& !$this->find(TRUE)) {
266 $this->parent_id
= $this->entity_id
;
270 if (empty($findCriteria)) {
271 CRM_Core_Error
::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
275 foreach ($this->recursionDates
as $key => $dateCols) {
276 $newCriteria = $dateCols;
277 foreach ($this->overwriteColumns
as $col => $val) {
278 $newCriteria[$col] = $val;
280 // create main entities
281 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
284 $this->isRecurringEntityRecord
287 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
288 $newCriteria = array();
289 $newEntities[$this->entity_table
][$count] = $obj->id
;
291 foreach ($this->linkedEntities
as $linkedInfo) {
292 foreach ($linkedInfo['linkedColumns'] as $col) {
293 $newCriteria[$col] = $obj->id
;
295 // create linked entities
296 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
297 $linkedInfo['findCriteria'],
299 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
302 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
303 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
311 self
::$status = NULL;
316 * This function iterates through when object criterias and
317 * generates recursive dates based on that
322 public function generateRecursiveDates() {
323 $this->generateRecursion();
325 $recursionDates = array();
326 if (is_a($this->recursion
, 'When')) {
327 $initialCount = CRM_Utils_Array
::value('start_action_offset', $this->schedule
);
329 $exRangeStart = $exRangeEnd = NULL;
330 if (!empty($this->excludeDateRangeColumns
)) {
331 $exRangeStart = $this->excludeDateRangeColumns
[0];
332 $exRangeEnd = $this->excludeDateRangeColumns
[1];
336 while ($result = $this->recursion
->next()) {
338 if ($result == $this->recursion_start_date
) {
339 // skip the recursion-start-date from the list we going to generate
342 $baseDate = CRM_Utils_Date
::processDate($result->format('Y-m-d H:i:s'));
344 foreach ($this->dateColumns
as $col) {
345 $recursionDates[$count][$col] = $baseDate;
347 foreach ($this->intervalDateColumns
as $col => $interval) {
348 $newDate = new DateTime($baseDate);
349 $newDate->add($interval);
350 $recursionDates[$count][$col] = CRM_Utils_Date
::processDate($newDate->format('Y-m-d H:i:s'));
353 $exRangeStartDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeStart], NULL, FALSE, 'Ymd');
354 $exRangeEndDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeEnd], NULL, FALSE, 'Ymd');
357 foreach ($this->excludeDates
as $exDate) {
358 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
359 if (!$exRangeStart) {
360 if ($exDate == $result->format('Ymd')) {
366 if (($exDate == $exRangeStartDate) ||
367 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
376 unset($recursionDates[$count]);
377 if ($initialCount && ($initialCount > 0)) {
378 // lets increase the counter, so we get correct number of occurrences
380 $this->recursion
->count($initialCount);
387 $this->recursionDates
= $recursionDates;
389 return $recursionDates;
393 * This function gets all the children for a particular parent entity
395 * @param int $parentId
397 * @param string $entityTable
398 * Name of the entity table .
399 * @param bool $includeParent
400 * If true parent id is included in result set and vice versa .
402 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
403 * @param int $initiatorId
404 * The instance where this function is invoked from .
409 * an array of child ids
411 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
413 if (empty($parentId) ||
empty($entityTable)) {
418 $initiatorId = $parentId;
421 $queryParams = array(
422 1 => array($parentId, 'Integer'),
423 2 => array($entityTable, 'String'),
424 3 => array($initiatorId, 'Integer'),
428 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
432 FROM civicrm_recurring_entity
433 WHERE parent_id = %1 AND entity_table = %2";
434 if (!$includeParent) {
435 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
438 if ($mode == '1') { // MODE = SINGLE
439 $query .= " AND entity_id = %3";
441 elseif ($mode == '2') { // MODE = FUTURE
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 $query .= " ORDER BY id ASC"; // FIXME: change to order by dates
446 $queryParams[4] = array($recurringEntityID, 'Integer');
449 // something wrong, return empty
454 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
455 while ($dao->fetch()) {
456 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
457 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
463 * This function when passed an entity id checks if it has parent and
464 * returns all other entities that are connected to same parent.
466 * @param int $entityId
468 * @param string $entityTable
469 * Entity table name .
470 * @param bool $includeParent
471 * Include parent in result set .
473 * 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 static public 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 .
501 * unsigned $parentId Parent ID
503 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
504 if (empty($entityId) ||
empty($entityTable)) {
510 FROM civicrm_recurring_entity
511 WHERE entity_id = %1 AND entity_table = %2";
512 if (!$includeParent) {
513 $query .= " AND parent_id != %1";
516 CRM_Core_DAO
::singleValueQuery($query,
518 1 => array($entityId, 'Integer'),
519 2 => array($entityTable, 'String'),
526 * This function copies the information from parent entity and creates other entities with same information
528 * @param string $entityTable
529 * Entity table name .
530 * @param array $fromCriteria
531 * Array of all the fields & values on which basis to copy .
532 * @param array $newParams
533 * Array of all the fields & values to be copied besides the other fields .
534 * @param bool $createRecurringEntity
535 * If to create a record in recurring_entity table .
541 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
542 $daoName = self
::$_tableDAOMapper[$entityTable];
544 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
546 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
548 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
549 $object = new $daoName( );
550 foreach ($fromCriteria as $key => $value) {
551 $object->$key = $value;
555 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
561 * This function acts as a listener to dao->update whenever there is an update,
562 * and propagates any changes to all related entities present in recurring entity table
564 * @param object $event
565 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated .
571 static public function triggerUpdate($event) {
572 // if DB version is earlier than 4.6 skip any processing
573 static $currentVer = NULL;
575 $currentVer = CRM_Core_BAO_Domain
::version();
577 if (version_compare($currentVer, '4.6.alpha1') < 0) {
581 static $processedEntities = array();
582 $obj =& $event->object;
583 if (empty($obj->id
) ||
empty($obj->__table
)) {
586 $key = "{$obj->__table}_{$obj->id}";
588 if (array_key_exists($key, $processedEntities)) {
593 // get related entities
594 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
595 if (empty($repeatingEntities)) {
596 // return if its not a recurring entity parent
599 // mark being processed
600 $processedEntities[$key] = 1;
602 // to make sure we not copying to source itself
603 unset($repeatingEntities[$key]);
605 foreach ($repeatingEntities as $key => $val) {
606 $entityID = $val['id'];
607 $entityTable = $val['table'];
609 $processedEntities[$key] = 1;
611 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
612 $daoName = self
::$_tableDAOMapper[$entityTable];
615 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
616 $skipFields = self
::$_updateSkipFields[$entityTable];
617 foreach ($skipFields as $sfield) {
618 $skipData[$sfield] = NULL;
622 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
623 CRM_Core_DAO
::freeResult();
626 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
629 // done with processing. lets unset static var.
630 unset($processedEntities);
634 * This function acts as a listener to dao->save,
635 * and creates entries for linked entities in recurring entity table
637 * @param object $event
638 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted .
644 static public function triggerInsert($event) {
645 $obj =& $event->object;
646 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
650 // if DB version is earlier than 4.6 skip any processing
651 static $currentVer = NULL;
653 $currentVer = CRM_Core_BAO_Domain
::version();
655 if (version_compare($currentVer, '4.6.alpha1') < 0) {
659 static $processedEntities = array();
660 if (empty($obj->id
) ||
empty($obj->__table
)) {
663 $key = "{$obj->__table}_{$obj->id}";
665 if (array_key_exists($key, $processedEntities)) {
666 // already being processed. Exit recursive calls.
670 if (self
::getStatus() == self
::RUNNING
) {
671 // if recursion->generate() is doing some work, lets not intercept
675 // mark being processed
676 $processedEntities[$key] = 1;
678 // get related entities for table being saved
679 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
681 if (empty($hasaRecurringRecord)) {
682 // check if its a linked entity
683 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
684 !CRM_Utils_Array
::value('is_multirecord', self
::$_linkedEntitiesInfo[$obj->__table
])) {
685 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
686 $linkedDAO->id
= $obj->id
;
687 if ($linkedDAO->find(TRUE)) {
688 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
689 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
691 $pEntityID = $linkedDAO->$idCol;
692 $pEntityTable = $linkedDAO->$tableCol;
694 // find all parent recurring entity set
695 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
697 if (!empty($pRepeatingEntities)) {
698 // for each parent entity in the set, find out a similar linked entity,
699 // if doesn't exist create one, and also create entries in recurring_entity table
701 foreach ($pRepeatingEntities as $key => $val) {
702 if (array_key_exists($key, $processedEntities)) {
703 // this graph is already being processed
706 $processedEntities[$key] = 1;
709 // start with first entry with just itself
710 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
712 foreach ($pRepeatingEntities as $key => $val) {
713 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
714 $rlinkedDAO->$idCol = $val['id'];
715 $rlinkedDAO->$tableCol = $val['table'];
716 if ($rlinkedDAO->find(TRUE)) {
717 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
720 // linked entity doesn't exist. lets create them
721 $newCriteria = array(
722 $idCol => $val['id'],
723 $tableCol => $val['table']
725 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
726 array('id' => $obj->id
),
730 if ($linkedObj->id
) {
731 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
740 // done with processing. lets unset static var.
741 unset($processedEntities);
745 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
747 * @param object $event
748 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted .
754 static public function triggerDelete($event) {
755 $obj =& $event->object;
757 // if DB version is earlier than 4.6 skip any processing
758 static $currentVer = NULL;
760 $currentVer = CRM_Core_BAO_Domain
::version();
762 if (version_compare($currentVer, '4.6.alpha1') < 0) {
766 static $processedEntities = array();
767 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
770 $key = "{$obj->__table}_{$obj->id}";
772 if (array_key_exists($key, $processedEntities)) {
777 // mark being processed
778 $processedEntities[$key] = 1;
780 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
782 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
787 * This function deletes main entity and related linked entities from recurring-entity table
789 * @param int $entityId
791 * @param string $entityTable
792 * Name of the entity table .
796 * @return boolean|object Returns either boolean value or CRM_Core_DAO_RecurringEntity object
798 static public function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
799 if (empty($entityId) ||
empty($entityTable)) {
802 $dao = new CRM_Core_DAO_RecurringEntity();
803 $dao->entity_id
= $entityId;
804 $dao->entity_table
= $entityTable;
805 if ($dao->find(TRUE)) {
806 // make sure its not a linked entity thats being deleted
807 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
808 // delete all linked entities from recurring entity table
809 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
810 $daoName = self
::$_tableDAOMapper[$linkedTable];
812 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
815 $linkedDao = new $daoName();
816 $linkedDao->$linfo['entity_id_col'] = $entityId;
817 $linkedDao->$linfo['entity_table_col'] = $entityTable;
819 while ($linkedDao->fetch()) {
820 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
824 // delete main entity
825 return $dao->delete();
831 * This function maps values posted from form to civicrm_action_schedule columns
833 * @param array $formParams
834 * And array of form values posted .
838 public function mapFormValuesToDB($formParams = array()) {
840 if (CRM_Utils_Array
::value('used_for', $formParams)) {
841 $dbParams['used_for'] = $formParams['used_for'];
844 if (CRM_Utils_Array
::value('entity_id', $formParams)) {
845 $dbParams['entity_value'] = $formParams['entity_id'];
848 if (CRM_Utils_Array
::value('repetition_start_date', $formParams)) {
849 if (CRM_Utils_Array
::value('repetition_start_date_display', $formParams)) {
850 $repetitionStartDate = $formParams['repetition_start_date_display'];
853 $repetitionStartDate = $formParams['repetition_start_date'];
855 if (CRM_Utils_Array
::value('repetition_start_date_time', $formParams)) {
856 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
858 $repetition_start_date = new DateTime($repetitionStartDate);
859 $dbParams['start_action_date'] = CRM_Utils_Date
::processDate($repetition_start_date->format('Y-m-d H:i:s'));
862 if (CRM_Utils_Array
::value('repetition_frequency_unit', $formParams)) {
863 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
866 if (CRM_Utils_Array
::value('repetition_frequency_interval', $formParams)) {
867 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
870 //For Repeats on:(weekly case)
871 if ($formParams['repetition_frequency_unit'] == 'week') {
872 if (CRM_Utils_Array
::value('start_action_condition', $formParams)) {
873 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
874 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
878 //For Repeats By:(monthly case)
879 if ($formParams['repetition_frequency_unit'] == 'month') {
880 if ($formParams['repeats_by'] == 1) {
881 if (CRM_Utils_Array
::value('limit_to', $formParams)) {
882 $dbParams['limit_to'] = $formParams['limit_to'];
885 if ($formParams['repeats_by'] == 2) {
886 if (CRM_Utils_Array
::value('entity_status_1', $formParams) && CRM_Utils_Array
::value('entity_status_2', $formParams)) {
887 $dbParams['entity_status'] = $formParams['entity_status_1']." ".$formParams['entity_status_2'];
892 //For "Ends" - After:
893 if ($formParams['ends'] == 1) {
894 if (CRM_Utils_Array
::value('start_action_offset', $formParams)) {
895 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
900 if ($formParams['ends'] == 2) {
901 if (CRM_Utils_Array
::value('repeat_absolute_date', $formParams)) {
902 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
909 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
911 * @param int $scheduleReminderId
912 * Primary key of civicrm_action_schedule table .
918 static public function getScheduleReminderDetailsById($scheduleReminderId) {
920 FROM civicrm_action_schedule WHERE 1";
921 if ($scheduleReminderId) {
925 $dao = CRM_Core_DAO
::executeQuery($query,
927 1 => array($scheduleReminderId, 'Integer')
935 * wrapper of getScheduleReminderDetailsById function
937 * @param int $scheduleReminderId
938 * Primary key of civicrm_action_schedule table .
942 public function getScheduleParams($scheduleReminderId) {
943 $scheduleReminderDetails = array();
944 if ($scheduleReminderId) {
945 //Get all the details from schedule reminder table
946 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
947 $scheduleReminderDetails = (array) $scheduleReminderDetails;
949 return $scheduleReminderDetails;
953 * This function takes criterias saved in civicrm_action_schedule table
954 * and creates recursion rule
956 * @param array $scheduleReminderDetails
957 * Array of repeat criterias saved in civicrm_action_schedule table .
962 public function getRecursionFromSchedule($scheduleReminderDetails = array()) {
964 //If there is some data for this id
965 if ($scheduleReminderDetails['repetition_frequency_unit']) {
966 if ($scheduleReminderDetails['start_action_date']) {
967 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
970 $currDate = date("Y-m-d H:i:s");
972 $start = new DateTime($currDate);
973 $this->recursion_start_date
= $start;
974 if ($scheduleReminderDetails['repetition_frequency_unit']) {
975 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
976 if ($repetition_frequency_unit == "day") {
977 $repetition_frequency_unit = "dai";
979 $repetition_frequency_unit = $repetition_frequency_unit.'ly';
980 $r->recur($start, $repetition_frequency_unit);
983 if ($scheduleReminderDetails['repetition_frequency_interval']) {
984 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
987 $r->errors
[] = 'Repeats every: is a required field';
991 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
992 if ($scheduleReminderDetails['start_action_condition']) {
993 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
994 $explodeStartActionCondition = explode(',', $startActionCondition);
995 $buildRuleArray = array();
996 foreach ($explodeStartActionCondition as $key => $val) {
997 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
999 $r->wkst('MO')->byday($buildRuleArray);
1004 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1005 if ($scheduleReminderDetails['entity_status']) {
1006 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1007 switch ($startActionDate[0]) {
1009 $startActionDate1 = 1;
1013 $startActionDate1 = 2;
1017 $startActionDate1 = 3;
1021 $startActionDate1 = 4;
1025 $startActionDate1 = -1;
1028 $concatStartActionDateBits = $startActionDate1.strtoupper(substr($startActionDate[1], 0, 2));
1029 $r->byday(array($concatStartActionDateBits));
1031 elseif ($scheduleReminderDetails['limit_to']) {
1032 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
1037 if ($scheduleReminderDetails['start_action_offset']) {
1038 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1039 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1041 $r->count($scheduleReminderDetails['start_action_offset']);
1044 if (CRM_Utils_Array
::value('absolute_date', $scheduleReminderDetails)) {
1045 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1046 $endDate = new DateTime($absoluteDate[0].' '.$absoluteDate[1]);
1047 $endDate->modify('+1 day');
1048 $r->until($endDate);
1051 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1052 $r->errors
[] = 'Ends: is a required field';
1056 $r->errors
[] = 'Repeats: is a required field';
1063 * This function gets time difference between the two datetime object
1065 * @param DateTime $startDate
1067 * @param DateTime $endDate
1073 * DateTime object which contain time difference
1075 static public function getInterval($startDate, $endDate) {
1076 if ($startDate && $endDate) {
1077 $startDate = new DateTime($startDate);
1078 $endDate = new DateTime($endDate);
1079 return $startDate->diff($endDate);
1084 * This function gets all columns from civicrm_action_schedule on the basis of event id
1086 * @param int $entityId
1088 * @param string $used_for
1089 * Specifies for which entity type it's used for .
1095 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1099 FROM civicrm_action_schedule
1100 WHERE entity_value = %1";
1102 $query .= " AND used_for = %2";
1105 1 => array($entityId, 'Integer'),
1106 2 => array($used_for, 'String')
1108 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1115 * Update mode column in civicrm_recurring_entity table for event related tabs
1117 * @param int $entityId
1119 * @param string $linkedEntityTable
1120 * Linked entity table name for this event .
1123 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1125 if ( $entityId && $linkedEntityTable && $mainEntityTable ) {
1126 if (CRM_Utils_Array
::value($linkedEntityTable, self
::$_tableDAOMapper)) {
1127 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1130 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1133 $entityTable = $linkedEntityTable;
1135 'entity_id' => $entityId,
1136 'entity_table' => $mainEntityTable
1138 $defaults = array();
1139 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1140 if (CRM_Utils_Array
::value('id', $defaults)) {
1141 $result['entityId'] = $defaults['id'];
1142 $result['entityTable'] = $entityTable;