3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
36 require_once 'packages/When/When.php';
38 class CRM_Core_BAO_RecurringEntity
extends CRM_Core_DAO_RecurringEntity
{
40 public $schedule = array();
41 public $scheduleId = NULL;
42 public $scheduleDBParams = array();
44 public $dateColumns = array();
45 public $overwriteColumns = array();
46 public $intervalDateColumns = array();
48 public $excludeDates = array();
50 public $recursion = NULL;
51 public $recursionCounter = NULL;
53 public $isGenRecurringEntity = TRUE;
55 static $_tableDAOMapper =
57 'civicrm_event' => 'CRM_Event_DAO_Event',
58 'civicrm_price_set_entity' => 'CRM_Price_DAO_PriceSetEntity',
59 'civicrm_uf_join' => 'CRM_Core_DAO_UFJoin',
60 'civicrm_tell_friend' => 'CRM_Friend_DAO_Friend',
61 'civicrm_pcp_block' => 'CRM_PCP_DAO_PCPBlock',
62 'civicrm_activity' => 'CRM_Activity_DAO_Activity',
65 static function add(&$params) {
66 if (CRM_Utils_Array
::value('id', $params)) {
67 CRM_Utils_Hook
::pre('edit', 'RecurringEntity', $params['id'], $params);
70 CRM_Utils_Hook
::pre('create', 'RecurringEntity', NULL, $params);
73 $daoRecurringEntity = new CRM_Core_DAO_RecurringEntity();
74 $daoRecurringEntity->copyValues($params);
75 $result = $daoRecurringEntity->save();
77 if (CRM_Utils_Array
::value('id', $params)) {
78 CRM_Utils_Hook
::post('edit', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
81 CRM_Utils_Hook
::post('create', 'RecurringEntity', $daoRecurringEntity->id
, $daoRecurringEntity);
86 static function quickAdd($parentId, $entityId, $entityTable) {
89 'parent_id' => $parentId,
90 'entity_id' => $entityId,
91 'entity_table' => $entityTable
93 return self
::add($params);
96 function mode($mode) {
97 if ($this->entity_id
&& $this->entity_table
) {
98 if ($this->find(TRUE)) {
101 $this->parent_id
= $this->entity_id
;
108 // generate all new entities based on object vars
109 function generate() {
110 $this->generateRecursiveDates();
112 return $this->generateEntities();
115 function generateRecursion() {
116 // return if already generated
117 if (is_a($this->recursion
, 'When')) {
118 return $this->recursion
;
121 if ($this->scheduleId
) {
123 $this->recursion
= $this->getRecursionFromReminder($this->scheduleId
);
124 } else if (!empty($this->schedule
)) {
125 $this->scheduleDBParams
= $this->mapFormValuesToDB($this->schedule
);//call using obj
128 if (!empty($this->scheduleDBParams
)) {
129 $this->recursion
= $this->getRecursionFromReminderByDBParams($this->scheduleDBParams
);
131 return $this->recursion
;
134 // generate new DAOs and along with entries in recurring_entity table
135 function generateEntities() {
136 // fixme: check if entityid & entitytable set
138 $newEntities = array();
139 if (!empty($this->recursionDates
)) {
140 // save an entry with initiating entity-id & entity-table
141 if (!$this->find(TRUE)) {
142 $this->parent_id
= $this->entity_id
;
146 foreach ($this->recursionDates
as $key => $dateCols) {
147 $newCriteria = $dateCols;
148 foreach ($this->overwriteColumns
as $col => $val) {
149 $newCriteria[$col] = $val;
151 $obj = CRM_Core_BAO_RecurringEntity
::copyCreateEntity($this->entity_table
,
152 array('id' => $this->entity_id
),
154 $this->isGenRecurringEntity
156 $newEntities[] = $obj->id
;
162 function generateRecursiveDates() {
163 $this->generateRecursion();
165 $recursionDates = array();
166 if (is_a($this->recursion
, 'When')) {
167 $initialCount = CRM_Utils_Array
::value('start_action_offset', $this->scheduleDBParams
);
169 $exRangeStart = $exRangeEnd = NULL;
170 if (!empty($this->excludeDateRangeColumns
)) {
171 $exRangeStart = $this->excludeDateRangeColumns
[0];
172 $exRangeEnd = $this->excludeDateRangeColumns
[1];
176 while ($result = $this->recursion
->next()) {
177 $baseDate = CRM_Utils_Date
::processDate($result->format('Y-m-d H:i:s'));
179 foreach ($this->dateColumns
as $col) {
180 $recursionDates[$count][$col] = $baseDate;
182 foreach ($this->intervalDateColumns
as $col => $interval) {
183 $newDate = new DateTime($baseDate);
184 $newDate->add($interval);
185 $recursionDates[$count][$col] = CRM_Utils_Date
::processDate($newDate->format('Y-m-d H:i:s'));
188 $exRangeStartDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeStart], NULL, FALSE, 'Ymd');
189 $exRangeEndDate = CRM_Utils_Date
::processDate($recursionDates[$count][$exRangeEnd], NULL, FALSE, 'Ymd');
193 foreach ($this->excludeDates
as $exDate) {
194 $exDate = CRM_Utils_Date
::processDate($exDate, NULL, FALSE, 'Ymd');
195 if (!$exRangeStart) {
196 if ($exDate == $result->format('Ymd')) {
201 if (($exDate == $exRangeStartDate) ||
202 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
211 unset($recursionDates[$count]);
212 if ($initialCount && ($initialCount > 0)) {
213 // lets increase the counter, so we get correct number of occurrences
215 $this->recursion
->count($initialCount);
216 $this->recursionCounter
= $initialCount;
223 $this->recursionDates
= $recursionDates;
225 return $recursionDates;
229 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
233 $initiatorId = $parentId;
236 $queryParams = array(
237 1 => array($parentId, 'Integer'),
238 2 => array($entityTable, 'String'),
239 3 => array($initiatorId, 'Integer'),
243 $mode = CRM_Core_DAO
::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
247 FROM civicrm_recurring_entity
248 WHERE parent_id = %1 AND entity_table = %2";
249 if (!$includeParent) {
250 $query .= " AND entity_id != " . ($initiatorId ?
"%3" : "%1");
253 if ($mode == '1') { // MODE = SINGLE
254 $query .= " AND entity_id = %3";
255 } else if ($mode == '2') { // MODE = FUTURE
256 $recurringEntityID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
257 if ($recurringEntityID) {
258 $query .= $includeParent ?
" AND id >= %4" : " AND id > %4";
259 $query .= " ORDER BY id ASC"; // FIXME: change to order by dates
260 $queryParams[4] = array($recurringEntityID, 'Integer');
262 // something wrong, return empty
267 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
268 while ($dao->fetch()) {
269 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table
;
270 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id
;
275 static public function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
276 $parentId = self
::getParentFor($entityId, $entityTable);
278 return self
::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
283 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
286 FROM civicrm_recurring_entity
287 WHERE entity_id = %1 AND entity_table = %2";
288 if (!$includeParent) {
289 $query .= " AND parent_id != %1";
292 CRM_Core_DAO
::singleValueQuery($query,
294 1 => array($entityId, 'Integer'),
295 2 => array($entityTable, 'String'),
301 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
302 $daoName = self
::$_tableDAOMapper[$entityTable];
303 $newObject = CRM_Core_DAO
::copyGeneric($daoName, $fromCriteria, $newParams);
305 if ($newObject->id
&& $createRecurringEntity) {
306 $object = new $daoName( );
307 foreach ($fromCriteria as $key => $value) {
308 $object->$key = $value;
312 CRM_Core_BAO_RecurringEntity
::quickAdd($object->id
, $newObject->id
, $entityTable);
317 static public function triggerUpdate($obj) {
318 // if DB version is earlier than 4.6 skip any processing
319 static $currentVer = NULL;
321 $currentVer = CRM_Core_BAO_Domain
::version();
323 if (version_compare($currentVer, '4.6.alpha1') < 0) {
327 static $processedEntities = array();
328 if (empty($obj->id
) ||
empty($obj->__table
)) {
331 $key = "{$obj->__table}_{$obj->id}";
333 if (array_key_exists($key, $processedEntities)) {
338 // get related entities
339 $repeatingEntities = self
::getEntitiesFor($obj->id
, $obj->__table
, FALSE, NULL);
340 if (empty($repeatingEntities)) {
341 // return if its not a recurring entity parent
344 // mark being processed
345 $processedEntities[$key] = 1;
347 // to make sure we not copying to source itself
348 unset($repeatingEntities[$key]);
350 foreach($repeatingEntities as $key => $val) {
351 $entityID = $val['id'];
352 $entityTable = $val['table'];
354 $processedEntities[$key] = 1;
356 if (array_key_exists($entityTable, self
::$_tableDAOMapper)) {
357 $daoName = self
::$_tableDAOMapper[$entityTable];
359 // FIXME: generalize me
360 $skipData = array('start_date' => NULL,
364 $updateDAO = CRM_Core_DAO
::cascadeUpdate($daoName, $obj->id
, $entityID, $skipData);
365 CRM_Core_DAO
::freeResult();
367 CRM_Core_Error
::fatal("DAO Mapper missing for $entityTable.");
370 // done with processing. lets unset static var.
371 unset($processedEntities);
374 function mapFormValuesToDB($formParams = array()){
376 if(CRM_Utils_Array
::value('used_for', $formParams)){
377 $dbParams['used_for'] = $formParams['used_for'];
380 if(CRM_Utils_Array
::value('parent_event_id', $formParams)){
381 $dbParams['entity_value'] = $formParams['parent_event_id'];
384 if(CRM_Utils_Array
::value('repetition_start_date', $formParams)) {
385 $repetitionStartDate = $formParams['repetition_start_date'];
386 if (CRM_Utils_Array
::value('repetition_start_date_time', $formParams)){
387 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
389 $repetition_start_date = new DateTime($repetitionStartDate);
390 $repetition_start_date->modify('+1 day');
391 $dbParams['entity_status'] = CRM_Utils_Date
::processDate($repetition_start_date->format('Y-m-d H:i:s'));
394 if(CRM_Utils_Array
::value('repetition_frequency_unit', $formParams)){
395 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
398 if(CRM_Utils_Array
::value('repetition_frequency_interval', $formParams)){
399 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
402 //For Repeats on:(weekly case)
403 if($formParams['repetition_frequency_unit'] == 'week'){
404 if(CRM_Utils_Array
::value('start_action_condition', $formParams)){
405 $repeats_on = CRM_Utils_Array
::value('start_action_condition', $formParams);
406 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
410 //For Repeats By:(monthly case)
411 if($formParams['repetition_frequency_unit'] == 'month'){
412 if($formParams['repeats_by'] == 1){
413 if(CRM_Utils_Array
::value('limit_to', $formParams)){
414 $dbParams['limit_to'] = $formParams['limit_to'];
417 if($formParams['repeats_by'] == 2){
418 if(CRM_Utils_Array
::value('start_action_date_1', $formParams) && CRM_Utils_Array
::value('start_action_date_2', $formParams)){
419 $dbParams['start_action_date'] = $formParams['start_action_date_1']." ".$formParams['start_action_date_2'];
424 //For "Ends" - After:
425 if($formParams['ends'] == 1){
426 if(CRM_Utils_Array
::value('start_action_offset', $formParams)){
427 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
432 if($formParams['ends'] == 2){
433 if(CRM_Utils_Array
::value('repeat_absolute_date', $formParams)){
434 $dbParams['absolute_date'] = CRM_Utils_Date
::processDate($formParams['repeat_absolute_date']);
440 static public function getScheduleReminderDetailsById($scheduleReminderId){
442 FROM civicrm_action_schedule WHERE 1";
443 if($scheduleReminderId){
447 $dao = CRM_Core_DAO
::executeQuery($query,
449 1 => array($scheduleReminderId, 'Integer')
456 function getRecursionFromReminder($scheduleReminderId){
457 if($scheduleReminderId){
458 //Get all the details from schedule reminder table
459 $scheduleReminderDetails = self
::getScheduleReminderDetailsById($scheduleReminderId);
460 $scheduleReminderDetails = (array) $scheduleReminderDetails;
461 $recursionDetails = self
::getRecursionFromReminderByDBParams($scheduleReminderDetails);
463 return $recursionDetails;
466 function getRecursionFromReminderByDBParams($scheduleReminderDetails = array()){
468 //If there is some data for this id
469 if($scheduleReminderDetails['repetition_frequency_unit']){
470 if($scheduleReminderDetails['entity_status']){
471 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['entity_status']));
473 $currDate = date("Y-m-d H:i:s");
475 $start = new DateTime($currDate);
476 if($scheduleReminderDetails['repetition_frequency_unit']){
477 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
478 if($repetition_frequency_unit == "day"){
479 $repetition_frequency_unit = "dai";
481 $repetition_frequency_unit = $repetition_frequency_unit.'ly';
482 $r->recur($start, $repetition_frequency_unit);
485 if($scheduleReminderDetails['repetition_frequency_interval']){
486 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
488 $r->errors
[] = 'Repeats every: is a required field';
492 if($scheduleReminderDetails['repetition_frequency_unit'] == 'week'){
493 if($scheduleReminderDetails['start_action_condition']){
494 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
495 $explodeStartActionCondition = explode(',', $startActionCondition);
496 $buildRuleArray = array();
497 foreach($explodeStartActionCondition as $key => $val){
498 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
500 $r->wkst('MO')->byday($buildRuleArray);
505 if($scheduleReminderDetails['repetition_frequency_unit'] == 'month'){
506 if($scheduleReminderDetails['start_action_date']){
507 $startActionDate = explode(" ", $scheduleReminderDetails['start_action_date']);
508 switch ($startActionDate[0]) {
510 $startActionDate1 = 1;
513 $startActionDate1 = 2;
516 $startActionDate1 = 3;
519 $startActionDate1 = 4;
522 $startActionDate1 = -1;
525 $concatStartActionDateBits = $startActionDate1.strtoupper(substr($startActionDate[1], 0, 2));
526 $r->byday(array($concatStartActionDateBits));
527 }else if($scheduleReminderDetails['limit_to']){
528 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
533 if($scheduleReminderDetails['start_action_offset']){
534 if($scheduleReminderDetails['start_action_offset'] > 30){
535 $r->errors
[] = 'Occurrences should be less than or equal to 30';
537 $r->count($scheduleReminderDetails['start_action_offset']);
540 if(CRM_Utils_Array
::value('absolute_date', $scheduleReminderDetails)) {
541 $absoluteDate = CRM_Utils_Date
::setDateDefaults($scheduleReminderDetails['absolute_date']);
542 $endDate = new DateTime($absoluteDate[0].' '.$absoluteDate[1]);
546 if(!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']){
547 $r->errors
[] = 'Ends: is a required field';
550 $r->errors
[] = 'Repeats: is a required field';
556 * Get Reminder id based on event id
558 static public function getReminderDetailsByEventId($eventId, $used_for){
562 FROM civicrm_action_schedule
563 WHERE entity_value = %1";
565 $query .= " AND used_for = %2";
568 1 => array($eventId, 'Integer'),
569 2 => array($used_for, 'String')
571 $dao = CRM_Core_DAO
::executeQuery($query, $params);
577 static public function getInterval($startDate, $endDate) {
578 if ($startDate && $endDate) {
579 $startDate = new DateTime($startDate);
580 $endDate = new DateTime($endDate);
582 return $startDate->diff($endDate);
586 static public function delEntityRelations($entityId, $entityTable){
587 if(!$entityId && !$entityTable){
590 $parentID = self
::getParentFor($entityId, $entityTable);
592 $dao = new CRM_Core_DAO_RecurringEntity();
593 $dao->parent_id
= $parentID;
594 return $dao->delete();
598 static public function getParticipantCountforEvent($listOfRelatedEntities = array()){
599 if(!empty($listOfRelatedEntities)){
600 $implodeRelatedEntities = implode(',', array_map(function($entity){
601 return $entity['id'];
602 }, $listOfRelatedEntities));
603 if($implodeRelatedEntities){
604 $query = "SELECT p.event_id as event_id,
605 concat_ws(' ', e.title, concat_ws(' - ', DATE_FORMAT(e.start_date, '%b %d %Y %h:%i %p'), DATE_FORMAT(e.end_date, '%b %d %Y %h:%i %p'))) as event_data,
606 count(p.id) as participant_count
607 FROM civicrm_participant p, civicrm_event e
608 WHERE p.event_id = e.id AND p.event_id IN ({$implodeRelatedEntities})
609 GROUP BY p.event_id";
610 $dao = CRM_Core_DAO
::executeQuery($query);
611 $participantDetails = array();
612 while($dao->fetch()) {
613 $participantDetails['countByID'][$dao->event_id
] = $dao->participant_count
;
614 $participantDetails['countByName'][$dao->event_id
][$dao->event_data
] = $dao->participant_count
;
618 return $participantDetails;