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 static function getStatus() {
129 return self
::$status;
132 static function setStatus($status) {
133 self
::$status = $status;
136 * Save records in civicrm_recujrring_entity table
138 * @param array $params reference array contains the values submitted by the form
145 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 Parent entity id
171 * @param int $entityId Child entity id
172 * @param String $entityTable Name of the entity table
179 static function quickAdd($parentId, $entityId, $entityTable) {
182 'parent_id' => $parentId,
183 'entity_id' => $entityId,
184 'entity_table' => $entityTable
186 return self
::add($params);
190 * This function updates the mode column in the civicrm_recurring_entity table
192 * @param int $mode 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
198 function mode($mode) {
199 if ($this->entity_id
&& $this->entity_table
) {
200 if ($this->find(TRUE)) {
204 $this->parent_id
= $this->entity_id
;
212 * This function generates all new entities based on object vars
216 function generate() {
217 $this->generateRecursiveDates();
219 return $this->generateEntities();
223 * This function builds a "When" object based on schedule/reminder params
225 * @return object When object
227 function generateRecursion() {
228 // return if already generated
229 if (is_a($this->recursion
, 'When')) {
230 return $this->recursion
;
233 if ($this->scheduleId
) {
235 $this->schedule
= $this->getScheduleParams($this->scheduleId
);
237 else if (!empty($this->scheduleFormValues
)) {
238 $this->schedule
= $this->mapFormValuesToDB($this->scheduleFormValues
);
241 if (!empty($this->schedule
)) {
242 $this->recursion
= $this->getRecursionFromSchedule($this->schedule
);
244 return $this->recursion
;
248 * Generate new DAOs and along with entries in civicrm_recurring_entity table
252 function generateEntities() {
253 self
::setStatus(self
::RUNNING
);
255 $newEntities = array();
256 $findCriteria = array();
257 if (!empty($this->recursionDates
)) {
258 if ($this->entity_id
) {
259 $findCriteria = array('id' => $this->entity_id
);
261 // save an entry with initiating entity-id & entity-table
262 if ($this->entity_table
&& !$this->find(TRUE)) {
263 $this->parent_id
= $this->entity_id
;
267 if (empty($findCriteria)) {
268 CRM_Core_Error
::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
272 foreach ($this->recursionDates
as $key => $dateCols) {
273 $newCriteria = $dateCols;
274 foreach ($this->overwriteColumns
as $col => $val) {
275 $newCriteria[$col] = $val;
277 // create main entities
278 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
281 $this->isRecurringEntityRecord
284 if (is_a($obj, 'CRM_Core_DAO') && $obj->id
) {
285 $newCriteria = array();
286 $newEntities[$this->entity_table
][$count] = $obj->id
;
288 foreach ($this->linkedEntities
as $linkedInfo) {
289 foreach ($linkedInfo['linkedColumns'] as $col) {
290 $newCriteria[$col] = $obj->id
;
292 // create linked entities
293 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($linkedInfo['table'],
294 $linkedInfo['findCriteria'],
296 CRM_Utils_Array
::value('isRecurringEntityRecord', $linkedInfo, TRUE)
299 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id
) {
300 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id
;
308 self
::$status = NULL;
313 * This function iterates through when object criterias and
314 * generates recursive dates based on that
316 * @return array array of dates
318 function generateRecursiveDates() {
319 $this->generateRecursion();
321 $recursionDates = array();
322 if (is_a($this->recursion
, 'When')) {
323 $initialCount = CRM_Utils_Array
::value('start_action_offset', $this->schedule
);
325 $exRangeStart = $exRangeEnd = NULL;
326 if (!empty($this->excludeDateRangeColumns
)) {
327 $exRangeStart = $this->excludeDateRangeColumns
[0];
328 $exRangeEnd = $this->excludeDateRangeColumns
[1];
332 while ($result = $this->recursion
->next()) {
334 if ($result == $this->recursion_start_date
) {
335 // skip the recursion-start-date from the list we going to generate
338 $baseDate = CRM_Utils_Date
::processDate($result->format('Y-m-d H:i:s'));
340 foreach ($this->dateColumns
as $col) {
341 $recursionDates[$count][$col] = $baseDate;
343 foreach ($this->intervalDateColumns
as $col => $interval) {
344 $newDate = new DateTime($baseDate);
345 $newDate->add($interval);
346 $recursionDates[$count][$col] = CRM_Utils_Date
::processDate($newDate->format('Y-m-d H:i:s'));
349 $exRangeStartDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeStart], NULL, FALSE, 'Ymd');
350 $exRangeEndDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeEnd], NULL, FALSE, 'Ymd');
353 foreach ($this->excludeDates
as $exDate) {
354 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
355 if (!$exRangeStart) {
356 if ($exDate == $result->format('Ymd')) {
362 if (($exDate == $exRangeStartDate) ||
363 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
372 unset($recursionDates[$count]);
373 if ($initialCount && ($initialCount > 0)) {
374 // lets increase the counter, so we get correct number of occurrences
376 $this->recursion
->count($initialCount);
383 $this->recursionDates
= $recursionDates;
385 return $recursionDates;
389 * This function gets all the children for a particular parent entity
391 * @param int $parentId Parent entity id
392 * @param string $entityTable Name of the entity table
393 * @param boolean $includeParent If true parent id is included in result set and vice versa
394 * @param int $mode 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set.
395 * @param int $initiatorId the instance where this function is invoked from
400 * @return array an array of child ids
402 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
404 if (empty($parentId) ||
empty($entityTable)) {
409 $initiatorId = $parentId;
412 $queryParams = array(
413 1 => array($parentId, 'Integer'),
414 2 => array($entityTable, 'String'),
415 3 => array($initiatorId, 'Integer'),
419 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
423 FROM civicrm_recurring_entity
424 WHERE parent_id = %1 AND entity_table = %2";
425 if (!$includeParent) {
426 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
429 if ($mode == '1') { // MODE = SINGLE
430 $query .= " AND entity_id = %3";
432 else if ($mode == '2') { // MODE = FUTURE
433 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
434 if ($recurringEntityID) {
435 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
436 $query .= " ORDER BY id ASC"; // FIXME: change to order by dates
437 $queryParams[4] = array($recurringEntityID, 'Integer');
440 // something wrong, return empty
445 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
446 while ($dao->fetch()) {
447 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
448 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
454 * This function when passed an entity id checks if it has parent and
455 * returns all other entities that are connected to same parent.
457 * @param int $entityId entity id
458 * @param string $entityTable Entity table name
459 * @param boolean $includeParent Include parent in result set
460 * @param int $mode 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set.
465 * @return array array of connected ids
467 static public function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
468 $parentId = self
::getParentFor($entityId, $entityTable);
470 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
476 * This function gets the parent for the entity id passed to it
478 * @param int $entityId entity ID
479 * @param string $entityTable Entity table name
480 * @param boolean $includeParent Include parent in result set
485 * @return int unsigned $parentId Parent ID
487 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
488 if (empty($entityId) ||
empty($entityTable)) {
494 FROM civicrm_recurring_entity
495 WHERE entity_id = %1 AND entity_table = %2";
496 if (!$includeParent) {
497 $query .= " AND parent_id != %1";
500 CRM_Core_DAO
::singleValueQuery($query,
502 1 => array($entityId, 'Integer'),
503 2 => array($entityTable, 'String'),
510 * This function copies the information from parent entity and creates other entities with same information
512 * @param string $entityTable Entity table name
513 * @param array $fromCriteria array of all the fields & values on which basis to copy
514 * @param array $newParams array of all the fields & values to be copied besides the other fields
515 * @param boolean $createRecurringEntity if to create a record in recurring_entity table
522 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
523 $daoName = self
::$_tableDAOMapper[$entityTable];
525 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
527 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
529 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id
&& $createRecurringEntity) {
530 $object = new $daoName( );
531 foreach ($fromCriteria as $key => $value) {
532 $object->$key = $value;
536 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
542 * This function acts as a listener to dao->update whenever there is an update,
543 * and propagates any changes to all related entities present in recurring entity table
545 * @param object $event An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated
552 static public function triggerUpdate($event) {
553 // if DB version is earlier than 4.6 skip any processing
554 static $currentVer = NULL;
556 $currentVer = CRM_Core_BAO_Domain
::version();
558 if (version_compare($currentVer, '4.6.alpha1') < 0) {
562 static $processedEntities = array();
563 $obj =& $event->object;
564 if (empty($obj->id
) ||
empty($obj->__table
)) {
567 $key = "{$obj->__table}_{$obj->id}";
569 if (array_key_exists($key, $processedEntities)) {
574 // get related entities
575 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
576 if (empty($repeatingEntities)) {
577 // return if its not a recurring entity parent
580 // mark being processed
581 $processedEntities[$key] = 1;
583 // to make sure we not copying to source itself
584 unset($repeatingEntities[$key]);
586 foreach($repeatingEntities as $key => $val) {
587 $entityID = $val['id'];
588 $entityTable = $val['table'];
590 $processedEntities[$key] = 1;
592 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
593 $daoName = self
::$_tableDAOMapper[$entityTable];
596 if (array_key_exists($entityTable, self
::$_updateSkipFields)) {
597 $skipFields = self
::$_updateSkipFields[$entityTable];
598 foreach ($skipFields as $sfield) {
599 $skipData[$sfield] = NULL;
603 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
604 CRM_Core_DAO
::freeResult();
607 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
610 // done with processing. lets unset static var.
611 unset($processedEntities);
615 * This function acts as a listener to dao->save,
616 * and creates entries for linked entities in recurring entity table
618 * @param object $event An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted
625 static public function triggerInsert($event) {
626 $obj =& $event->object;
627 if (!array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo)) {
631 // if DB version is earlier than 4.6 skip any processing
632 static $currentVer = NULL;
634 $currentVer = CRM_Core_BAO_Domain
::version();
636 if (version_compare($currentVer, '4.6.alpha1') < 0) {
640 static $processedEntities = array();
641 if (empty($obj->id
) ||
empty($obj->__table
)) {
644 $key = "{$obj->__table}_{$obj->id}";
646 if (array_key_exists($key, $processedEntities)) {
647 // already being processed. Exit recursive calls.
651 if (self
::getStatus() == self
::RUNNING
) {
652 // if recursion->generate() is doing some work, lets not intercept
656 // mark being processed
657 $processedEntities[$key] = 1;
659 // get related entities for table being saved
660 $hasaRecurringRecord = self
::getParentFor($obj->id
, $obj->__table
);
662 if (empty($hasaRecurringRecord)) {
663 // check if its a linked entity
664 if (array_key_exists($obj->__table
, self
::$_linkedEntitiesInfo) &&
665 !CRM_Utils_Array
::value('is_multirecord', self
::$_linkedEntitiesInfo[$obj->__table
])) {
666 $linkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
667 $linkedDAO->id
= $obj->id
;
668 if ($linkedDAO->find(TRUE)) {
669 $idCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_id_col'];
670 $tableCol = self
::$_linkedEntitiesInfo[$obj->__table
]['entity_table_col'];
672 $pEntityID = $linkedDAO->$idCol;
673 $pEntityTable = $linkedDAO->$tableCol;
675 // find all parent recurring entity set
676 $pRepeatingEntities = self
::getEntitiesFor($pEntityID, $pEntityTable);
678 if (!empty($pRepeatingEntities)) {
679 // for each parent entity in the set, find out a similar linked entity,
680 // if doesn't exist create one, and also create entries in recurring_entity table
682 foreach($pRepeatingEntities as $key => $val) {
683 if (array_key_exists($key, $processedEntities)) {
684 // this graph is already being processed
687 $processedEntities[$key] = 1;
690 // start with first entry with just itself
691 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $obj->id
, $obj->__table
);
693 foreach($pRepeatingEntities as $key => $val) {
694 $rlinkedDAO = new self
::$_tableDAOMapper[$obj->__table
]();
695 $rlinkedDAO->$idCol = $val['id'];
696 $rlinkedDAO->$tableCol = $val['table'];
697 if ($rlinkedDAO->find(TRUE)) {
698 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $rlinkedDAO->id
, $obj->__table
);
701 // linked entity doesn't exist. lets create them
702 $newCriteria = array(
703 $idCol => $val['id'],
704 $tableCol => $val['table']
706 $linkedObj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($obj->__table
,
707 array('id' => $obj->id
),
711 if ($linkedObj->id
) {
712 CRM_Core_BAO_RecurringEntity
::quickAdd($obj->id
, $linkedObj->id
, $obj->__table
);
721 // done with processing. lets unset static var.
722 unset($processedEntities);
726 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
728 * @param object $event An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted
735 static public function triggerDelete($event) {
736 $obj =& $event->object;
738 // if DB version is earlier than 4.6 skip any processing
739 static $currentVer = NULL;
741 $currentVer = CRM_Core_BAO_Domain
::version();
743 if (version_compare($currentVer, '4.6.alpha1') < 0) {
747 static $processedEntities = array();
748 if (empty($obj->id
) ||
empty($obj->__table
) ||
!$event->result
) {
751 $key = "{$obj->__table}_{$obj->id}";
753 if (array_key_exists($key, $processedEntities)) {
758 // mark being processed
759 $processedEntities[$key] = 1;
761 $parentID = self
::getParentFor($obj->id
, $obj->__table
);
763 CRM_Core_BAO_RecurringEntity
::delEntity($obj->id
, $obj->__table
, TRUE);
768 * This function deletes main entity and related linked entities from recurring-entity table
770 * @param int $entityId Entity id
771 * @param string $entityTable Name of the entity table
776 * @return boolean|object Returns either boolean value or CRM_Core_DAO_RecurringEntity object
778 static public function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
779 if (empty($entityId) ||
empty($entityTable)) {
782 $dao = new CRM_Core_DAO_RecurringEntity();
783 $dao->entity_id
= $entityId;
784 $dao->entity_table
= $entityTable;
785 if ($dao->find(TRUE)) {
786 // make sure its not a linked entity thats being deleted
787 if ($isDelLinkedEntities && !array_key_exists($entityTable, self
::$_linkedEntitiesInfo)) {
788 // delete all linked entities from recurring entity table
789 foreach (self
::$_linkedEntitiesInfo as $linkedTable => $linfo) {
790 $daoName = self
::$_tableDAOMapper[$linkedTable];
792 CRM_Core_Error
::fatal("DAO Mapper missing for $linkedTable.");
795 $linkedDao = new $daoName();
796 $linkedDao->$linfo['entity_id_col'] = $entityId;
797 $linkedDao->$linfo['entity_table_col'] = $entityTable;
799 while ($linkedDao->fetch()) {
800 CRM_Core_BAO_RecurringEntity
::delEntity($linkedDao->id
, $linkedTable, FALSE);
804 // delete main entity
805 return $dao->delete();
811 * This function maps values posted from form to civicrm_action_schedule columns
813 * @param array $formParams and array of form values posted
817 function mapFormValuesToDB($formParams = array()) {
819 if (CRM_Utils_Array
::value('used_for', $formParams)) {
820 $dbParams['used_for'] = $formParams['used_for'];
823 if (CRM_Utils_Array
::value('entity_id', $formParams)) {
824 $dbParams['entity_value'] = $formParams['entity_id'];
827 if (CRM_Utils_Array
::value('repetition_start_date', $formParams)) {
828 if (CRM_Utils_Array
::value('repetition_start_date_display', $formParams)) {
829 $repetitionStartDate = $formParams['repetition_start_date_display'];
832 $repetitionStartDate = $formParams['repetition_start_date'];
834 if (CRM_Utils_Array
::value('repetition_start_date_time', $formParams)) {
835 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
837 $repetition_start_date = new DateTime($repetitionStartDate);
838 $dbParams['start_action_date'] = CRM_Utils_Date
::processDate($repetition_start_date->format('Y-m-d H:i:s'));
841 if (CRM_Utils_Array
::value('repetition_frequency_unit', $formParams)) {
842 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
845 if (CRM_Utils_Array
::value('repetition_frequency_interval', $formParams)) {
846 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
849 //For Repeats on:(weekly case)
850 if ($formParams['repetition_frequency_unit'] == 'week') {
851 if (CRM_Utils_Array
::value('start_action_condition', $formParams)) {
852 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
853 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
857 //For Repeats By:(monthly case)
858 if ($formParams['repetition_frequency_unit'] == 'month') {
859 if ($formParams['repeats_by'] == 1) {
860 if (CRM_Utils_Array
::value('limit_to', $formParams)) {
861 $dbParams['limit_to'] = $formParams['limit_to'];
864 if ($formParams['repeats_by'] == 2) {
865 if (CRM_Utils_Array
::value('entity_status_1', $formParams) && CRM_Utils_Array
::value('entity_status_2', $formParams)) {
866 $dbParams['entity_status'] = $formParams['entity_status_1']." ".$formParams['entity_status_2'];
871 //For "Ends" - After:
872 if ($formParams['ends'] == 1) {
873 if (CRM_Utils_Array
::value('start_action_offset', $formParams)) {
874 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
879 if ($formParams['ends'] == 2) {
880 if (CRM_Utils_Array
::value('repeat_absolute_date', $formParams)) {
881 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
888 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
890 * @param int $scheduleReminderId primary key of civicrm_action_schedule table
897 static public function getScheduleReminderDetailsById($scheduleReminderId) {
899 FROM civicrm_action_schedule WHERE 1";
900 if ($scheduleReminderId) {
904 $dao = CRM_Core_DAO
::executeQuery($query,
906 1 => array($scheduleReminderId, 'Integer')
914 * This function is a wrapper of getScheduleReminderDetailsById function
916 * @param int $scheduleReminderId primary key of civicrm_action_schedule table
920 function getScheduleParams($scheduleReminderId) {
921 $scheduleReminderDetails = array();
922 if ($scheduleReminderId) {
923 //Get all the details from schedule reminder table
924 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
925 $scheduleReminderDetails = (array) $scheduleReminderDetails;
927 return $scheduleReminderDetails;
931 * This function takes criterias saved in civicrm_action_schedule table
932 * and creates recursion rule
934 * @param array $scheduleReminderDetails array of repeat criterias saved in civicrm_action_schedule table
936 * @return object When object
938 function getRecursionFromSchedule($scheduleReminderDetails = array()) {
940 //If there is some data for this id
941 if ($scheduleReminderDetails['repetition_frequency_unit']) {
942 if ($scheduleReminderDetails['start_action_date']) {
943 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
946 $currDate = date("Y-m-d H:i:s");
948 $start = new DateTime($currDate);
949 $this->recursion_start_date
= $start;
950 if ($scheduleReminderDetails['repetition_frequency_unit']) {
951 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
952 if ($repetition_frequency_unit == "day") {
953 $repetition_frequency_unit = "dai";
955 $repetition_frequency_unit = $repetition_frequency_unit.'ly';
956 $r->recur($start, $repetition_frequency_unit);
959 if ($scheduleReminderDetails['repetition_frequency_interval']) {
960 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
963 $r->errors
[] = 'Repeats every: is a required field';
967 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
968 if ($scheduleReminderDetails['start_action_condition']) {
969 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
970 $explodeStartActionCondition = explode(',', $startActionCondition);
971 $buildRuleArray = array();
972 foreach($explodeStartActionCondition as $key => $val) {
973 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
975 $r->wkst('MO')->byday($buildRuleArray);
980 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
981 if ($scheduleReminderDetails['entity_status']) {
982 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
983 switch ($startActionDate[0]) {
985 $startActionDate1 = 1;
988 $startActionDate1 = 2;
991 $startActionDate1 = 3;
994 $startActionDate1 = 4;
997 $startActionDate1 = -1;
1000 $concatStartActionDateBits = $startActionDate1.strtoupper(substr($startActionDate[1], 0, 2));
1001 $r->byday(array($concatStartActionDateBits));
1003 else if ($scheduleReminderDetails['limit_to']) {
1004 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
1009 if ($scheduleReminderDetails['start_action_offset']) {
1010 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1011 $r->errors
[] = 'Occurrences should be less than or equal to 30';
1013 $r->count($scheduleReminderDetails['start_action_offset']);
1016 if (CRM_Utils_Array
::value('absolute_date', $scheduleReminderDetails)) {
1017 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
1018 $endDate = new DateTime($absoluteDate[0].' '.$absoluteDate[1]);
1019 $endDate->modify('+1 day');
1020 $r->until($endDate);
1023 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1024 $r->errors
[] = 'Ends: is a required field';
1028 $r->errors
[] = 'Repeats: is a required field';
1035 * This function gets time difference between the two datetime object
1037 * @param DateTime $startDate Start Date
1038 * @param DateTime $endDate End Date
1043 * @return object DateTime object which contain time difference
1045 static public function getInterval($startDate, $endDate) {
1046 if ($startDate && $endDate) {
1047 $startDate = new DateTime($startDate);
1048 $endDate = new DateTime($endDate);
1049 return $startDate->diff($endDate);
1054 * This function gets all columns from civicrm_action_schedule on the basis of event id
1056 * @param int $entityId Entity ID
1057 * @param string $used_for Specifies for which entity type it's used for
1064 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1068 FROM civicrm_action_schedule
1069 WHERE entity_value = %1";
1071 $query .= " AND used_for = %2";
1074 1 => array($entityId, 'Integer'),
1075 2 => array($used_for, 'String')
1077 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1084 * Update mode column in civicrm_recurring_entity table for event related tabs
1086 * @param int $entityId event id
1087 * @param string $linkedEntityTable Linked entity table name for this event
1090 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1092 if ( $entityId && $linkedEntityTable && $mainEntityTable ) {
1093 if (CRM_Utils_Array
::value($linkedEntityTable, self
::$_tableDAOMapper)) {
1094 $dao = self
::$_tableDAOMapper[$linkedEntityTable];
1097 CRM_Core_Session
::setStatus('Could not update mode for linked entities');
1100 $entityTable = $linkedEntityTable;
1102 'entity_id' => $entityId,
1103 'entity_table' => $mainEntityTable
1105 $defaults = array();
1106 CRM_Core_DAO
::commonRetrieve($dao, $params, $defaults);
1107 if (CRM_Utils_Array
::value('id', $defaults)) {
1108 $result['entityId'] = $defaults['id'];
1109 $result['entityTable'] = $entityTable;