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
227 * @return object When object
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
318 * @return array array of dates
320 public function generateRecursiveDates() {
321 $this->generateRecursion();
323 $recursionDates = array();
324 if (is_a($this->recursion
, 'When')) {
325 $initialCount = CRM_Utils_Array
::value('start_action_offset', $this->schedule
);
327 $exRangeStart = $exRangeEnd = NULL;
328 if (!empty($this->excludeDateRangeColumns
)) {
329 $exRangeStart = $this->excludeDateRangeColumns
[0];
330 $exRangeEnd = $this->excludeDateRangeColumns
[1];
334 while ($result = $this->recursion
->next()) {
336 if ($result == $this->recursion_start_date
) {
337 // skip the recursion-start-date from the list we going to generate
340 $baseDate = CRM_Utils_Date
::processDate($result->format('Y-m-d H:i:s'));
342 foreach ($this->dateColumns
as $col) {
343 $recursionDates[$count][$col] = $baseDate;
345 foreach ($this->intervalDateColumns
as $col => $interval) {
346 $newDate = new DateTime($baseDate);
347 $newDate->add($interval);
348 $recursionDates[$count][$col] = CRM_Utils_Date
::processDate($newDate->format('Y-m-d H:i:s'));
351 $exRangeStartDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeStart], NULL, FALSE, 'Ymd');
352 $exRangeEndDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeEnd], NULL, FALSE, 'Ymd');
355 foreach ($this->excludeDates
as $exDate) {
356 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
357 if (!$exRangeStart) {
358 if ($exDate == $result->format('Ymd')) {
364 if (($exDate == $exRangeStartDate) ||
365 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
374 unset($recursionDates[$count]);
375 if ($initialCount && ($initialCount > 0)) {
376 // lets increase the counter, so we get correct number of occurrences
378 $this->recursion
->count($initialCount);
385 $this->recursionDates
= $recursionDates;
387 return $recursionDates;
391 * This function gets all the children for a particular parent entity
393 * @param int $parentId
395 * @param string $entityTable
396 * Name of the entity table .
397 * @param bool $includeParent
398 * If true parent id is included in result set and vice versa .
400 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
401 * @param int $initiatorId
402 * The instance where this function is invoked from .
406 * @return array an array of child ids
408 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
410 if (empty($parentId) ||
empty($entityTable)) {
415 $initiatorId = $parentId;
418 $queryParams = array(
419 1 => array($parentId, 'Integer'),
420 2 => array($entityTable, 'String'),
421 3 => array($initiatorId, 'Integer'),
425 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
429 FROM civicrm_recurring_entity
430 WHERE parent_id = %1 AND entity_table = %2";
431 if (!$includeParent) {
432 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
435 if ($mode == '1') { // MODE = SINGLE
436 $query .= " AND entity_id = %3";
438 elseif ($mode == '2') { // MODE = FUTURE
439 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
440 if ($recurringEntityID) {
441 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
442 $query .= " ORDER BY id ASC"; // FIXME: change to order by dates
443 $queryParams[4] = array($recurringEntityID, 'Integer');
446 // something wrong, return empty
451 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
452 while ($dao->fetch()) {
453 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
454 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
460 * This function when passed an entity id checks if it has parent and
461 * returns all other entities that are connected to same parent.
463 * @param int $entityId
465 * @param string $entityTable
466 * Entity table name .
467 * @param bool $includeParent
468 * Include parent in result set .
470 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
474 * @return array array of connected ids
476 static public function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
477 $parentId = self
::getParentFor($entityId, $entityTable);
479 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
485 * This function gets the parent for the entity id passed to it
487 * @param int $entityId
489 * @param string $entityTable
490 * Entity table name .
491 * @param bool $includeParent
492 * Include parent in result set .
496 * @return int unsigned $parentId Parent ID
498 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
499 if (empty($entityId) ||
empty($entityTable)) {
505 FROM civicrm_recurring_entity
506 WHERE entity_id = %1 AND entity_table = %2";
507 if (!$includeParent) {
508 $query .= " AND parent_id != %1";
511 CRM_Core_DAO
::singleValueQuery($query,
513 1 => array($entityId, 'Integer'),
514 2 => array($entityTable, 'String'),
521 * This function copies the information from parent entity and creates other entities with same information
523 * @param string $entityTable
524 * Entity table name .
525 * @param array $fromCriteria
526 * Array of all the fields & values on which basis to copy .
527 * @param array $newParams
528 * Array of all the fields & values to be copied besides the other fields .
529 * @param bool $createRecurringEntity
530 * If to create a record in recurring_entity table .
536 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
537 $daoName = self
::$_tableDAOMapper[$entityTable];
539 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
541 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
543 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
544 $object = new $daoName( );
545 foreach ($fromCriteria as $key => $value) {
546 $object->$key = $value;
550 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
556 * This function acts as a listener to dao->update whenever there is an update,
557 * and propagates any changes to all related entities present in recurring entity table
559 * @param object $event
560 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated .
566 static public function triggerUpdate($event) {
567 // if DB version is earlier than 4.6 skip any processing
568 static $currentVer = NULL;
570 $currentVer = CRM_Core_BAO_Domain
::version();
572 if (version_compare($currentVer, '4.6.alpha1') < 0) {
576 static $processedEntities = array();
577 $obj =& $event->object;
578 if (empty($obj->id
) ||
empty($obj->__table
)) {
581 $key = "{$obj->__table}_{$obj->id}";
583 if (array_key_exists($key, $processedEntities)) {
588 // get related entities
589 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
590 if (empty($repeatingEntities)) {
591 // return if its not a recurring entity parent
594 // mark being processed
595 $processedEntities[$key] = 1;
597 // to make sure we not copying to source itself
598 unset($repeatingEntities[$key]);
600 foreach ($repeatingEntities as $key => $val) {
601 $entityID = $val['id'];
602 $entityTable = $val['table'];
604 $processedEntities[$key] = 1;
606 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
607 $daoName = self
::$_tableDAOMapper[$entityTable];
610 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
611 $skipFields = self
::$_updateSkipFields[$entityTable];
612 foreach ($skipFields as $sfield) {
613 $skipData[$sfield] = NULL;
617 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
618 CRM_Core_DAO
::freeResult();
621 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
624 // done with processing. lets unset static var.
625 unset($processedEntities);
629 * This function acts as a listener to dao->save,
630 * and creates entries for linked entities in recurring entity table
632 * @param object $event
633 * 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
])) {
680 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
681 $linkedDAO->id
= $obj->id
;
682 if ($linkedDAO->find(TRUE)) {
683 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
684 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
686 $pEntityID = $linkedDAO->$idCol;
687 $pEntityTable = $linkedDAO->$tableCol;
689 // find all parent recurring entity set
690 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
692 if (!empty($pRepeatingEntities)) {
693 // for each parent entity in the set, find out a similar linked entity,
694 // if doesn't exist create one, and also create entries in recurring_entity table
696 foreach ($pRepeatingEntities as $key => $val) {
697 if (array_key_exists($key, $processedEntities)) {
698 // this graph is already being processed
701 $processedEntities[$key] = 1;
704 // start with first entry with just itself
705 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
707 foreach ($pRepeatingEntities as $key => $val) {
708 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
709 $rlinkedDAO->$idCol = $val['id'];
710 $rlinkedDAO->$tableCol = $val['table'];
711 if ($rlinkedDAO->find(TRUE)) {
712 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
715 // linked entity doesn't exist. lets create them
716 $newCriteria = array(
717 $idCol => $val['id'],
718 $tableCol => $val['table']
720 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
721 array('id' => $obj->id
),
725 if ($linkedObj->id
) {
726 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
735 // done with processing. lets unset static var.
736 unset($processedEntities);
740 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
742 * @param object $event
743 * 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 .
791 * @return boolean|object Returns either boolean value or CRM_Core_DAO_RecurringEntity object
793 static public function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
794 if (empty($entityId) ||
empty($entityTable)) {
797 $dao = new CRM_Core_DAO_RecurringEntity();
798 $dao->entity_id
= $entityId;
799 $dao->entity_table
= $entityTable;
800 if ($dao->find(TRUE)) {
801 // make sure its not a linked entity thats being deleted
802 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
803 // delete all linked entities from recurring entity table
804 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
805 $daoName = self
::$_tableDAOMapper[$linkedTable];
807 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
810 $linkedDao = new $daoName();
811 $linkedDao->$linfo['entity_id_col'] = $entityId;
812 $linkedDao->$linfo['entity_table_col'] = $entityTable;
814 while ($linkedDao->fetch()) {
815 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
819 // delete main entity
820 return $dao->delete();
826 * This function maps values posted from form to civicrm_action_schedule columns
828 * @param array $formParams
829 * And array of form values posted .
833 public function mapFormValuesToDB($formParams = array()) {
835 if (CRM_Utils_Array
::value('used_for', $formParams)) {
836 $dbParams['used_for'] = $formParams['used_for'];
839 if (CRM_Utils_Array
::value('entity_id', $formParams)) {
840 $dbParams['entity_value'] = $formParams['entity_id'];
843 if (CRM_Utils_Array
::value('repetition_start_date', $formParams)) {
844 if (CRM_Utils_Array
::value('repetition_start_date_display', $formParams)) {
845 $repetitionStartDate = $formParams['repetition_start_date_display'];
848 $repetitionStartDate = $formParams['repetition_start_date'];
850 if (CRM_Utils_Array
::value('repetition_start_date_time', $formParams)) {
851 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
853 $repetition_start_date = new DateTime($repetitionStartDate);
854 $dbParams['start_action_date'] = CRM_Utils_Date
::processDate($repetition_start_date->format('Y-m-d H:i:s'));
857 if (CRM_Utils_Array
::value('repetition_frequency_unit', $formParams)) {
858 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
861 if (CRM_Utils_Array
::value('repetition_frequency_interval', $formParams)) {
862 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
865 //For Repeats on:(weekly case)
866 if ($formParams['repetition_frequency_unit'] == 'week') {
867 if (CRM_Utils_Array
::value('start_action_condition', $formParams)) {
868 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
869 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
873 //For Repeats By:(monthly case)
874 if ($formParams['repetition_frequency_unit'] == 'month') {
875 if ($formParams['repeats_by'] == 1) {
876 if (CRM_Utils_Array
::value('limit_to', $formParams)) {
877 $dbParams['limit_to'] = $formParams['limit_to'];
880 if ($formParams['repeats_by'] == 2) {
881 if (CRM_Utils_Array
::value('entity_status_1', $formParams) && CRM_Utils_Array
::value('entity_status_2', $formParams)) {
882 $dbParams['entity_status'] = $formParams['entity_status_1']." ".$formParams['entity_status_2'];
887 //For "Ends" - After:
888 if ($formParams['ends'] == 1) {
889 if (CRM_Utils_Array
::value('start_action_offset', $formParams)) {
890 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
895 if ($formParams['ends'] == 2) {
896 if (CRM_Utils_Array
::value('repeat_absolute_date', $formParams)) {
897 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
904 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
906 * @param int $scheduleReminderId
907 * Primary key of civicrm_action_schedule table .
913 static public function getScheduleReminderDetailsById($scheduleReminderId) {
915 FROM civicrm_action_schedule WHERE 1";
916 if ($scheduleReminderId) {
920 $dao = CRM_Core_DAO
::executeQuery($query,
922 1 => array($scheduleReminderId, 'Integer')
930 * This function is a wrapper of getScheduleReminderDetailsById function
932 * @param int $scheduleReminderId
933 * Primary key of civicrm_action_schedule table .
937 public function getScheduleParams($scheduleReminderId) {
938 $scheduleReminderDetails = array();
939 if ($scheduleReminderId) {
940 //Get all the details from schedule reminder table
941 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
942 $scheduleReminderDetails = (array) $scheduleReminderDetails;
944 return $scheduleReminderDetails;
948 * This function takes criterias saved in civicrm_action_schedule table
949 * and creates recursion rule
951 * @param array $scheduleReminderDetails
952 * Array of repeat criterias saved in civicrm_action_schedule table .
954 * @return object When object
956 public function getRecursionFromSchedule($scheduleReminderDetails = array()) {
958 //If there is some data for this id
959 if ($scheduleReminderDetails['repetition_frequency_unit']) {
960 if ($scheduleReminderDetails['start_action_date']) {
961 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
964 $currDate = date("Y-m-d H:i:s");
966 $start = new DateTime($currDate);
967 $this->recursion_start_date
= $start;
968 if ($scheduleReminderDetails['repetition_frequency_unit']) {
969 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
970 if ($repetition_frequency_unit == "day") {
971 $repetition_frequency_unit = "dai";
973 $repetition_frequency_unit = $repetition_frequency_unit.'ly';
974 $r->recur($start, $repetition_frequency_unit);
977 if ($scheduleReminderDetails['repetition_frequency_interval']) {
978 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
981 $r->errors
[] = 'Repeats every: is a required field';
985 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
986 if ($scheduleReminderDetails['start_action_condition']) {
987 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
988 $explodeStartActionCondition = explode(',', $startActionCondition);
989 $buildRuleArray = array();
990 foreach ($explodeStartActionCondition as $key => $val) {
991 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
993 $r->wkst('MO')->byday($buildRuleArray);
998 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
999 if ($scheduleReminderDetails['entity_status']) {
1000 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1001 switch ($startActionDate[0]) {
1003 $startActionDate1 = 1;
1006 $startActionDate1 = 2;
1009 $startActionDate1 = 3;
1012 $startActionDate1 = 4;
1015 $startActionDate1 = -1;
1018 $concatStartActionDateBits = $startActionDate1.strtoupper(substr($startActionDate[1], 0, 2));
1019 $r->byday(array($concatStartActionDateBits));
1021 elseif ($scheduleReminderDetails['limit_to']) {
1022 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
1027 if ($scheduleReminderDetails['start_action_offset']) {
1028 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1029 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1031 $r->count($scheduleReminderDetails['start_action_offset']);
1034 if (CRM_Utils_Array
::value('absolute_date', $scheduleReminderDetails)) {
1035 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1036 $endDate = new DateTime($absoluteDate[0].' '.$absoluteDate[1]);
1037 $endDate->modify('+1 day');
1038 $r->until($endDate);
1041 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1042 $r->errors
[] = 'Ends: is a required field';
1046 $r->errors
[] = 'Repeats: is a required field';
1053 * This function gets time difference between the two datetime object
1055 * @param DateTime $startDate
1057 * @param DateTime $endDate
1062 * @return object DateTime object which contain time difference
1064 static public function getInterval($startDate, $endDate) {
1065 if ($startDate && $endDate) {
1066 $startDate = new DateTime($startDate);
1067 $endDate = new DateTime($endDate);
1068 return $startDate->diff($endDate);
1073 * This function gets all columns from civicrm_action_schedule on the basis of event id
1075 * @param int $entityId
1077 * @param string $used_for
1078 * Specifies for which entity type it's used for .
1084 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1088 FROM civicrm_action_schedule
1089 WHERE entity_value = %1";
1091 $query .= " AND used_for = %2";
1094 1 => array($entityId, 'Integer'),
1095 2 => array($used_for, 'String')
1097 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1104 * Update mode column in civicrm_recurring_entity table for event related tabs
1106 * @param int $entityId
1108 * @param string $linkedEntityTable
1109 * Linked entity table name for this event .
1112 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1114 if ( $entityId && $linkedEntityTable && $mainEntityTable ) {
1115 if (CRM_Utils_Array
::value($linkedEntityTable, self
::$_tableDAOMapper)) {
1116 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1119 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1122 $entityTable = $linkedEntityTable;
1124 'entity_id' => $entityId,
1125 'entity_table' => $mainEntityTable
1127 $defaults = array();
1128 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1129 if (CRM_Utils_Array
::value('id', $defaults)) {
1130 $result['entityId'] = $defaults['id'];
1131 $result['entityTable'] = $entityTable;