Merge branch 'CRM-14696-v2' of https://github.com/JKingsnorth/civicrm-core into CRM...
[civicrm-core.git] / CRM / Core / BAO / RecurringEntity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35
36 require_once 'packages/When/When.php';
37
38 class CRM_Core_BAO_RecurringEntity extends CRM_Core_DAO_RecurringEntity {
39
40 CONST RUNNING = 1;
41 public $schedule = array();
42 public $scheduleId = NULL;
43 public $scheduleFormValues = array();
44
45 public $dateColumns = array();
46 public $overwriteColumns = array();
47 public $intervalDateColumns = array();
48 public $excludeDates = array();
49
50 public $linkedEntities = array();
51
52 public $isRecurringEntityRecord = TRUE;
53
54 protected $recursion = NULL;
55 protected $recursion_start_date = NULL;
56
57 public static $_entitiesToBeDeleted = array();
58
59 public static $status = NULL;
60
61 static $_recurringEntityHelper =
62 array(
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'
67 ),
68 'civicrm_activity' => array(
69 'helper_class' => 'CRM_Activity_DAO_Activity',
70 'delete_func' => 'delete',
71 'pre_delete_func' => ''
72 )
73 );
74
75 static $_dateColumns =
76 array(
77 'civicrm_event' => array(
78 'dateColumns' => array('start_date'),
79 'excludeDateRangeColumns' => array('start_date', 'end_date'),
80 'intervalDateColumns' => array('end_date')
81 ),
82 'civicrm_activity' => array(
83 'dateColumns' => array('activity_date_time'),
84 )
85 );
86
87 static $_tableDAOMapper =
88 array(
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',
96 );
97
98 static $_updateSkipFields =
99 array(
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'),
104 );
105
106 static $_linkedEntitiesInfo =
107 array(
108 'civicrm_tell_friend' => array(
109 'entity_id_col' => 'entity_id',
110 'entity_table_col' => 'entity_table'
111 ),
112 'civicrm_price_set_entity' => array(
113 'entity_id_col' => 'entity_id',
114 'entity_table_col' => 'entity_table',
115 'is_multirecord' => TRUE,
116 ),
117 'civicrm_uf_join' => array(
118 'entity_id_col' => 'entity_id',
119 'entity_table_col' => 'entity_table',
120 'is_multirecord' => TRUE,
121 ),
122 'civicrm_pcp_block' => array(
123 'entity_id_col' => 'entity_id',
124 'entity_table_col' => 'entity_table'
125 ),
126 );
127
128 static function getStatus() {
129 return self::$status;
130 }
131
132 static function setStatus($status) {
133 self::$status = $status;
134 }
135 /**
136 * Save records in civicrm_recujrring_entity table
137 *
138 * @param array $params reference array contains the values submitted by the form
139 *
140 * @access public
141 * @static
142 *
143 * @return object
144 */
145 static function add(&$params) {
146 if (CRM_Utils_Array::value('id', $params)) {
147 CRM_Utils_Hook::pre('edit', 'RecurringEntity', $params['id'], $params);
148 }
149 else {
150 CRM_Utils_Hook::pre('create', 'RecurringEntity', NULL, $params);
151 }
152
153 $daoRecurringEntity = new CRM_Core_DAO_RecurringEntity();
154 $daoRecurringEntity->copyValues($params);
155 $daoRecurringEntity->find(TRUE);
156 $result = $daoRecurringEntity->save();
157
158 if (CRM_Utils_Array::value('id', $params)) {
159 CRM_Utils_Hook::post('edit', 'RecurringEntity', $daoRecurringEntity->id, $daoRecurringEntity);
160 }
161 else {
162 CRM_Utils_Hook::post('create', 'RecurringEntity', $daoRecurringEntity->id, $daoRecurringEntity);
163 }
164 return $result;
165 }
166
167 /**
168 * Wrapper for the function add() to add entry in recurring entity
169 *
170 * @param int $parentId Parent entity id
171 * @param int $entityId Child entity id
172 * @param String $entityTable Name of the entity table
173 *
174 * @access public
175 * @static
176 *
177 * @return object
178 */
179 static function quickAdd($parentId, $entityId, $entityTable) {
180 $params =
181 array(
182 'parent_id' => $parentId,
183 'entity_id' => $entityId,
184 'entity_table' => $entityTable
185 );
186 return self::add($params);
187 }
188
189 /**
190 * This function updates the mode column in the civicrm_recurring_entity table
191 *
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
193 *
194 * @access public
195 *
196 * @return void
197 */
198 function mode($mode) {
199 if ($this->entity_id && $this->entity_table) {
200 if ($this->find(TRUE)) {
201 $this->mode = $mode;
202 }
203 else {
204 $this->parent_id = $this->entity_id;
205 $this->mode = $mode;
206 }
207 $this->save();
208 }
209 }
210
211 /**
212 * This function generates all new entities based on object vars
213 *
214 * @return array
215 */
216 function generate() {
217 $this->generateRecursiveDates();
218
219 return $this->generateEntities();
220 }
221
222 /**
223 * This function builds a "When" object based on schedule/reminder params
224 *
225 * @return object When object
226 */
227 function generateRecursion() {
228 // return if already generated
229 if (is_a($this->recursion, 'When')) {
230 return $this->recursion;
231 }
232
233 if ($this->scheduleId) {
234 // get params by ID
235 $this->schedule = $this->getScheduleParams($this->scheduleId);
236 }
237 else if (!empty($this->scheduleFormValues)) {
238 $this->schedule = $this->mapFormValuesToDB($this->scheduleFormValues);
239 }
240
241 if (!empty($this->schedule)) {
242 $this->recursion = $this->getRecursionFromSchedule($this->schedule);
243 }
244 return $this->recursion;
245 }
246
247 /**
248 * Generate new DAOs and along with entries in civicrm_recurring_entity table
249 *
250 * @return array
251 */
252 function generateEntities() {
253 self::setStatus(self::RUNNING);
254
255 $newEntities = array();
256 $findCriteria = array();
257 if (!empty($this->recursionDates)) {
258 if ($this->entity_id) {
259 $findCriteria = array('id' => $this->entity_id);
260
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;
264 $this->save();
265 }
266 }
267 if (empty($findCriteria)) {
268 CRM_Core_Error::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
269 }
270
271 $count = 0;
272 foreach ($this->recursionDates as $key => $dateCols) {
273 $newCriteria = $dateCols;
274 foreach ($this->overwriteColumns as $col => $val) {
275 $newCriteria[$col] = $val;
276 }
277 // create main entities
278 $obj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($this->entity_table,
279 $findCriteria,
280 $newCriteria,
281 $this->isRecurringEntityRecord
282 );
283
284 if (is_a($obj, 'CRM_Core_DAO') && $obj->id) {
285 $newCriteria = array();
286 $newEntities[$this->entity_table][$count] = $obj->id;
287
288 foreach ($this->linkedEntities as $linkedInfo) {
289 foreach ($linkedInfo['linkedColumns'] as $col) {
290 $newCriteria[$col] = $obj->id;
291 }
292 // create linked entities
293 $linkedObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($linkedInfo['table'],
294 $linkedInfo['findCriteria'],
295 $newCriteria,
296 CRM_Utils_Array::value('isRecurringEntityRecord', $linkedInfo, TRUE)
297 );
298
299 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id) {
300 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id;
301 }
302 }
303 }
304 $count++;
305 }
306 }
307
308 self::$status = NULL;
309 return $newEntities;
310 }
311
312 /**
313 * This function iterates through when object criterias and
314 * generates recursive dates based on that
315 *
316 * @return array array of dates
317 */
318 function generateRecursiveDates() {
319 $this->generateRecursion();
320
321 $recursionDates = array();
322 if (is_a($this->recursion, 'When')) {
323 $initialCount = CRM_Utils_Array::value('start_action_offset', $this->schedule);
324
325 $exRangeStart = $exRangeEnd = NULL;
326 if (!empty($this->excludeDateRangeColumns)) {
327 $exRangeStart = $this->excludeDateRangeColumns[0];
328 $exRangeEnd = $this->excludeDateRangeColumns[1];
329 }
330
331 $count = 1;
332 while ($result = $this->recursion->next()) {
333 $skip = FALSE;
334 if ($result == $this->recursion_start_date) {
335 // skip the recursion-start-date from the list we going to generate
336 $skip = TRUE;
337 }
338 $baseDate = CRM_Utils_Date::processDate($result->format('Y-m-d H:i:s'));
339
340 foreach ($this->dateColumns as $col) {
341 $recursionDates[$count][$col] = $baseDate;
342 }
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'));
347 }
348 if ($exRangeStart) {
349 $exRangeStartDate = CRM_Utils_Date::processDate($recursionDates[$count][$exRangeStart], NULL, FALSE, 'Ymd');
350 $exRangeEndDate = CRM_Utils_Date::processDate($recursionDates[$count][$exRangeEnd], NULL, FALSE, 'Ymd');
351 }
352
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')) {
357 $skip = TRUE;
358 break;
359 }
360 }
361 else {
362 if (($exDate == $exRangeStartDate) ||
363 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
364 ) {
365 $skip = TRUE;
366 break;
367 }
368 }
369 }
370
371 if ($skip) {
372 unset($recursionDates[$count]);
373 if ($initialCount && ($initialCount > 0)) {
374 // lets increase the counter, so we get correct number of occurrences
375 $initialCount++;
376 $this->recursion->count($initialCount);
377 }
378 continue;
379 }
380 $count++;
381 }
382 }
383 $this->recursionDates = $recursionDates;
384
385 return $recursionDates;
386 }
387
388 /**
389 * This function gets all the children for a particular parent entity
390 *
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
396 *
397 * @access public
398 * @static
399 *
400 * @return array an array of child ids
401 */
402 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
403 $entities = array();
404 if (empty($parentId) || empty($entityTable)) {
405 return $entities;
406 }
407
408 if (!$initiatorId) {
409 $initiatorId = $parentId;
410 }
411
412 $queryParams = array(
413 1 => array($parentId, 'Integer'),
414 2 => array($entityTable, 'String'),
415 3 => array($initiatorId, 'Integer'),
416 );
417
418 if (!$mode) {
419 $mode = CRM_Core_DAO::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
420 }
421
422 $query = "SELECT *
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");
427 }
428
429 if ($mode == '1') { // MODE = SINGLE
430 $query .= " AND entity_id = %3";
431 }
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');
438 }
439 else {
440 // something wrong, return empty
441 return array();
442 }
443 }
444
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;
449 }
450 return $entities;
451 }
452
453 /**
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.
456 *
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.
461 *
462 * @access public
463 * @static
464 *
465 * @return array array of connected ids
466 */
467 static public function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
468 $parentId = self::getParentFor($entityId, $entityTable);
469 if ($parentId) {
470 return self::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
471 }
472 return array();
473 }
474
475 /**
476 * This function gets the parent for the entity id passed to it
477 *
478 * @param int $entityId entity ID
479 * @param string $entityTable Entity table name
480 * @param boolean $includeParent Include parent in result set
481 *
482 * @access public
483 * @static
484 *
485 * @return int unsigned $parentId Parent ID
486 */
487 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
488 if (empty($entityId) || empty($entityTable)) {
489 return NULL;
490 }
491
492 $query = "
493 SELECT parent_id
494 FROM civicrm_recurring_entity
495 WHERE entity_id = %1 AND entity_table = %2";
496 if (!$includeParent) {
497 $query .= " AND parent_id != %1";
498 }
499 $parentId =
500 CRM_Core_DAO::singleValueQuery($query,
501 array(
502 1 => array($entityId, 'Integer'),
503 2 => array($entityTable, 'String'),
504 )
505 );
506 return $parentId;
507 }
508
509 /**
510 * This function copies the information from parent entity and creates other entities with same information
511 *
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
516 *
517 * @access public
518 * @static
519 *
520 * @return object
521 */
522 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
523 $daoName = self::$_tableDAOMapper[$entityTable];
524 if (!$daoName) {
525 CRM_Core_Error::fatal("DAO Mapper missing for $entityTable.");
526 }
527 $newObject = CRM_Core_DAO::copyGeneric($daoName, $fromCriteria, $newParams);
528
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;
533 }
534 $object->find(TRUE);
535
536 CRM_Core_BAO_RecurringEntity::quickAdd($object->id, $newObject->id, $entityTable);
537 }
538 return $newObject;
539 }
540
541 /**
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
544 *
545 * @param object $event An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated
546 *
547 * @access public
548 * @static
549 *
550 * @return void
551 */
552 static public function triggerUpdate($event) {
553 // if DB version is earlier than 4.6 skip any processing
554 static $currentVer = NULL;
555 if (!$currentVer) {
556 $currentVer = CRM_Core_BAO_Domain::version();
557 }
558 if (version_compare($currentVer, '4.6.alpha1') < 0) {
559 return;
560 }
561
562 static $processedEntities = array();
563 $obj =& $event->object;
564 if (empty($obj->id) || empty($obj->__table)) {
565 return FALSE;
566 }
567 $key = "{$obj->__table}_{$obj->id}";
568
569 if (array_key_exists($key, $processedEntities)) {
570 // already processed
571 return NULL;
572 }
573
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
578 return NULL;
579 }
580 // mark being processed
581 $processedEntities[$key] = 1;
582
583 // to make sure we not copying to source itself
584 unset($repeatingEntities[$key]);
585
586 foreach($repeatingEntities as $key => $val) {
587 $entityID = $val['id'];
588 $entityTable = $val['table'];
589
590 $processedEntities[$key] = 1;
591
592 if (array_key_exists($entityTable, self::$_tableDAOMapper)) {
593 $daoName = self::$_tableDAOMapper[$entityTable];
594
595 $skipData = array();
596 if (array_key_exists($entityTable, self::$_updateSkipFields)) {
597 $skipFields = self::$_updateSkipFields[$entityTable];
598 foreach ($skipFields as $sfield) {
599 $skipData[$sfield] = NULL;
600 }
601 }
602
603 $updateDAO = CRM_Core_DAO::cascadeUpdate($daoName, $obj->id, $entityID, $skipData);
604 CRM_Core_DAO::freeResult();
605 }
606 else {
607 CRM_Core_Error::fatal("DAO Mapper missing for $entityTable.");
608 }
609 }
610 // done with processing. lets unset static var.
611 unset($processedEntities);
612 }
613
614 /**
615 * This function acts as a listener to dao->save,
616 * and creates entries for linked entities in recurring entity table
617 *
618 * @param object $event An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted
619 *
620 * @access public
621 * @static
622 *
623 * @return void
624 */
625 static public function triggerInsert($event) {
626 $obj =& $event->object;
627 if (!array_key_exists($obj->__table, self::$_linkedEntitiesInfo)) {
628 return FALSE;
629 }
630
631 // if DB version is earlier than 4.6 skip any processing
632 static $currentVer = NULL;
633 if (!$currentVer) {
634 $currentVer = CRM_Core_BAO_Domain::version();
635 }
636 if (version_compare($currentVer, '4.6.alpha1') < 0) {
637 return;
638 }
639
640 static $processedEntities = array();
641 if (empty($obj->id) || empty($obj->__table)) {
642 return FALSE;
643 }
644 $key = "{$obj->__table}_{$obj->id}";
645
646 if (array_key_exists($key, $processedEntities)) {
647 // already being processed. Exit recursive calls.
648 return NULL;
649 }
650
651 if (self::getStatus() == self::RUNNING) {
652 // if recursion->generate() is doing some work, lets not intercept
653 return NULL;
654 }
655
656 // mark being processed
657 $processedEntities[$key] = 1;
658
659 // get related entities for table being saved
660 $hasaRecurringRecord = self::getParentFor($obj->id, $obj->__table);
661
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'];
671
672 $pEntityID = $linkedDAO->$idCol;
673 $pEntityTable = $linkedDAO->$tableCol;
674
675 // find all parent recurring entity set
676 $pRepeatingEntities = self::getEntitiesFor($pEntityID, $pEntityTable);
677
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
681
682 foreach($pRepeatingEntities as $key => $val) {
683 if (array_key_exists($key, $processedEntities)) {
684 // this graph is already being processed
685 return NULL;
686 }
687 $processedEntities[$key] = 1;
688 }
689
690 // start with first entry with just itself
691 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $obj->id, $obj->__table);
692
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);
699 }
700 else {
701 // linked entity doesn't exist. lets create them
702 $newCriteria = array(
703 $idCol => $val['id'],
704 $tableCol => $val['table']
705 );
706 $linkedObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($obj->__table,
707 array('id' => $obj->id),
708 $newCriteria,
709 TRUE
710 );
711 if ($linkedObj->id) {
712 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $linkedObj->id, $obj->__table);
713 }
714 }
715 }
716 }
717 }
718 }
719 }
720
721 // done with processing. lets unset static var.
722 unset($processedEntities);
723 }
724
725 /**
726 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
727 *
728 * @param object $event An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted
729 *
730 * @access public
731 * @static
732 *
733 * @return void
734 */
735 static public function triggerDelete($event) {
736 $obj =& $event->object;
737
738 // if DB version is earlier than 4.6 skip any processing
739 static $currentVer = NULL;
740 if (!$currentVer) {
741 $currentVer = CRM_Core_BAO_Domain::version();
742 }
743 if (version_compare($currentVer, '4.6.alpha1') < 0) {
744 return;
745 }
746
747 static $processedEntities = array();
748 if (empty($obj->id) || empty($obj->__table) || !$event->result) {
749 return FALSE;
750 }
751 $key = "{$obj->__table}_{$obj->id}";
752
753 if (array_key_exists($key, $processedEntities)) {
754 // already processed
755 return NULL;
756 }
757
758 // mark being processed
759 $processedEntities[$key] = 1;
760
761 $parentID = self::getParentFor($obj->id, $obj->__table);
762 if ($parentID) {
763 CRM_Core_BAO_RecurringEntity::delEntity($obj->id, $obj->__table, TRUE);
764 }
765 }
766
767 /**
768 * This function deletes main entity and related linked entities from recurring-entity table
769 *
770 * @param int $entityId Entity id
771 * @param string $entityTable Name of the entity table
772 *
773 * @access public
774 * @static
775 *
776 * @return boolean|object Returns either boolean value or CRM_Core_DAO_RecurringEntity object
777 */
778 static public function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
779 if (empty($entityId) || empty($entityTable)) {
780 return FALSE;
781 }
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];
791 if (!$daoName) {
792 CRM_Core_Error::fatal("DAO Mapper missing for $linkedTable.");
793 }
794
795 $linkedDao = new $daoName();
796 $linkedDao->$linfo['entity_id_col'] = $entityId;
797 $linkedDao->$linfo['entity_table_col'] = $entityTable;
798 $linkedDao->find();
799 while ($linkedDao->fetch()) {
800 CRM_Core_BAO_RecurringEntity::delEntity($linkedDao->id, $linkedTable, FALSE);
801 }
802 }
803 }
804 // delete main entity
805 return $dao->delete();
806 }
807 return FALSE;
808 }
809
810 /**
811 * This function maps values posted from form to civicrm_action_schedule columns
812 *
813 * @param array $formParams and array of form values posted
814 *
815 * @return array
816 */
817 function mapFormValuesToDB($formParams = array()) {
818 $dbParams = array();
819 if (CRM_Utils_Array::value('used_for', $formParams)) {
820 $dbParams['used_for'] = $formParams['used_for'];
821 }
822
823 if (CRM_Utils_Array::value('entity_id', $formParams)) {
824 $dbParams['entity_value'] = $formParams['entity_id'];
825 }
826
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'];
830 }
831 else {
832 $repetitionStartDate = $formParams['repetition_start_date'];
833 }
834 if (CRM_Utils_Array::value('repetition_start_date_time', $formParams)) {
835 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
836 }
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'));
839 }
840
841 if (CRM_Utils_Array::value('repetition_frequency_unit', $formParams)) {
842 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
843 }
844
845 if (CRM_Utils_Array::value('repetition_frequency_interval', $formParams)) {
846 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
847 }
848
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));
854 }
855 }
856
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'];
862 }
863 }
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'];
867 }
868 }
869 }
870
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'];
875 }
876 }
877
878 //For "Ends" - On:
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']);
882 }
883 }
884 return $dbParams;
885 }
886
887 /**
888 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
889 *
890 * @param int $scheduleReminderId primary key of civicrm_action_schedule table
891 *
892 * @access public
893 * @static
894 *
895 * @return object
896 */
897 static public function getScheduleReminderDetailsById($scheduleReminderId) {
898 $query = "SELECT *
899 FROM civicrm_action_schedule WHERE 1";
900 if ($scheduleReminderId) {
901 $query .= "
902 AND id = %1";
903 }
904 $dao = CRM_Core_DAO::executeQuery($query,
905 array(
906 1 => array($scheduleReminderId, 'Integer')
907 )
908 );
909 $dao->fetch();
910 return $dao;
911 }
912
913 /**
914 * This function is a wrapper of getScheduleReminderDetailsById function
915 *
916 * @param int $scheduleReminderId primary key of civicrm_action_schedule table
917 *
918 * @return array
919 */
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;
926 }
927 return $scheduleReminderDetails;
928 }
929
930 /**
931 * This function takes criterias saved in civicrm_action_schedule table
932 * and creates recursion rule
933 *
934 * @param array $scheduleReminderDetails array of repeat criterias saved in civicrm_action_schedule table
935 *
936 * @return object When object
937 */
938 function getRecursionFromSchedule($scheduleReminderDetails = array()) {
939 $r = new When();
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']));
944 }
945 else {
946 $currDate = date("Y-m-d H:i:s");
947 }
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";
954 }
955 $repetition_frequency_unit = $repetition_frequency_unit.'ly';
956 $r->recur($start, $repetition_frequency_unit);
957 }
958
959 if ($scheduleReminderDetails['repetition_frequency_interval']) {
960 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
961 }
962 else {
963 $r->errors[] = 'Repeats every: is a required field';
964 }
965
966 //week
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));
974 }
975 $r->wkst('MO')->byday($buildRuleArray);
976 }
977 }
978
979 //month
980 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
981 if ($scheduleReminderDetails['entity_status']) {
982 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
983 switch ($startActionDate[0]) {
984 case 'first':
985 $startActionDate1 = 1;
986 break;
987 case 'second':
988 $startActionDate1 = 2;
989 break;
990 case 'third':
991 $startActionDate1 = 3;
992 break;
993 case 'fourth':
994 $startActionDate1 = 4;
995 break;
996 case 'last':
997 $startActionDate1 = -1;
998 break;
999 }
1000 $concatStartActionDateBits = $startActionDate1.strtoupper(substr($startActionDate[1], 0, 2));
1001 $r->byday(array($concatStartActionDateBits));
1002 }
1003 else if ($scheduleReminderDetails['limit_to']) {
1004 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
1005 }
1006 }
1007
1008 //Ends
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';
1012 }
1013 $r->count($scheduleReminderDetails['start_action_offset']);
1014 }
1015
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);
1021 }
1022
1023 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1024 $r->errors[] = 'Ends: is a required field';
1025 }
1026 }
1027 else {
1028 $r->errors[] = 'Repeats: is a required field';
1029 }
1030 return $r;
1031 }
1032
1033
1034 /**
1035 * This function gets time difference between the two datetime object
1036 *
1037 * @param DateTime $startDate Start Date
1038 * @param DateTime $endDate End Date
1039 *
1040 * @access public
1041 * @static
1042 *
1043 * @return object DateTime object which contain time difference
1044 */
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);
1050 }
1051 }
1052
1053 /**
1054 * This function gets all columns from civicrm_action_schedule on the basis of event id
1055 *
1056 * @param int $entityId Entity ID
1057 * @param string $used_for Specifies for which entity type it's used for
1058 *
1059 * @access public
1060 * @static
1061 *
1062 * @return object
1063 */
1064 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1065 if ($entityId) {
1066 $query = "
1067 SELECT *
1068 FROM civicrm_action_schedule
1069 WHERE entity_value = %1";
1070 if ($used_for) {
1071 $query .= " AND used_for = %2";
1072 }
1073 $params = array(
1074 1 => array($entityId, 'Integer'),
1075 2 => array($used_for, 'String')
1076 );
1077 $dao = CRM_Core_DAO::executeQuery($query, $params);
1078 $dao->fetch();
1079 }
1080 return $dao;
1081 }
1082
1083 /**
1084 * Update mode column in civicrm_recurring_entity table for event related tabs
1085 *
1086 * @param int $entityId event id
1087 * @param string $linkedEntityTable Linked entity table name for this event
1088 * @return array
1089 */
1090 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1091 $result = array();
1092 if ( $entityId && $linkedEntityTable && $mainEntityTable ) {
1093 if (CRM_Utils_Array::value($linkedEntityTable, self::$_tableDAOMapper)) {
1094 $dao = self::$_tableDAOMapper[$linkedEntityTable];
1095 }
1096 else {
1097 CRM_Core_Session::setStatus('Could not update mode for linked entities');
1098 return;
1099 }
1100 $entityTable = $linkedEntityTable;
1101 $params = array(
1102 'entity_id' => $entityId,
1103 'entity_table' => $mainEntityTable
1104 );
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;
1110 }
1111 }
1112 return $result;
1113 }
1114 }