INFRA-132 - SpacingAfterBeak
[civicrm-core.git] / CRM / Core / BAO / RecurringEntity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 public static function getStatus() {
129 return self::$status;
130 }
131
132 public static function setStatus($status) {
133 self::$status = $status;
134 }
135 /**
136 * Save records in civicrm_recujrring_entity table
137 *
138 * @param array $params
139 * Reference array contains the values submitted by the form .
140 *
141 * @static
142 *
143 * @return object
144 */
145 public 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
171 * Parent entity id .
172 * @param int $entityId
173 * Child entity id .
174 * @param string $entityTable
175 * Name of the entity table .
176 *
177 * @static
178 *
179 * @return object
180 */
181 public static function quickAdd($parentId, $entityId, $entityTable) {
182 $params =
183 array(
184 'parent_id' => $parentId,
185 'entity_id' => $entityId,
186 'entity_table' => $entityTable
187 );
188 return self::add($params);
189 }
190
191 /**
192 * This function updates the mode column in the civicrm_recurring_entity table
193 *
194 * @param int $mode
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 .
196 *
197 *
198 * @return void
199 */
200 public function mode($mode) {
201 if ($this->entity_id && $this->entity_table) {
202 if ($this->find(TRUE)) {
203 $this->mode = $mode;
204 }
205 else {
206 $this->parent_id = $this->entity_id;
207 $this->mode = $mode;
208 }
209 $this->save();
210 }
211 }
212
213 /**
214 * This function generates all new entities based on object vars
215 *
216 * @return array
217 */
218 public function generate() {
219 $this->generateRecursiveDates();
220
221 return $this->generateEntities();
222 }
223
224 /**
225 * This function builds a "When" object based on schedule/reminder params
226 *
227 * @return object
228 * When object
229 */
230 public function generateRecursion() {
231 // return if already generated
232 if (is_a($this->recursion, 'When')) {
233 return $this->recursion;
234 }
235
236 if ($this->scheduleId) {
237 // get params by ID
238 $this->schedule = $this->getScheduleParams($this->scheduleId);
239 }
240 elseif (!empty($this->scheduleFormValues)) {
241 $this->schedule = $this->mapFormValuesToDB($this->scheduleFormValues);
242 }
243
244 if (!empty($this->schedule)) {
245 $this->recursion = $this->getRecursionFromSchedule($this->schedule);
246 }
247 return $this->recursion;
248 }
249
250 /**
251 * Generate new DAOs and along with entries in civicrm_recurring_entity table
252 *
253 * @return array
254 */
255 public function generateEntities() {
256 self::setStatus(self::RUNNING);
257
258 $newEntities = array();
259 $findCriteria = array();
260 if (!empty($this->recursionDates)) {
261 if ($this->entity_id) {
262 $findCriteria = array('id' => $this->entity_id);
263
264 // save an entry with initiating entity-id & entity-table
265 if ($this->entity_table && !$this->find(TRUE)) {
266 $this->parent_id = $this->entity_id;
267 $this->save();
268 }
269 }
270 if (empty($findCriteria)) {
271 CRM_Core_Error::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
272 }
273
274 $count = 0;
275 foreach ($this->recursionDates as $key => $dateCols) {
276 $newCriteria = $dateCols;
277 foreach ($this->overwriteColumns as $col => $val) {
278 $newCriteria[$col] = $val;
279 }
280 // create main entities
281 $obj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($this->entity_table,
282 $findCriteria,
283 $newCriteria,
284 $this->isRecurringEntityRecord
285 );
286
287 if (is_a($obj, 'CRM_Core_DAO') && $obj->id) {
288 $newCriteria = array();
289 $newEntities[$this->entity_table][$count] = $obj->id;
290
291 foreach ($this->linkedEntities as $linkedInfo) {
292 foreach ($linkedInfo['linkedColumns'] as $col) {
293 $newCriteria[$col] = $obj->id;
294 }
295 // create linked entities
296 $linkedObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($linkedInfo['table'],
297 $linkedInfo['findCriteria'],
298 $newCriteria,
299 CRM_Utils_Array::value('isRecurringEntityRecord', $linkedInfo, TRUE)
300 );
301
302 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id) {
303 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id;
304 }
305 }
306 }
307 $count++;
308 }
309 }
310
311 self::$status = NULL;
312 return $newEntities;
313 }
314
315 /**
316 * This function iterates through when object criterias and
317 * generates recursive dates based on that
318 *
319 * @return array
320 * array of dates
321 */
322 public function generateRecursiveDates() {
323 $this->generateRecursion();
324
325 $recursionDates = array();
326 if (is_a($this->recursion, 'When')) {
327 $initialCount = CRM_Utils_Array::value('start_action_offset', $this->schedule);
328
329 $exRangeStart = $exRangeEnd = NULL;
330 if (!empty($this->excludeDateRangeColumns)) {
331 $exRangeStart = $this->excludeDateRangeColumns[0];
332 $exRangeEnd = $this->excludeDateRangeColumns[1];
333 }
334
335 $count = 1;
336 while ($result = $this->recursion->next()) {
337 $skip = FALSE;
338 if ($result == $this->recursion_start_date) {
339 // skip the recursion-start-date from the list we going to generate
340 $skip = TRUE;
341 }
342 $baseDate = CRM_Utils_Date::processDate($result->format('Y-m-d H:i:s'));
343
344 foreach ($this->dateColumns as $col) {
345 $recursionDates[$count][$col] = $baseDate;
346 }
347 foreach ($this->intervalDateColumns as $col => $interval) {
348 $newDate = new DateTime($baseDate);
349 $newDate->add($interval);
350 $recursionDates[$count][$col] = CRM_Utils_Date::processDate($newDate->format('Y-m-d H:i:s'));
351 }
352 if ($exRangeStart) {
353 $exRangeStartDate = CRM_Utils_Date::processDate($recursionDates[$count][$exRangeStart], NULL, FALSE, 'Ymd');
354 $exRangeEndDate = CRM_Utils_Date::processDate($recursionDates[$count][$exRangeEnd], NULL, FALSE, 'Ymd');
355 }
356
357 foreach ($this->excludeDates as $exDate) {
358 $exDate = CRM_Utils_Date::processDate($exDate, NULL, FALSE, 'Ymd');
359 if (!$exRangeStart) {
360 if ($exDate == $result->format('Ymd')) {
361 $skip = TRUE;
362 break;
363 }
364 }
365 else {
366 if (($exDate == $exRangeStartDate) ||
367 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
368 ) {
369 $skip = TRUE;
370 break;
371 }
372 }
373 }
374
375 if ($skip) {
376 unset($recursionDates[$count]);
377 if ($initialCount && ($initialCount > 0)) {
378 // lets increase the counter, so we get correct number of occurrences
379 $initialCount++;
380 $this->recursion->count($initialCount);
381 }
382 continue;
383 }
384 $count++;
385 }
386 }
387 $this->recursionDates = $recursionDates;
388
389 return $recursionDates;
390 }
391
392 /**
393 * This function gets all the children for a particular parent entity
394 *
395 * @param int $parentId
396 * Parent entity id .
397 * @param string $entityTable
398 * Name of the entity table .
399 * @param bool $includeParent
400 * If true parent id is included in result set and vice versa .
401 * @param int $mode
402 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
403 * @param int $initiatorId
404 * The instance where this function is invoked from .
405 *
406 * @static
407 *
408 * @return array
409 * an array of child ids
410 */
411 static public function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
412 $entities = array();
413 if (empty($parentId) || empty($entityTable)) {
414 return $entities;
415 }
416
417 if (!$initiatorId) {
418 $initiatorId = $parentId;
419 }
420
421 $queryParams = array(
422 1 => array($parentId, 'Integer'),
423 2 => array($entityTable, 'String'),
424 3 => array($initiatorId, 'Integer'),
425 );
426
427 if (!$mode) {
428 $mode = CRM_Core_DAO::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
429 }
430
431 $query = "SELECT *
432 FROM civicrm_recurring_entity
433 WHERE parent_id = %1 AND entity_table = %2";
434 if (!$includeParent) {
435 $query .= " AND entity_id != " . ($initiatorId ? "%3" : "%1");
436 }
437
438 if ($mode == '1') { // MODE = SINGLE
439 $query .= " AND entity_id = %3";
440 }
441 elseif ($mode == '2') { // MODE = FUTURE
442 $recurringEntityID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
443 if ($recurringEntityID) {
444 $query .= $includeParent ? " AND id >= %4" : " AND id > %4";
445 $query .= " ORDER BY id ASC"; // FIXME: change to order by dates
446 $queryParams[4] = array($recurringEntityID, 'Integer');
447 }
448 else {
449 // something wrong, return empty
450 return array();
451 }
452 }
453
454 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
455 while ($dao->fetch()) {
456 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table;
457 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id;
458 }
459 return $entities;
460 }
461
462 /**
463 * This function when passed an entity id checks if it has parent and
464 * returns all other entities that are connected to same parent.
465 *
466 * @param int $entityId
467 * Entity id .
468 * @param string $entityTable
469 * Entity table name .
470 * @param bool $includeParent
471 * Include parent in result set .
472 * @param int $mode
473 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
474 *
475 * @static
476 *
477 * @return array
478 * array of connected ids
479 */
480 static public function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
481 $parentId = self::getParentFor($entityId, $entityTable);
482 if ($parentId) {
483 return self::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
484 }
485 return array();
486 }
487
488 /**
489 * This function gets the parent for the entity id passed to it
490 *
491 * @param int $entityId
492 * Entity ID .
493 * @param string $entityTable
494 * Entity table name .
495 * @param bool $includeParent
496 * Include parent in result set .
497 *
498 * @static
499 *
500 * @return int
501 * unsigned $parentId Parent ID
502 */
503 static public function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
504 if (empty($entityId) || empty($entityTable)) {
505 return NULL;
506 }
507
508 $query = "
509 SELECT parent_id
510 FROM civicrm_recurring_entity
511 WHERE entity_id = %1 AND entity_table = %2";
512 if (!$includeParent) {
513 $query .= " AND parent_id != %1";
514 }
515 $parentId =
516 CRM_Core_DAO::singleValueQuery($query,
517 array(
518 1 => array($entityId, 'Integer'),
519 2 => array($entityTable, 'String'),
520 )
521 );
522 return $parentId;
523 }
524
525 /**
526 * This function copies the information from parent entity and creates other entities with same information
527 *
528 * @param string $entityTable
529 * Entity table name .
530 * @param array $fromCriteria
531 * Array of all the fields & values on which basis to copy .
532 * @param array $newParams
533 * Array of all the fields & values to be copied besides the other fields .
534 * @param bool $createRecurringEntity
535 * If to create a record in recurring_entity table .
536 *
537 * @static
538 *
539 * @return object
540 */
541 static public function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
542 $daoName = self::$_tableDAOMapper[$entityTable];
543 if (!$daoName) {
544 CRM_Core_Error::fatal("DAO Mapper missing for $entityTable.");
545 }
546 $newObject = CRM_Core_DAO::copyGeneric($daoName, $fromCriteria, $newParams);
547
548 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id && $createRecurringEntity) {
549 $object = new $daoName( );
550 foreach ($fromCriteria as $key => $value) {
551 $object->$key = $value;
552 }
553 $object->find(TRUE);
554
555 CRM_Core_BAO_RecurringEntity::quickAdd($object->id, $newObject->id, $entityTable);
556 }
557 return $newObject;
558 }
559
560 /**
561 * This function acts as a listener to dao->update whenever there is an update,
562 * and propagates any changes to all related entities present in recurring entity table
563 *
564 * @param object $event
565 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated .
566 *
567 * @static
568 *
569 * @return void
570 */
571 static public function triggerUpdate($event) {
572 // if DB version is earlier than 4.6 skip any processing
573 static $currentVer = NULL;
574 if (!$currentVer) {
575 $currentVer = CRM_Core_BAO_Domain::version();
576 }
577 if (version_compare($currentVer, '4.6.alpha1') < 0) {
578 return;
579 }
580
581 static $processedEntities = array();
582 $obj =& $event->object;
583 if (empty($obj->id) || empty($obj->__table)) {
584 return FALSE;
585 }
586 $key = "{$obj->__table}_{$obj->id}";
587
588 if (array_key_exists($key, $processedEntities)) {
589 // already processed
590 return NULL;
591 }
592
593 // get related entities
594 $repeatingEntities = self::getEntitiesFor($obj->id, $obj->__table, FALSE, NULL);
595 if (empty($repeatingEntities)) {
596 // return if its not a recurring entity parent
597 return NULL;
598 }
599 // mark being processed
600 $processedEntities[$key] = 1;
601
602 // to make sure we not copying to source itself
603 unset($repeatingEntities[$key]);
604
605 foreach ($repeatingEntities as $key => $val) {
606 $entityID = $val['id'];
607 $entityTable = $val['table'];
608
609 $processedEntities[$key] = 1;
610
611 if (array_key_exists($entityTable, self::$_tableDAOMapper)) {
612 $daoName = self::$_tableDAOMapper[$entityTable];
613
614 $skipData = array();
615 if (array_key_exists($entityTable, self::$_updateSkipFields)) {
616 $skipFields = self::$_updateSkipFields[$entityTable];
617 foreach ($skipFields as $sfield) {
618 $skipData[$sfield] = NULL;
619 }
620 }
621
622 $updateDAO = CRM_Core_DAO::cascadeUpdate($daoName, $obj->id, $entityID, $skipData);
623 CRM_Core_DAO::freeResult();
624 }
625 else {
626 CRM_Core_Error::fatal("DAO Mapper missing for $entityTable.");
627 }
628 }
629 // done with processing. lets unset static var.
630 unset($processedEntities);
631 }
632
633 /**
634 * This function acts as a listener to dao->save,
635 * and creates entries for linked entities in recurring entity table
636 *
637 * @param object $event
638 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted .
639 *
640 * @static
641 *
642 * @return void
643 */
644 static public function triggerInsert($event) {
645 $obj =& $event->object;
646 if (!array_key_exists($obj->__table, self::$_linkedEntitiesInfo)) {
647 return FALSE;
648 }
649
650 // if DB version is earlier than 4.6 skip any processing
651 static $currentVer = NULL;
652 if (!$currentVer) {
653 $currentVer = CRM_Core_BAO_Domain::version();
654 }
655 if (version_compare($currentVer, '4.6.alpha1') < 0) {
656 return;
657 }
658
659 static $processedEntities = array();
660 if (empty($obj->id) || empty($obj->__table)) {
661 return FALSE;
662 }
663 $key = "{$obj->__table}_{$obj->id}";
664
665 if (array_key_exists($key, $processedEntities)) {
666 // already being processed. Exit recursive calls.
667 return NULL;
668 }
669
670 if (self::getStatus() == self::RUNNING) {
671 // if recursion->generate() is doing some work, lets not intercept
672 return NULL;
673 }
674
675 // mark being processed
676 $processedEntities[$key] = 1;
677
678 // get related entities for table being saved
679 $hasaRecurringRecord = self::getParentFor($obj->id, $obj->__table);
680
681 if (empty($hasaRecurringRecord)) {
682 // check if its a linked entity
683 if (array_key_exists($obj->__table, self::$_linkedEntitiesInfo) &&
684 !CRM_Utils_Array::value('is_multirecord', self::$_linkedEntitiesInfo[$obj->__table])) {
685 $linkedDAO = new self::$_tableDAOMapper[$obj->__table]();
686 $linkedDAO->id = $obj->id;
687 if ($linkedDAO->find(TRUE)) {
688 $idCol = self::$_linkedEntitiesInfo[$obj->__table]['entity_id_col'];
689 $tableCol = self::$_linkedEntitiesInfo[$obj->__table]['entity_table_col'];
690
691 $pEntityID = $linkedDAO->$idCol;
692 $pEntityTable = $linkedDAO->$tableCol;
693
694 // find all parent recurring entity set
695 $pRepeatingEntities = self::getEntitiesFor($pEntityID, $pEntityTable);
696
697 if (!empty($pRepeatingEntities)) {
698 // for each parent entity in the set, find out a similar linked entity,
699 // if doesn't exist create one, and also create entries in recurring_entity table
700
701 foreach ($pRepeatingEntities as $key => $val) {
702 if (array_key_exists($key, $processedEntities)) {
703 // this graph is already being processed
704 return NULL;
705 }
706 $processedEntities[$key] = 1;
707 }
708
709 // start with first entry with just itself
710 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $obj->id, $obj->__table);
711
712 foreach ($pRepeatingEntities as $key => $val) {
713 $rlinkedDAO = new self::$_tableDAOMapper[$obj->__table]();
714 $rlinkedDAO->$idCol = $val['id'];
715 $rlinkedDAO->$tableCol = $val['table'];
716 if ($rlinkedDAO->find(TRUE)) {
717 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $rlinkedDAO->id, $obj->__table);
718 }
719 else {
720 // linked entity doesn't exist. lets create them
721 $newCriteria = array(
722 $idCol => $val['id'],
723 $tableCol => $val['table']
724 );
725 $linkedObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($obj->__table,
726 array('id' => $obj->id),
727 $newCriteria,
728 TRUE
729 );
730 if ($linkedObj->id) {
731 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $linkedObj->id, $obj->__table);
732 }
733 }
734 }
735 }
736 }
737 }
738 }
739
740 // done with processing. lets unset static var.
741 unset($processedEntities);
742 }
743
744 /**
745 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
746 *
747 * @param object $event
748 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted .
749 *
750 * @static
751 *
752 * @return void
753 */
754 static public function triggerDelete($event) {
755 $obj =& $event->object;
756
757 // if DB version is earlier than 4.6 skip any processing
758 static $currentVer = NULL;
759 if (!$currentVer) {
760 $currentVer = CRM_Core_BAO_Domain::version();
761 }
762 if (version_compare($currentVer, '4.6.alpha1') < 0) {
763 return;
764 }
765
766 static $processedEntities = array();
767 if (empty($obj->id) || empty($obj->__table) || !$event->result) {
768 return FALSE;
769 }
770 $key = "{$obj->__table}_{$obj->id}";
771
772 if (array_key_exists($key, $processedEntities)) {
773 // already processed
774 return NULL;
775 }
776
777 // mark being processed
778 $processedEntities[$key] = 1;
779
780 $parentID = self::getParentFor($obj->id, $obj->__table);
781 if ($parentID) {
782 CRM_Core_BAO_RecurringEntity::delEntity($obj->id, $obj->__table, TRUE);
783 }
784 }
785
786 /**
787 * This function deletes main entity and related linked entities from recurring-entity table
788 *
789 * @param int $entityId
790 * Entity id .
791 * @param string $entityTable
792 * Name of the entity table .
793 *
794 * @static
795 *
796 * @return boolean|object Returns either boolean value or CRM_Core_DAO_RecurringEntity object
797 */
798 static public function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
799 if (empty($entityId) || empty($entityTable)) {
800 return FALSE;
801 }
802 $dao = new CRM_Core_DAO_RecurringEntity();
803 $dao->entity_id = $entityId;
804 $dao->entity_table = $entityTable;
805 if ($dao->find(TRUE)) {
806 // make sure its not a linked entity thats being deleted
807 if ($isDelLinkedEntities && !array_key_exists($entityTable, self::$_linkedEntitiesInfo)) {
808 // delete all linked entities from recurring entity table
809 foreach (self::$_linkedEntitiesInfo as $linkedTable => $linfo) {
810 $daoName = self::$_tableDAOMapper[$linkedTable];
811 if (!$daoName) {
812 CRM_Core_Error::fatal("DAO Mapper missing for $linkedTable.");
813 }
814
815 $linkedDao = new $daoName();
816 $linkedDao->$linfo['entity_id_col'] = $entityId;
817 $linkedDao->$linfo['entity_table_col'] = $entityTable;
818 $linkedDao->find();
819 while ($linkedDao->fetch()) {
820 CRM_Core_BAO_RecurringEntity::delEntity($linkedDao->id, $linkedTable, FALSE);
821 }
822 }
823 }
824 // delete main entity
825 return $dao->delete();
826 }
827 return FALSE;
828 }
829
830 /**
831 * This function maps values posted from form to civicrm_action_schedule columns
832 *
833 * @param array $formParams
834 * And array of form values posted .
835 *
836 * @return array
837 */
838 public function mapFormValuesToDB($formParams = array()) {
839 $dbParams = array();
840 if (CRM_Utils_Array::value('used_for', $formParams)) {
841 $dbParams['used_for'] = $formParams['used_for'];
842 }
843
844 if (CRM_Utils_Array::value('entity_id', $formParams)) {
845 $dbParams['entity_value'] = $formParams['entity_id'];
846 }
847
848 if (CRM_Utils_Array::value('repetition_start_date', $formParams)) {
849 if (CRM_Utils_Array::value('repetition_start_date_display', $formParams)) {
850 $repetitionStartDate = $formParams['repetition_start_date_display'];
851 }
852 else {
853 $repetitionStartDate = $formParams['repetition_start_date'];
854 }
855 if (CRM_Utils_Array::value('repetition_start_date_time', $formParams)) {
856 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
857 }
858 $repetition_start_date = new DateTime($repetitionStartDate);
859 $dbParams['start_action_date'] = CRM_Utils_Date::processDate($repetition_start_date->format('Y-m-d H:i:s'));
860 }
861
862 if (CRM_Utils_Array::value('repetition_frequency_unit', $formParams)) {
863 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
864 }
865
866 if (CRM_Utils_Array::value('repetition_frequency_interval', $formParams)) {
867 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
868 }
869
870 //For Repeats on:(weekly case)
871 if ($formParams['repetition_frequency_unit'] == 'week') {
872 if (CRM_Utils_Array::value('start_action_condition', $formParams)) {
873 $repeats_on = CRM_Utils_Array::value('start_action_condition', $formParams);
874 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
875 }
876 }
877
878 //For Repeats By:(monthly case)
879 if ($formParams['repetition_frequency_unit'] == 'month') {
880 if ($formParams['repeats_by'] == 1) {
881 if (CRM_Utils_Array::value('limit_to', $formParams)) {
882 $dbParams['limit_to'] = $formParams['limit_to'];
883 }
884 }
885 if ($formParams['repeats_by'] == 2) {
886 if (CRM_Utils_Array::value('entity_status_1', $formParams) && CRM_Utils_Array::value('entity_status_2', $formParams)) {
887 $dbParams['entity_status'] = $formParams['entity_status_1']." ".$formParams['entity_status_2'];
888 }
889 }
890 }
891
892 //For "Ends" - After:
893 if ($formParams['ends'] == 1) {
894 if (CRM_Utils_Array::value('start_action_offset', $formParams)) {
895 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
896 }
897 }
898
899 //For "Ends" - On:
900 if ($formParams['ends'] == 2) {
901 if (CRM_Utils_Array::value('repeat_absolute_date', $formParams)) {
902 $dbParams['absolute_date'] = CRM_Utils_Date::processDate($formParams['repeat_absolute_date']);
903 }
904 }
905 return $dbParams;
906 }
907
908 /**
909 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
910 *
911 * @param int $scheduleReminderId
912 * Primary key of civicrm_action_schedule table .
913 *
914 * @static
915 *
916 * @return object
917 */
918 static public function getScheduleReminderDetailsById($scheduleReminderId) {
919 $query = "SELECT *
920 FROM civicrm_action_schedule WHERE 1";
921 if ($scheduleReminderId) {
922 $query .= "
923 AND id = %1";
924 }
925 $dao = CRM_Core_DAO::executeQuery($query,
926 array(
927 1 => array($scheduleReminderId, 'Integer')
928 )
929 );
930 $dao->fetch();
931 return $dao;
932 }
933
934 /**
935 * wrapper of getScheduleReminderDetailsById function
936 *
937 * @param int $scheduleReminderId
938 * Primary key of civicrm_action_schedule table .
939 *
940 * @return array
941 */
942 public function getScheduleParams($scheduleReminderId) {
943 $scheduleReminderDetails = array();
944 if ($scheduleReminderId) {
945 //Get all the details from schedule reminder table
946 $scheduleReminderDetails = self::getScheduleReminderDetailsById($scheduleReminderId);
947 $scheduleReminderDetails = (array) $scheduleReminderDetails;
948 }
949 return $scheduleReminderDetails;
950 }
951
952 /**
953 * This function takes criterias saved in civicrm_action_schedule table
954 * and creates recursion rule
955 *
956 * @param array $scheduleReminderDetails
957 * Array of repeat criterias saved in civicrm_action_schedule table .
958 *
959 * @return object
960 * When object
961 */
962 public function getRecursionFromSchedule($scheduleReminderDetails = array()) {
963 $r = new When();
964 //If there is some data for this id
965 if ($scheduleReminderDetails['repetition_frequency_unit']) {
966 if ($scheduleReminderDetails['start_action_date']) {
967 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
968 }
969 else {
970 $currDate = date("Y-m-d H:i:s");
971 }
972 $start = new DateTime($currDate);
973 $this->recursion_start_date = $start;
974 if ($scheduleReminderDetails['repetition_frequency_unit']) {
975 $repetition_frequency_unit = $scheduleReminderDetails['repetition_frequency_unit'];
976 if ($repetition_frequency_unit == "day") {
977 $repetition_frequency_unit = "dai";
978 }
979 $repetition_frequency_unit = $repetition_frequency_unit.'ly';
980 $r->recur($start, $repetition_frequency_unit);
981 }
982
983 if ($scheduleReminderDetails['repetition_frequency_interval']) {
984 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
985 }
986 else {
987 $r->errors[] = 'Repeats every: is a required field';
988 }
989
990 //week
991 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
992 if ($scheduleReminderDetails['start_action_condition']) {
993 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
994 $explodeStartActionCondition = explode(',', $startActionCondition);
995 $buildRuleArray = array();
996 foreach ($explodeStartActionCondition as $key => $val) {
997 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
998 }
999 $r->wkst('MO')->byday($buildRuleArray);
1000 }
1001 }
1002
1003 //month
1004 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1005 if ($scheduleReminderDetails['entity_status']) {
1006 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1007 switch ($startActionDate[0]) {
1008 case 'first':
1009 $startActionDate1 = 1;
1010 break;
1011
1012 case 'second':
1013 $startActionDate1 = 2;
1014 break;
1015
1016 case 'third':
1017 $startActionDate1 = 3;
1018 break;
1019
1020 case 'fourth':
1021 $startActionDate1 = 4;
1022 break;
1023
1024 case 'last':
1025 $startActionDate1 = -1;
1026 break;
1027 }
1028 $concatStartActionDateBits = $startActionDate1.strtoupper(substr($startActionDate[1], 0, 2));
1029 $r->byday(array($concatStartActionDateBits));
1030 }
1031 elseif ($scheduleReminderDetails['limit_to']) {
1032 $r->bymonthday(array($scheduleReminderDetails['limit_to']));
1033 }
1034 }
1035
1036 //Ends
1037 if ($scheduleReminderDetails['start_action_offset']) {
1038 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1039 $r->errors[] = 'Occurrences should be less than or equal to 30';
1040 }
1041 $r->count($scheduleReminderDetails['start_action_offset']);
1042 }
1043
1044 if (CRM_Utils_Array::value('absolute_date', $scheduleReminderDetails)) {
1045 $absoluteDate = CRM_Utils_Date::setDateDefaults($scheduleReminderDetails['absolute_date']);
1046 $endDate = new DateTime($absoluteDate[0].' '.$absoluteDate[1]);
1047 $endDate->modify('+1 day');
1048 $r->until($endDate);
1049 }
1050
1051 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1052 $r->errors[] = 'Ends: is a required field';
1053 }
1054 }
1055 else {
1056 $r->errors[] = 'Repeats: is a required field';
1057 }
1058 return $r;
1059 }
1060
1061
1062 /**
1063 * This function gets time difference between the two datetime object
1064 *
1065 * @param DateTime $startDate
1066 * Start Date .
1067 * @param DateTime $endDate
1068 * End Date .
1069 *
1070 * @static
1071 *
1072 * @return object
1073 * DateTime object which contain time difference
1074 */
1075 static public function getInterval($startDate, $endDate) {
1076 if ($startDate && $endDate) {
1077 $startDate = new DateTime($startDate);
1078 $endDate = new DateTime($endDate);
1079 return $startDate->diff($endDate);
1080 }
1081 }
1082
1083 /**
1084 * This function gets all columns from civicrm_action_schedule on the basis of event id
1085 *
1086 * @param int $entityId
1087 * Entity ID .
1088 * @param string $used_for
1089 * Specifies for which entity type it's used for .
1090 *
1091 * @static
1092 *
1093 * @return object
1094 */
1095 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1096 if ($entityId) {
1097 $query = "
1098 SELECT *
1099 FROM civicrm_action_schedule
1100 WHERE entity_value = %1";
1101 if ($used_for) {
1102 $query .= " AND used_for = %2";
1103 }
1104 $params = array(
1105 1 => array($entityId, 'Integer'),
1106 2 => array($used_for, 'String')
1107 );
1108 $dao = CRM_Core_DAO::executeQuery($query, $params);
1109 $dao->fetch();
1110 }
1111 return $dao;
1112 }
1113
1114 /**
1115 * Update mode column in civicrm_recurring_entity table for event related tabs
1116 *
1117 * @param int $entityId
1118 * Event id .
1119 * @param string $linkedEntityTable
1120 * Linked entity table name for this event .
1121 * @return array
1122 */
1123 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1124 $result = array();
1125 if ( $entityId && $linkedEntityTable && $mainEntityTable ) {
1126 if (CRM_Utils_Array::value($linkedEntityTable, self::$_tableDAOMapper)) {
1127 $dao = self::$_tableDAOMapper[$linkedEntityTable];
1128 }
1129 else {
1130 CRM_Core_Session::setStatus('Could not update mode for linked entities');
1131 return;
1132 }
1133 $entityTable = $linkedEntityTable;
1134 $params = array(
1135 'entity_id' => $entityId,
1136 'entity_table' => $mainEntityTable
1137 );
1138 $defaults = array();
1139 CRM_Core_DAO::commonRetrieve($dao, $params, $defaults);
1140 if (CRM_Utils_Array::value('id', $defaults)) {
1141 $result['entityId'] = $defaults['id'];
1142 $result['entityTable'] = $entityTable;
1143 }
1144 }
1145 return $result;
1146 }
1147 }