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' => '',
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;
137 * Save records in civicrm_recujrring_entity table
139 * @param array $params
140 * 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 .
180 public static function quickAdd($parentId, $entityId, $entityTable) {
183 'parent_id' => $parentId,
184 'entity_id' => $entityId,
185 'entity_table' => $entityTable,
187 return self
::add($params);
191 * This function updates the mode column in the civicrm_recurring_entity table
194 * 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 .
199 public function mode($mode) {
200 if ($this->entity_id
&& $this->entity_table
) {
201 if ($this->find(TRUE)) {
205 $this->parent_id
= $this->entity_id
;
213 * This function generates all new entities based on object vars
217 public function generate() {
218 $this->generateRecursiveDates();
220 return $this->generateEntities();
224 * This function builds a "When" object based on schedule/reminder params
229 public function generateRecursion() {
230 // return if already generated
231 if (is_a($this->recursion
, 'When')) {
232 return $this->recursion
;
235 if ($this->scheduleId
) {
237 $this->schedule
= $this->getScheduleParams($this->scheduleId
);
239 elseif (!empty($this->scheduleFormValues
)) {
240 $this->schedule
= $this->mapFormValuesToDB($this->scheduleFormValues
);
243 if (!empty($this->schedule
)) {
244 $this->recursion
= $this->getRecursionFromSchedule($this->schedule
);
246 return $this->recursion
;
250 * Generate new DAOs and along with entries in civicrm_recurring_entity table
254 public function generateEntities() {
255 self
::setStatus(self
::RUNNING
);
257 $newEntities = array();
258 $findCriteria = array();
259 if (!empty($this->recursionDates
)) {
260 if ($this->entity_id
) {
261 $findCriteria = array('id' => $this->entity_id
);
263 // save an entry with initiating entity-id & entity-table
264 if ($this->entity_table
&& !$this->find(TRUE)) {
265 $this->parent_id
= $this->entity_id
;
269 if (empty($findCriteria)) {
270 CRM_Core_Error
::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
274 foreach ($this->recursionDates
as $key => $dateCols) {
275 $newCriteria = $dateCols;
276 foreach ($this->overwriteColumns
as $col => $val) {
277 $newCriteria[$col] = $val;
279 // create main entities
280 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
283 $this->isRecurringEntityRecord
286 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
287 $newCriteria = array();
288 $newEntities[$this->entity_table
][$count] = $obj->id
;
290 foreach ($this->linkedEntities
as $linkedInfo) {
291 foreach ($linkedInfo['linkedColumns'] as $col) {
292 $newCriteria[$col] = $obj->id
;
294 // create linked entities
295 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
296 $linkedInfo['findCriteria'],
298 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
301 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
302 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
310 self
::$status = NULL;
315 * This function iterates through when object criterias and
316 * generates recursive dates based on that
321 public function generateRecursiveDates() {
322 $this->generateRecursion();
324 $recursionDates = array();
325 if (is_a($this->recursion
, 'When')) {
326 $initialCount = CRM_Utils_Array
::value('start_action_offset', $this->schedule
);
328 $exRangeStart = $exRangeEnd = NULL;
329 if (!empty($this->excludeDateRangeColumns
)) {
330 $exRangeStart = $this->excludeDateRangeColumns
[0];
331 $exRangeEnd = $this->excludeDateRangeColumns
[1];
335 while ($result = $this->recursion
->next()) {
337 if ($result == $this->recursion_start_date
) {
338 // skip the recursion-start-date from the list we going to generate
341 $baseDate = CRM_Utils_Date
::processDate($result->format('Y-m-d H:i:s'));
343 foreach ($this->dateColumns
as $col) {
344 $recursionDates[$count][$col] = $baseDate;
346 foreach ($this->intervalDateColumns
as $col => $interval) {
347 $newDate = new DateTime($baseDate);
348 $newDate->add($interval);
349 $recursionDates[$count][$col] = CRM_Utils_Date
::processDate($newDate->format('Y-m-d H:i:s'));
352 $exRangeStartDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeStart], NULL, FALSE, 'Ymd');
353 $exRangeEndDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeEnd], NULL, FALSE, 'Ymd');
356 foreach ($this->excludeDates
as $exDate) {
357 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
358 if (!$exRangeStart) {
359 if ($exDate == $result->format('Ymd')) {
365 if (($exDate == $exRangeStartDate) ||
366 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
375 unset($recursionDates[$count]);
376 if ($initialCount && ($initialCount > 0)) {
377 // lets increase the counter, so we get correct number of occurrences
379 $this->recursion
->count($initialCount);
386 $this->recursionDates
= $recursionDates;
388 return $recursionDates;
392 * This function gets all the children for a particular parent entity
394 * @param int $parentId
396 * @param string $entityTable
397 * Name of the entity table .
398 * @param bool $includeParent
399 * If true parent id is included in result set and vice versa .
401 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
402 * @param int $initiatorId
403 * The instance where this function is invoked from .
407 * an array of child ids
409 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
411 if (empty($parentId) ||
empty($entityTable)) {
416 $initiatorId = $parentId;
419 $queryParams = array(
420 1 => array($parentId, 'Integer'),
421 2 => array($entityTable, 'String'),
422 3 => array($initiatorId, 'Integer'),
426 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
430 FROM civicrm_recurring_entity
431 WHERE parent_id = %1 AND entity_table = %2";
432 if (!$includeParent) {
433 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
438 $query .= " AND entity_id = %3";
441 elseif ($mode == '2') {
442 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
443 if ($recurringEntityID) {
444 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
445 $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. .
477 * array of connected ids
479 static public function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
480 $parentId = self
::getParentFor($entityId, $entityTable);
482 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
488 * This function gets the parent for the entity id passed to it
490 * @param int $entityId
492 * @param string $entityTable
493 * Entity table name .
494 * @param bool $includeParent
495 * Include parent in result set .
499 * unsigned $parentId Parent ID
501 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
502 if (empty($entityId) ||
empty($entityTable)) {
508 FROM civicrm_recurring_entity
509 WHERE entity_id = %1 AND entity_table = %2";
510 if (!$includeParent) {
511 $query .= " AND parent_id != %1";
514 = CRM_Core_DAO
::singleValueQuery($query,
516 1 => array($entityId, 'Integer'),
517 2 => array($entityTable, 'String'),
524 * This function copies the information from parent entity and creates other entities with same information
526 * @param string $entityTable
527 * Entity table name .
528 * @param array $fromCriteria
529 * Array of all the fields & values on which basis to copy .
530 * @param array $newParams
531 * Array of all the fields & values to be copied besides the other fields .
532 * @param bool $createRecurringEntity
533 * If to create a record in recurring_entity table .
538 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
539 $daoName = self
::$_tableDAOMapper[$entityTable];
541 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
543 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
545 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
546 $object = new $daoName();
547 foreach ($fromCriteria as $key => $value) {
548 $object->$key = $value;
552 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
558 * This function acts as a listener to dao->update whenever there is an update,
559 * and propagates any changes to all related entities present in recurring entity table
561 * @param object $event
562 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated .
567 static public function triggerUpdate($event) {
568 // if DB version is earlier than 4.6 skip any processing
569 static $currentVer = NULL;
571 $currentVer = CRM_Core_BAO_Domain
::version();
573 if (version_compare($currentVer, '4.6.alpha1') < 0) {
577 static $processedEntities = array();
578 $obj =& $event->object;
579 if (empty($obj->id
) ||
empty($obj->__table
)) {
582 $key = "{$obj->__table}_{$obj->id}";
584 if (array_key_exists($key, $processedEntities)) {
589 // get related entities
590 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
591 if (empty($repeatingEntities)) {
592 // return if its not a recurring entity parent
595 // mark being processed
596 $processedEntities[$key] = 1;
598 // to make sure we not copying to source itself
599 unset($repeatingEntities[$key]);
601 foreach ($repeatingEntities as $key => $val) {
602 $entityID = $val['id'];
603 $entityTable = $val['table'];
605 $processedEntities[$key] = 1;
607 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
608 $daoName = self
::$_tableDAOMapper[$entityTable];
611 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
612 $skipFields = self
::$_updateSkipFields[$entityTable];
613 foreach ($skipFields as $sfield) {
614 $skipData[$sfield] = NULL;
618 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
619 CRM_Core_DAO
::freeResult();
622 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
625 // done with processing. lets unset static var.
626 unset($processedEntities);
630 * This function acts as a listener to dao->save,
631 * and creates entries for linked entities in recurring entity table
633 * @param object $event
634 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted .
639 static public function triggerInsert($event) {
640 $obj =& $event->object;
641 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
645 // if DB version is earlier than 4.6 skip any processing
646 static $currentVer = NULL;
648 $currentVer = CRM_Core_BAO_Domain
::version();
650 if (version_compare($currentVer, '4.6.alpha1') < 0) {
654 static $processedEntities = array();
655 if (empty($obj->id
) ||
empty($obj->__table
)) {
658 $key = "{$obj->__table}_{$obj->id}";
660 if (array_key_exists($key, $processedEntities)) {
661 // already being processed. Exit recursive calls.
665 if (self
::getStatus() == self
::RUNNING
) {
666 // if recursion->generate() is doing some work, lets not intercept
670 // mark being processed
671 $processedEntities[$key] = 1;
673 // get related entities for table being saved
674 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
676 if (empty($hasaRecurringRecord)) {
677 // check if its a linked entity
678 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
679 !CRM_Utils_Array
::value('is_multirecord', self
::$_linkedEntitiesInfo[$obj->__table
])
681 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
682 $linkedDAO->id
= $obj->id
;
683 if ($linkedDAO->find(TRUE)) {
684 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
685 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
687 $pEntityID = $linkedDAO->$idCol;
688 $pEntityTable = $linkedDAO->$tableCol;
690 // find all parent recurring entity set
691 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
693 if (!empty($pRepeatingEntities)) {
694 // for each parent entity in the set, find out a similar linked entity,
695 // if doesn't exist create one, and also create entries in recurring_entity table
697 foreach ($pRepeatingEntities as $key => $val) {
698 if (array_key_exists($key, $processedEntities)) {
699 // this graph is already being processed
702 $processedEntities[$key] = 1;
705 // start with first entry with just itself
706 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
708 foreach ($pRepeatingEntities as $key => $val) {
709 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
710 $rlinkedDAO->$idCol = $val['id'];
711 $rlinkedDAO->$tableCol = $val['table'];
712 if ($rlinkedDAO->find(TRUE)) {
713 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
716 // linked entity doesn't exist. lets create them
717 $newCriteria = array(
718 $idCol => $val['id'],
719 $tableCol => $val['table'],
721 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
722 array('id' => $obj->id
),
726 if ($linkedObj->id
) {
727 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
736 // done with processing. lets unset static var.
737 unset($processedEntities);
741 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
743 * @param object $event
744 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted .
749 static public function triggerDelete($event) {
750 $obj =& $event->object;
752 // if DB version is earlier than 4.6 skip any processing
753 static $currentVer = NULL;
755 $currentVer = CRM_Core_BAO_Domain
::version();
757 if (version_compare($currentVer, '4.6.alpha1') < 0) {
761 static $processedEntities = array();
762 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
765 $key = "{$obj->__table}_{$obj->id}";
767 if (array_key_exists($key, $processedEntities)) {
772 // mark being processed
773 $processedEntities[$key] = 1;
775 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
777 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
782 * This function deletes main entity and related linked entities from recurring-entity table
784 * @param int $entityId
786 * @param string $entityTable
787 * Name of the entity table
790 * @return bool|CRM_Core_DAO_RecurringEntity
792 static public function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
793 if (empty($entityId) ||
empty($entityTable)) {
796 $dao = new CRM_Core_DAO_RecurringEntity();
797 $dao->entity_id
= $entityId;
798 $dao->entity_table
= $entityTable;
799 if ($dao->find(TRUE)) {
800 // make sure its not a linked entity thats being deleted
801 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
802 // delete all linked entities from recurring entity table
803 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
804 $daoName = self
::$_tableDAOMapper[$linkedTable];
806 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
809 $linkedDao = new $daoName();
810 $linkedDao->$linfo['entity_id_col'] = $entityId;
811 $linkedDao->$linfo['entity_table_col'] = $entityTable;
813 while ($linkedDao->fetch()) {
814 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
818 // delete main entity
819 return $dao->delete();
825 * This function maps values posted from form to civicrm_action_schedule columns
827 * @param array $formParams
828 * And array of form values posted .
832 public function mapFormValuesToDB($formParams = array()) {
834 if (CRM_Utils_Array
::value('used_for', $formParams)) {
835 $dbParams['used_for'] = $formParams['used_for'];
838 if (CRM_Utils_Array
::value('entity_id', $formParams)) {
839 $dbParams['entity_value'] = $formParams['entity_id'];
842 if (CRM_Utils_Array
::value('repetition_start_date', $formParams)) {
843 if (CRM_Utils_Array
::value('repetition_start_date_display', $formParams)) {
844 $repetitionStartDate = $formParams['repetition_start_date_display'];
847 $repetitionStartDate = $formParams['repetition_start_date'];
849 if (CRM_Utils_Array
::value('repetition_start_date_time', $formParams)) {
850 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
852 $repetition_start_date = new DateTime($repetitionStartDate);
853 $dbParams['start_action_date'] = CRM_Utils_Date
::processDate($repetition_start_date->format('Y-m-d H:i:s'));
856 if (CRM_Utils_Array
::value('repetition_frequency_unit', $formParams)) {
857 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
860 if (CRM_Utils_Array
::value('repetition_frequency_interval', $formParams)) {
861 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
864 //For Repeats on:(weekly case)
865 if ($formParams['repetition_frequency_unit'] == 'week') {
866 if (CRM_Utils_Array
::value('start_action_condition', $formParams)) {
867 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
868 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
872 //For Repeats By:(monthly case)
873 if ($formParams['repetition_frequency_unit'] == 'month') {
874 if ($formParams['repeats_by'] == 1) {
875 if (CRM_Utils_Array
::value('limit_to', $formParams)) {
876 $dbParams['limit_to'] = $formParams['limit_to'];
879 if ($formParams['repeats_by'] == 2) {
880 if (CRM_Utils_Array
::value('entity_status_1', $formParams) && CRM_Utils_Array
::value('entity_status_2', $formParams)) {
881 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
886 //For "Ends" - After:
887 if ($formParams['ends'] == 1) {
888 if (CRM_Utils_Array
::value('start_action_offset', $formParams)) {
889 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
894 if ($formParams['ends'] == 2) {
895 if (CRM_Utils_Array
::value('repeat_absolute_date', $formParams)) {
896 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
903 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
905 * @param int $scheduleReminderId
906 * Primary key of civicrm_action_schedule table .
911 static public function getScheduleReminderDetailsById($scheduleReminderId) {
913 FROM civicrm_action_schedule WHERE 1";
914 if ($scheduleReminderId) {
918 $dao = CRM_Core_DAO
::executeQuery($query,
920 1 => array($scheduleReminderId, 'Integer'),
928 * wrapper of getScheduleReminderDetailsById function
930 * @param int $scheduleReminderId
931 * Primary key of civicrm_action_schedule table .
935 public function getScheduleParams($scheduleReminderId) {
936 $scheduleReminderDetails = array();
937 if ($scheduleReminderId) {
938 //Get all the details from schedule reminder table
939 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
940 $scheduleReminderDetails = (array) $scheduleReminderDetails;
942 return $scheduleReminderDetails;
946 * This function takes criterias saved in civicrm_action_schedule table
947 * and creates recursion rule
949 * @param array $scheduleReminderDetails
950 * Array of repeat criterias saved in civicrm_action_schedule table .
955 public function getRecursionFromSchedule($scheduleReminderDetails = array()) {
957 //If there is some data for this id
958 if ($scheduleReminderDetails['repetition_frequency_unit']) {
959 if ($scheduleReminderDetails['start_action_date']) {
960 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
963 $currDate = date("Y-m-d H:i:s");
965 $start = new DateTime($currDate);
966 $this->recursion_start_date
= $start;
967 if ($scheduleReminderDetails['repetition_frequency_unit']) {
968 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
969 if ($repetition_frequency_unit == "day") {
970 $repetition_frequency_unit = "dai";
972 $repetition_frequency_unit = $repetition_frequency_unit . 'ly';
973 $r->recur($start, $repetition_frequency_unit);
976 if ($scheduleReminderDetails['repetition_frequency_interval']) {
977 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
980 $r->errors
[] = 'Repeats every: is a required field';
984 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
985 if ($scheduleReminderDetails['start_action_condition']) {
986 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
987 $explodeStartActionCondition = explode(',', $startActionCondition);
988 $buildRuleArray = array();
989 foreach ($explodeStartActionCondition as $key => $val) {
990 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
992 $r->wkst('MO')->byday($buildRuleArray);
997 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
998 if ($scheduleReminderDetails['entity_status']) {
999 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1000 switch ($startActionDate[0]) {
1002 $startActionDate1 = 1;
1006 $startActionDate1 = 2;
1010 $startActionDate1 = 3;
1014 $startActionDate1 = 4;
1018 $startActionDate1 = -1;
1021 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1022 $r->byday(array($concatStartActionDateBits));
1024 elseif ($scheduleReminderDetails['limit_to']) {
1025 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
1030 if ($scheduleReminderDetails['start_action_offset']) {
1031 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1032 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1034 $r->count($scheduleReminderDetails['start_action_offset']);
1037 if (CRM_Utils_Array
::value('absolute_date', $scheduleReminderDetails)) {
1038 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1039 $endDate = new DateTime($absoluteDate[0] . ' ' . $absoluteDate[1]);
1040 $endDate->modify('+1 day');
1041 $r->until($endDate);
1044 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1045 $r->errors
[] = 'Ends: is a required field';
1049 $r->errors
[] = 'Repeats: is a required field';
1056 * This function gets time difference between the two datetime object
1058 * @param DateTime $startDate
1060 * @param DateTime $endDate
1065 * DateTime object which contain time difference
1067 static public function getInterval($startDate, $endDate) {
1068 if ($startDate && $endDate) {
1069 $startDate = new DateTime($startDate);
1070 $endDate = new DateTime($endDate);
1071 return $startDate->diff($endDate);
1076 * This function gets all columns from civicrm_action_schedule on the basis of event id
1078 * @param int $entityId
1080 * @param string $used_for
1081 * Specifies for which entity type it's used for .
1086 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1090 FROM civicrm_action_schedule
1091 WHERE entity_value = %1";
1093 $query .= " AND used_for = %2";
1096 1 => array($entityId, 'Integer'),
1097 2 => array($used_for, 'String'),
1099 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1106 * Update mode column in civicrm_recurring_entity table for event related tabs
1108 * @param int $entityId
1110 * @param string $linkedEntityTable
1111 * Linked entity table name for this event .
1114 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1116 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1117 if (CRM_Utils_Array
::value($linkedEntityTable, self
::$_tableDAOMapper)) {
1118 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1121 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1124 $entityTable = $linkedEntityTable;
1126 'entity_id' => $entityId,
1127 'entity_table' => $mainEntityTable,
1129 $defaults = array();
1130 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1131 if (CRM_Utils_Array
::value('id', $defaults)) {
1132 $result['entityId'] = $defaults['id'];
1133 $result['entityTable'] = $entityTable;