Merge pull request #17116 from lcdservices/dev-core-1721
[civicrm-core.git] / CRM / Core / BAO / RecurringEntity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 use When\When;
19
20 /**
21 * Class CRM_Core_BAO_RecurringEntity.
22 */
23 class CRM_Core_BAO_RecurringEntity extends CRM_Core_DAO_RecurringEntity {
24
25 const RUNNING = 1;
26 public $schedule = [];
27 public $scheduleId = NULL;
28 public $scheduleFormValues = [];
29
30 public $dateColumns = [];
31 public $overwriteColumns = [];
32 public $intervalDateColumns = [];
33 public $excludeDates = [];
34
35 public $linkedEntities = [];
36
37 public $isRecurringEntityRecord = TRUE;
38
39 protected $recursion = NULL;
40 protected $recursion_start_date = NULL;
41
42 public static $_entitiesToBeDeleted = [];
43
44 public static $status = NULL;
45
46 public static $_recurringEntityHelper
47 = [
48 'civicrm_event' => [
49 'helper_class' => 'CRM_Event_DAO_Event',
50 'delete_func' => 'delete',
51 'pre_delete_func' => 'CRM_Event_Form_ManageEvent_Repeat::checkRegistrationForEvents',
52 ],
53 'civicrm_activity' => [
54 'helper_class' => 'CRM_Activity_DAO_Activity',
55 'delete_func' => 'delete',
56 'pre_delete_func' => '',
57 ],
58 ];
59
60 public static $_dateColumns
61 = [
62 'civicrm_event' => [
63 'dateColumns' => ['start_date'],
64 'excludeDateRangeColumns' => ['start_date', 'end_date'],
65 'intervalDateColumns' => ['end_date'],
66 ],
67 'civicrm_activity' => [
68 'dateColumns' => ['activity_date_time'],
69 ],
70 ];
71
72 public static $_tableDAOMapper
73 = [
74 'civicrm_event' => 'CRM_Event_DAO_Event',
75 'civicrm_price_set_entity' => 'CRM_Price_DAO_PriceSetEntity',
76 'civicrm_uf_join' => 'CRM_Core_DAO_UFJoin',
77 'civicrm_tell_friend' => 'CRM_Friend_DAO_Friend',
78 'civicrm_pcp_block' => 'CRM_PCP_DAO_PCPBlock',
79 'civicrm_activity' => 'CRM_Activity_DAO_Activity',
80 'civicrm_activity_contact' => 'CRM_Activity_DAO_ActivityContact',
81 ];
82
83 public static $_updateSkipFields
84 = [
85 'civicrm_event' => ['start_date', 'end_date'],
86 'civicrm_tell_friend' => ['entity_id'],
87 'civicrm_pcp_block' => ['entity_id'],
88 'civicrm_activity' => ['activity_date_time'],
89 ];
90
91 public static $_linkedEntitiesInfo
92 = [
93 'civicrm_tell_friend' => [
94 'entity_id_col' => 'entity_id',
95 'entity_table_col' => 'entity_table',
96 ],
97 'civicrm_price_set_entity' => [
98 'entity_id_col' => 'entity_id',
99 'entity_table_col' => 'entity_table',
100 'is_multirecord' => TRUE,
101 ],
102 'civicrm_uf_join' => [
103 'entity_id_col' => 'entity_id',
104 'entity_table_col' => 'entity_table',
105 'is_multirecord' => TRUE,
106 ],
107 'civicrm_pcp_block' => [
108 'entity_id_col' => 'entity_id',
109 'entity_table_col' => 'entity_table',
110 ],
111 ];
112
113 //Define global CLASS CONSTANTS for recurring entity mode types
114 const MODE_THIS_ENTITY_ONLY = 1;
115 const MODE_NEXT_ALL_ENTITY = 2;
116 const MODE_ALL_ENTITY_IN_SERIES = 3;
117
118 /**
119 * Getter for status.
120 *
121 * @return string
122 */
123 public static function getStatus() {
124 return self::$status;
125 }
126
127 /**
128 * Setter for status.
129 *
130 * @param string $status
131 */
132 public static function setStatus($status) {
133 self::$status = $status;
134 }
135
136 /**
137 * Create or update a RecurringEntity.
138 *
139 * @param array $params
140 * @return CRM_Core_DAO_RecurringEntity
141 */
142 public static function add($params) {
143 return self::writeRecord($params);
144 }
145
146 /**
147 * Convenience wrapper for self::writeRecord
148 *
149 * @param int $parentId
150 * Parent entity id .
151 * @param int $entityId
152 * Child entity id .
153 * @param string $entityTable
154 * Name of the entity table .
155 *
156 * @return CRM_Core_DAO_RecurringEntity
157 */
158 public static function quickAdd($parentId, $entityId, $entityTable) {
159 $params = [
160 'parent_id' => $parentId,
161 'entity_id' => $entityId,
162 'entity_table' => $entityTable,
163 ];
164 return self::writeRecord($params);
165 }
166
167 /**
168 * This function updates the mode column in the civicrm_recurring_entity table.
169 *
170 * @param int $mode
171 * 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.
172 */
173 public function mode($mode) {
174 if ($this->entity_id && $this->entity_table) {
175 if ($this->find(TRUE)) {
176 $this->mode = $mode;
177 }
178 else {
179 $this->parent_id = $this->entity_id;
180 $this->mode = $mode;
181 }
182 $this->save();
183 }
184 }
185
186 /**
187 * This function generates all new entities based on object vars.
188 *
189 * @return array
190 */
191 public function generate() {
192 $this->generateRecursiveDates();
193
194 return $this->generateEntities();
195 }
196
197 /**
198 * This function builds a "When" object based on schedule/reminder params
199 *
200 * @return object
201 * When object
202 */
203 public function generateRecursion() {
204 // return if already generated
205 if (is_a($this->recursion, 'When\When')) {
206 return $this->recursion;
207 }
208
209 if ($this->scheduleId) {
210 // get params by ID
211 $this->schedule = $this->getScheduleParams($this->scheduleId);
212 }
213 elseif (!empty($this->scheduleFormValues)) {
214 $this->schedule = $this->mapFormValuesToDB($this->scheduleFormValues);
215 }
216
217 if (!empty($this->schedule)) {
218 $this->recursion = $this->getRecursionFromSchedule($this->schedule);
219 }
220 return $this->recursion;
221 }
222
223 /**
224 * Generate new DAOs and along with entries in civicrm_recurring_entity table.
225 *
226 * @return array
227 */
228 public function generateEntities() {
229 self::setStatus(self::RUNNING);
230
231 $newEntities = [];
232 $findCriteria = [];
233 if (!empty($this->recursionDates)) {
234 if ($this->entity_id) {
235 $findCriteria = ['id' => $this->entity_id];
236
237 // save an entry with initiating entity-id & entity-table
238 if ($this->entity_table && !$this->find(TRUE)) {
239 $this->parent_id = $this->entity_id;
240 $this->save();
241 }
242 }
243 if (empty($findCriteria)) {
244 CRM_Core_Error::fatal("Find criteria missing to generate form. Make sure entity_id and table is set.");
245 }
246
247 $count = 0;
248 foreach ($this->recursionDates as $key => $dateCols) {
249 $newCriteria = $dateCols;
250 foreach ($this->overwriteColumns as $col => $val) {
251 $newCriteria[$col] = $val;
252 }
253 // create main entities
254 $obj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($this->entity_table,
255 $findCriteria,
256 $newCriteria,
257 $this->isRecurringEntityRecord
258 );
259
260 if (is_a($obj, 'CRM_Core_DAO') && $obj->id) {
261 $newCriteria = [];
262 $newEntities[$this->entity_table][$count] = $obj->id;
263
264 foreach ($this->linkedEntities as $linkedInfo) {
265 foreach ($linkedInfo['linkedColumns'] as $col) {
266 $newCriteria[$col] = $obj->id;
267 }
268 // create linked entities
269 $linkedObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($linkedInfo['table'],
270 $linkedInfo['findCriteria'],
271 $newCriteria,
272 CRM_Utils_Array::value('isRecurringEntityRecord', $linkedInfo, TRUE)
273 );
274
275 if (is_a($linkedObj, 'CRM_Core_DAO') && $linkedObj->id) {
276 $newEntities[$linkedInfo['table']][$count] = $linkedObj->id;
277 }
278 }
279 }
280 $count++;
281 }
282 }
283
284 self::$status = NULL;
285 return $newEntities;
286 }
287
288 /**
289 * This function iterates through when object criteria and
290 * generates recursive dates based on that
291 *
292 * @return array
293 * array of dates
294 */
295 public function generateRecursiveDates() {
296 $this->generateRecursion();
297
298 $recursionDates = [];
299 if (is_a($this->recursion, 'When\When')) {
300 $initialCount = $this->schedule['start_action_offset'] ?? NULL;
301
302 $exRangeStart = $exRangeEnd = NULL;
303 if (!empty($this->excludeDateRangeColumns)) {
304 $exRangeStart = $this->excludeDateRangeColumns[0];
305 $exRangeEnd = $this->excludeDateRangeColumns[1];
306 }
307
308 if (CRM_Core_Config::singleton()->userFramework == 'UnitTests') {
309 $this->recursion->RFC5545_COMPLIANT = When::IGNORE;
310 }
311 $count = 1;
312 $result = $this->recursion_start_date;
313 while ($result = $this->getNextOccurrence($result)) {
314 $skip = FALSE;
315 if ($result == $this->recursion_start_date) {
316 // skip the recursion-start-date from the list we going to generate
317 $skip = TRUE;
318 }
319 $baseDate = $result->format('YmdHis');
320
321 foreach ($this->dateColumns as $col) {
322 $recursionDates[$count][$col] = $baseDate;
323 }
324 foreach ($this->intervalDateColumns as $col => $interval) {
325 $newDate = new DateTime($baseDate);
326 $newDate->add($interval);
327 $recursionDates[$count][$col] = $newDate->format('YmdHis');
328 }
329 if ($exRangeStart) {
330 $exRangeStartDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value($exRangeStart, $recursionDates[$count]), NULL, FALSE, 'Ymd');
331 $exRangeEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value($exRangeEnd, $recursionDates[$count]), NULL, FALSE, 'Ymd');
332 }
333
334 foreach ($this->excludeDates as $exDate) {
335 $exDate = CRM_Utils_Date::processDate($exDate, NULL, FALSE, 'Ymd');
336 if (!$exRangeStart) {
337 if ($exDate == $result->format('Ymd')) {
338 $skip = TRUE;
339 break;
340 }
341 }
342 else {
343 if (($exDate == $exRangeStartDate) ||
344 ($exRangeEndDate && ($exDate > $exRangeStartDate) && ($exDate <= $exRangeEndDate))
345 ) {
346 $skip = TRUE;
347 break;
348 }
349 }
350 }
351
352 if ($skip) {
353 unset($recursionDates[$count]);
354 if ($initialCount && ($initialCount > 0)) {
355 // lets increase the counter, so we get correct number of occurrences
356 $initialCount++;
357 $this->recursion->count($initialCount);
358 }
359 continue;
360 }
361 $count++;
362 }
363 }
364 $this->recursionDates = $recursionDates;
365
366 return $recursionDates;
367 }
368
369 /**
370 * This function gets all the children for a particular parent entity.
371 *
372 * @param int $parentId
373 * Parent entity id .
374 * @param string $entityTable
375 * Name of the entity table .
376 * @param bool $includeParent
377 * If true parent id is included in result set and vice versa .
378 * @param int $mode
379 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
380 * @param int $initiatorId
381 * The instance where this function is invoked from .
382 *
383 *
384 * @return array
385 * an array of child ids
386 */
387 public static function getEntitiesForParent($parentId, $entityTable, $includeParent = TRUE, $mode = 3, $initiatorId = NULL) {
388 $entities = [];
389 if (empty($parentId) || empty($entityTable)) {
390 return $entities;
391 }
392
393 if (!$initiatorId) {
394 $initiatorId = $parentId;
395 }
396
397 $queryParams = [
398 1 => [$parentId, 'Integer'],
399 2 => [$entityTable, 'String'],
400 3 => [$initiatorId, 'Integer'],
401 ];
402
403 if (!$mode) {
404 $mode = CRM_Core_DAO::singleValueQuery("SELECT mode FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
405 }
406
407 $query = "SELECT *
408 FROM civicrm_recurring_entity
409 WHERE parent_id = %1 AND entity_table = %2";
410 if (!$includeParent) {
411 $query .= " AND entity_id != " . ($initiatorId ? "%3" : "%1");
412 }
413
414 // MODE = SINGLE
415 if ($mode == '1') {
416 $query .= " AND entity_id = %3";
417 }
418 // MODE = FUTURE
419 elseif ($mode == '2') {
420 $recurringEntityID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_recurring_entity WHERE entity_id = %3 AND entity_table = %2", $queryParams);
421 if ($recurringEntityID) {
422 $query .= $includeParent ? " AND id >= %4" : " AND id > %4";
423 // FIXME: change to order by dates
424 $query .= " ORDER BY id ASC";
425 $queryParams[4] = [$recurringEntityID, 'Integer'];
426 }
427 else {
428 // something wrong, return empty
429 return [];
430 }
431 }
432
433 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
434 while ($dao->fetch()) {
435 $entities["{$dao->entity_table}_{$dao->entity_id}"]['table'] = $dao->entity_table;
436 $entities["{$dao->entity_table}_{$dao->entity_id}"]['id'] = $dao->entity_id;
437 }
438 return $entities;
439 }
440
441 /**
442 * This function when passed an entity id checks if it has parent and
443 * returns all other entities that are connected to same parent.
444 *
445 * @param int $entityId
446 * Entity id .
447 * @param string $entityTable
448 * Entity table name .
449 * @param bool $includeParent
450 * Include parent in result set .
451 * @param int $mode
452 * 1. retrieve only one entity. 2. retrieve all future entities in the repeating set. 3. all entities in the repeating set. .
453 *
454 *
455 * @return array
456 * array of connected ids
457 */
458 public static function getEntitiesFor($entityId, $entityTable, $includeParent = TRUE, $mode = 3) {
459 $parentId = self::getParentFor($entityId, $entityTable);
460 if ($parentId) {
461 return self::getEntitiesForParent($parentId, $entityTable, $includeParent, $mode, $entityId);
462 }
463 return [];
464 }
465
466 /**
467 * This function gets the parent for the entity id passed to it.
468 *
469 * @param int $entityId
470 * Entity ID .
471 * @param string $entityTable
472 * Entity table name .
473 * @param bool $includeParent
474 * Include parent in result set .
475 *
476 *
477 * @return int
478 * unsigned $parentId Parent ID
479 */
480 public static function getParentFor($entityId, $entityTable, $includeParent = TRUE) {
481 if (empty($entityId) || empty($entityTable)) {
482 return NULL;
483 }
484
485 $query = "
486 SELECT parent_id
487 FROM civicrm_recurring_entity
488 WHERE entity_id = %1 AND entity_table = %2";
489 if (!$includeParent) {
490 $query .= " AND parent_id != %1";
491 }
492 $parentId
493 = CRM_Core_DAO::singleValueQuery($query,
494 [
495 1 => [$entityId, 'Integer'],
496 2 => [$entityTable, 'String'],
497 ]
498 );
499 return $parentId;
500 }
501
502 /**
503 * Finds the position of this entity as well as total count of the repeating set
504 *
505 * @param $entityId
506 * @param $entityTable
507 * @return array|null
508 */
509 public static function getPositionAndCount($entityId, $entityTable) {
510 $position = $count = 0;
511
512 $query = "
513 SELECT entity_id
514 FROM civicrm_recurring_entity
515 WHERE parent_id = (SELECT parent_id FROM civicrm_recurring_entity WHERE entity_id = %1 AND entity_table = %2) AND entity_table = %2";
516
517 $dao = CRM_Core_DAO::executeQuery($query,
518 [
519 1 => [$entityId, 'Integer'],
520 2 => [$entityTable, 'String'],
521 ]
522 );
523
524 while ($dao->fetch()) {
525 ++$count;
526 if ($dao->entity_id <= $entityId) {
527 ++$position;
528 }
529 }
530 if ($count) {
531 return [$position, $count];
532 }
533 return NULL;
534 }
535
536 /**
537 * This function copies the information from parent entity and creates other entities with same information.
538 *
539 * @param string $entityTable
540 * Entity table name .
541 * @param array $fromCriteria
542 * Array of all the fields & values on which basis to copy .
543 * @param array $newParams
544 * Array of all the fields & values to be copied besides the other fields .
545 * @param bool $createRecurringEntity
546 * If to create a record in recurring_entity table .
547 *
548 *
549 * @return object
550 */
551 public static function copyCreateEntity($entityTable, $fromCriteria, $newParams, $createRecurringEntity = TRUE) {
552 $daoName = self::$_tableDAOMapper[$entityTable];
553 if (!$daoName) {
554 CRM_Core_Error::fatal("DAO Mapper missing for $entityTable.");
555 }
556 $newObject = CRM_Core_DAO::copyGeneric($daoName, $fromCriteria, $newParams);
557
558 if (is_a($newObject, 'CRM_Core_DAO') && $newObject->id && $createRecurringEntity) {
559 $object = new $daoName();
560 foreach ($fromCriteria as $key => $value) {
561 $object->$key = $value;
562 }
563 $object->find(TRUE);
564
565 CRM_Core_BAO_RecurringEntity::quickAdd($object->id, $newObject->id, $entityTable);
566 }
567
568 CRM_Utils_Hook::copy(CRM_Core_DAO_AllCoreTables::getBriefName($daoName), $newObject);
569 return $newObject;
570 }
571
572 /**
573 * This function acts as a listener to dao->update whenever there is an update.
574 *
575 * It propagates any changes to all related entities present in recurring entity table
576 *
577 * @param object $event
578 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just updated.
579 */
580 public static function triggerUpdate($event) {
581 // if DB version is earlier than 4.6 skip any processing
582 static $currentVer = NULL;
583 if (!$currentVer) {
584 $currentVer = CRM_Core_BAO_Domain::version();
585 }
586 if (version_compare($currentVer, '4.6.alpha1') < 0) {
587 return;
588 }
589
590 static $processedEntities = [];
591 $obj =& $event->object;
592 if (empty($obj->id) || empty($obj->__table)) {
593 return;
594 }
595 $key = "{$obj->__table}_{$obj->id}";
596
597 if (array_key_exists($key, $processedEntities)) {
598 // already processed
599 return;
600 }
601
602 // get related entities
603 $repeatingEntities = self::getEntitiesFor($obj->id, $obj->__table, FALSE, NULL);
604 if (empty($repeatingEntities)) {
605 // return if its not a recurring entity parent
606 return;
607 }
608 // mark being processed
609 $processedEntities[$key] = 1;
610
611 // to make sure we not copying to source itself
612 unset($repeatingEntities[$key]);
613
614 foreach ($repeatingEntities as $key => $val) {
615 $entityID = $val['id'];
616 $entityTable = $val['table'];
617
618 $processedEntities[$key] = 1;
619
620 if (array_key_exists($entityTable, self::$_tableDAOMapper)) {
621 $daoName = self::$_tableDAOMapper[$entityTable];
622
623 $skipData = [];
624 if (array_key_exists($entityTable, self::$_updateSkipFields)) {
625 $skipFields = self::$_updateSkipFields[$entityTable];
626 foreach ($skipFields as $sfield) {
627 $skipData[$sfield] = NULL;
628 }
629 }
630
631 $updateDAO = CRM_Core_DAO::cascadeUpdate($daoName, $obj->id, $entityID, $skipData);
632 }
633 else {
634 CRM_Core_Error::fatal("DAO Mapper missing for $entityTable.");
635 }
636 }
637 // done with processing. lets unset static var.
638 unset($processedEntities);
639 }
640
641 /**
642 * This function acts as a listener to dao->save,
643 * and creates entries for linked entities in recurring entity table
644 *
645 * @param object $event
646 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just inserted.
647 */
648 public static function triggerInsert($event) {
649 $obj =& $event->object;
650 if (!array_key_exists($obj->__table, self::$_linkedEntitiesInfo)) {
651 return;
652 }
653
654 // if DB version is earlier than 4.6 skip any processing
655 static $currentVer = NULL;
656 if (!$currentVer) {
657 $currentVer = CRM_Core_BAO_Domain::version();
658 }
659 if (version_compare($currentVer, '4.6.alpha1') < 0) {
660 return;
661 }
662
663 static $processedEntities = [];
664 if (empty($obj->id) || empty($obj->__table)) {
665 return;
666 }
667 $key = "{$obj->__table}_{$obj->id}";
668
669 if (array_key_exists($key, $processedEntities)) {
670 // already being processed. Exit recursive calls.
671 return;
672 }
673
674 if (self::getStatus() == self::RUNNING) {
675 // if recursion->generate() is doing some work, lets not intercept
676 return;
677 }
678
679 // mark being processed
680 $processedEntities[$key] = 1;
681
682 // get related entities for table being saved
683 $hasaRecurringRecord = self::getParentFor($obj->id, $obj->__table);
684
685 if (empty($hasaRecurringRecord)) {
686 // check if its a linked entity
687 if (array_key_exists($obj->__table, self::$_linkedEntitiesInfo) &&
688 empty(self::$_linkedEntitiesInfo[$obj->__table]['is_multirecord'])
689 ) {
690 $linkedDAO = new self::$_tableDAOMapper[$obj->__table]();
691 $linkedDAO->id = $obj->id;
692 if ($linkedDAO->find(TRUE)) {
693 $idCol = self::$_linkedEntitiesInfo[$obj->__table]['entity_id_col'];
694 $tableCol = self::$_linkedEntitiesInfo[$obj->__table]['entity_table_col'];
695
696 $pEntityID = $linkedDAO->$idCol;
697 $pEntityTable = $linkedDAO->$tableCol;
698
699 // find all parent recurring entity set
700 $pRepeatingEntities = self::getEntitiesFor($pEntityID, $pEntityTable);
701
702 if (!empty($pRepeatingEntities)) {
703 // for each parent entity in the set, find out a similar linked entity,
704 // if doesn't exist create one, and also create entries in recurring_entity table
705
706 foreach ($pRepeatingEntities as $key => $val) {
707 if (array_key_exists($key, $processedEntities)) {
708 // this graph is already being processed
709 return;
710 }
711 $processedEntities[$key] = 1;
712 }
713
714 // start with first entry with just itself
715 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $obj->id, $obj->__table);
716
717 foreach ($pRepeatingEntities as $key => $val) {
718 $rlinkedDAO = new self::$_tableDAOMapper[$obj->__table]();
719 $rlinkedDAO->$idCol = $val['id'];
720 $rlinkedDAO->$tableCol = $val['table'];
721 if ($rlinkedDAO->find(TRUE)) {
722 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $rlinkedDAO->id, $obj->__table);
723 }
724 else {
725 // linked entity doesn't exist. lets create them
726 $newCriteria = [
727 $idCol => $val['id'],
728 $tableCol => $val['table'],
729 ];
730 $linkedObj = CRM_Core_BAO_RecurringEntity::copyCreateEntity($obj->__table,
731 ['id' => $obj->id],
732 $newCriteria,
733 TRUE
734 );
735 if ($linkedObj->id) {
736 CRM_Core_BAO_RecurringEntity::quickAdd($obj->id, $linkedObj->id, $obj->__table);
737 }
738 }
739 }
740 }
741 }
742 }
743 }
744
745 // done with processing. lets unset static var.
746 unset($processedEntities);
747 }
748
749 /**
750 * This function acts as a listener to dao->delete, and deletes an entry from recurring_entity table
751 *
752 * @param object $event
753 * An object of /Civi/Core/DAO/Event/PostUpdate containing dao object that was just deleted.
754 */
755 public static function triggerDelete($event) {
756 $obj =& $event->object;
757
758 // if DB version is earlier than 4.6 skip any processing
759 static $currentVer = NULL;
760 if (!$currentVer) {
761 $currentVer = CRM_Core_BAO_Domain::version();
762 }
763 if (version_compare($currentVer, '4.6.alpha1') < 0) {
764 return;
765 }
766
767 static $processedEntities = [];
768 if (empty($obj->id) || empty($obj->__table) || !$event->result) {
769 return;
770 }
771 $key = "{$obj->__table}_{$obj->id}";
772
773 if (array_key_exists($key, $processedEntities)) {
774 // already processed
775 return;
776 }
777
778 // mark being processed
779 $processedEntities[$key] = 1;
780
781 $parentID = self::getParentFor($obj->id, $obj->__table);
782 if ($parentID) {
783 CRM_Core_BAO_RecurringEntity::delEntity($obj->id, $obj->__table, TRUE);
784 }
785 }
786
787 /**
788 * This function deletes main entity and related linked entities from recurring-entity table.
789 *
790 * @param int $entityId
791 * Entity id
792 * @param string $entityTable
793 * Name of the entity table
794 *
795 * @param bool $isDelLinkedEntities
796 *
797 * @return bool|\CRM_Core_DAO_RecurringEntity
798 * @throws \Exception
799 */
800 public static function delEntity($entityId, $entityTable, $isDelLinkedEntities = FALSE) {
801 if (empty($entityId) || empty($entityTable)) {
802 return FALSE;
803 }
804 $dao = new CRM_Core_DAO_RecurringEntity();
805 $dao->entity_id = $entityId;
806 $dao->entity_table = $entityTable;
807 if ($dao->find(TRUE)) {
808 // make sure its not a linked entity thats being deleted
809 if ($isDelLinkedEntities && !array_key_exists($entityTable, self::$_linkedEntitiesInfo)) {
810 // delete all linked entities from recurring entity table
811 foreach (self::$_linkedEntitiesInfo as $linkedTable => $linfo) {
812 $daoName = self::$_tableDAOMapper[$linkedTable];
813 if (!$daoName) {
814 CRM_Core_Error::fatal("DAO Mapper missing for $linkedTable.");
815 }
816
817 $linkedDao = new $daoName();
818 $linkedDao->{$linfo['entity_id_col']} = $entityId;
819 $linkedDao->{$linfo['entity_table_col']} = $entityTable;
820 $linkedDao->find();
821 while ($linkedDao->fetch()) {
822 CRM_Core_BAO_RecurringEntity::delEntity($linkedDao->id, $linkedTable, FALSE);
823 }
824 }
825 }
826 // delete main entity
827 return $dao->delete();
828 }
829 return FALSE;
830 }
831
832 /**
833 * This function maps values posted from form to civicrm_action_schedule columns.
834 *
835 * @param array $formParams
836 * And array of form values posted .
837 *
838 * @return array
839 */
840 public function mapFormValuesToDB($formParams = []) {
841 $dbParams = [];
842 if (!empty($formParams['used_for'])) {
843 $dbParams['used_for'] = $formParams['used_for'];
844 }
845
846 if (!empty($formParams['entity_id'])) {
847 $dbParams['entity_value'] = $formParams['entity_id'];
848 }
849
850 if (!empty($formParams['repetition_start_date'])) {
851 if (!empty($formParams['repetition_start_date_display'])) {
852 $repetitionStartDate = $formParams['repetition_start_date_display'];
853 }
854 else {
855 $repetitionStartDate = $formParams['repetition_start_date'];
856 }
857 if (!empty($formParams['repetition_start_date_time'])) {
858 $repetitionStartDate = $repetitionStartDate . " " . $formParams['repetition_start_date_time'];
859 }
860 $repetition_start_date = new DateTime($repetitionStartDate);
861 $dbParams['start_action_date'] = $repetition_start_date->format('YmdHis');
862 }
863
864 if (!empty($formParams['repetition_frequency_unit'])) {
865 $dbParams['repetition_frequency_unit'] = $formParams['repetition_frequency_unit'];
866 }
867
868 if (!empty($formParams['repetition_frequency_interval'])) {
869 $dbParams['repetition_frequency_interval'] = $formParams['repetition_frequency_interval'];
870 }
871
872 //For Repeats on:(weekly case)
873 if ($formParams['repetition_frequency_unit'] == 'week') {
874 if (!empty($formParams['start_action_condition'])) {
875 $repeats_on = $formParams['start_action_condition'] ?? NULL;
876 $dbParams['start_action_condition'] = implode(",", array_keys($repeats_on));
877 }
878 }
879
880 //For Repeats By:(monthly case)
881 if ($formParams['repetition_frequency_unit'] == 'month') {
882 if ($formParams['repeats_by'] == 1) {
883 if (!empty($formParams['limit_to'])) {
884 $dbParams['limit_to'] = $formParams['limit_to'];
885 }
886 }
887 if ($formParams['repeats_by'] == 2) {
888 if (!empty($formParams['entity_status_1']) && !empty($formParams['entity_status_2'])) {
889 $dbParams['entity_status'] = $formParams['entity_status_1'] . " " . $formParams['entity_status_2'];
890 }
891 }
892 }
893
894 //For "Ends" - After:
895 if ($formParams['ends'] == 1) {
896 if (!empty($formParams['start_action_offset'])) {
897 $dbParams['start_action_offset'] = $formParams['start_action_offset'];
898 }
899 }
900
901 //For "Ends" - On:
902 if ($formParams['ends'] == 2) {
903 if (!empty($formParams['repeat_absolute_date'])) {
904 $dbParams['absolute_date'] = CRM_Utils_Date::processDate($formParams['repeat_absolute_date']);
905 }
906 }
907 return $dbParams;
908 }
909
910 /**
911 * This function gets all the columns of civicrm_action_schedule table based on id(primary key)
912 *
913 * @param int $scheduleReminderId
914 * Primary key of civicrm_action_schedule table .
915 *
916 *
917 * @return object
918 */
919 public static function getScheduleReminderDetailsById($scheduleReminderId) {
920 $query = "SELECT *
921 FROM civicrm_action_schedule WHERE 1";
922 if ($scheduleReminderId) {
923 $query .= "
924 AND id = %1";
925 }
926 $dao = CRM_Core_DAO::executeQuery($query,
927 [
928 1 => [$scheduleReminderId, 'Integer'],
929 ]
930 );
931 $dao->fetch();
932 return $dao;
933 }
934
935 /**
936 * wrapper of getScheduleReminderDetailsById function.
937 *
938 * @param int $scheduleReminderId
939 * Primary key of civicrm_action_schedule table .
940 *
941 * @return array
942 */
943 public function getScheduleParams($scheduleReminderId) {
944 $scheduleReminderDetails = [];
945 if ($scheduleReminderId) {
946 //Get all the details from schedule reminder table
947 $scheduleReminderDetails = self::getScheduleReminderDetailsById($scheduleReminderId);
948 $scheduleReminderDetails = (array) $scheduleReminderDetails;
949 }
950 return $scheduleReminderDetails;
951 }
952
953 /**
954 * This function takes criteria saved in civicrm_action_schedule table
955 * and creates recursion rule
956 *
957 * @param array $scheduleReminderDetails
958 * Array of repeat criteria saved in civicrm_action_schedule table .
959 *
960 * @return object
961 * When object
962 */
963 public function getRecursionFromSchedule($scheduleReminderDetails = []) {
964 $r = new When();
965 //If there is some data for this id
966 if ($scheduleReminderDetails['repetition_frequency_unit']) {
967 if ($scheduleReminderDetails['start_action_date']) {
968 $currDate = date('Y-m-d H:i:s', strtotime($scheduleReminderDetails['start_action_date']));
969 }
970 else {
971 $currDate = date("Y-m-d H:i:s");
972 }
973 $start = new DateTime($currDate);
974 $this->recursion_start_date = $start;
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->startDate($start)
981 ->exclusions([$start])
982 ->freq($repetition_frequency_unit);
983
984 if ($scheduleReminderDetails['repetition_frequency_interval']) {
985 $r->interval($scheduleReminderDetails['repetition_frequency_interval']);
986 }
987 else {
988 $r->errors[] = 'Repeats every: is a required field';
989 }
990
991 //week
992 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'week') {
993 if ($scheduleReminderDetails['start_action_condition']) {
994 $startActionCondition = $scheduleReminderDetails['start_action_condition'];
995 $explodeStartActionCondition = explode(',', $startActionCondition);
996 $buildRuleArray = [];
997 foreach ($explodeStartActionCondition as $key => $val) {
998 $buildRuleArray[] = strtoupper(substr($val, 0, 2));
999 }
1000 $r->wkst('MO')->byday($buildRuleArray);
1001 }
1002 }
1003
1004 //month
1005 if ($scheduleReminderDetails['repetition_frequency_unit'] == 'month') {
1006 if ($scheduleReminderDetails['entity_status']) {
1007 $startActionDate = explode(" ", $scheduleReminderDetails['entity_status']);
1008 switch ($startActionDate[0]) {
1009 case 'first':
1010 $startActionDate1 = 1;
1011 break;
1012
1013 case 'second':
1014 $startActionDate1 = 2;
1015 break;
1016
1017 case 'third':
1018 $startActionDate1 = 3;
1019 break;
1020
1021 case 'fourth':
1022 $startActionDate1 = 4;
1023 break;
1024
1025 case 'last':
1026 $startActionDate1 = -1;
1027 break;
1028 }
1029 $concatStartActionDateBits = $startActionDate1 . strtoupper(substr($startActionDate[1], 0, 2));
1030 $r->byday([$concatStartActionDateBits]);
1031 }
1032 elseif ($scheduleReminderDetails['limit_to']) {
1033 $r->bymonthday([$scheduleReminderDetails['limit_to']]);
1034 }
1035 }
1036
1037 //Ends
1038 if ($scheduleReminderDetails['start_action_offset']) {
1039 if ($scheduleReminderDetails['start_action_offset'] > 30) {
1040 $r->errors[] = 'Occurrences should be less than or equal to 30';
1041 }
1042 $r->count($scheduleReminderDetails['start_action_offset']);
1043 }
1044
1045 if (!empty($scheduleReminderDetails['absolute_date'])) {
1046 $absoluteDate = CRM_Utils_Date::setDateDefaults($scheduleReminderDetails['absolute_date']);
1047 // absolute_date column of scheduled-reminder table is of type date (and not datetime)
1048 // and we always want the date to be included, and therefore appending 23:59
1049 $endDate = new DateTime($absoluteDate[0] . ' ' . '23:59');
1050 $r->until($endDate);
1051 }
1052
1053 if (!$scheduleReminderDetails['start_action_offset'] && !$scheduleReminderDetails['absolute_date']) {
1054 $r->errors[] = 'Ends: is a required field';
1055 }
1056 }
1057 else {
1058 $r->errors[] = 'Repeats: is a required field';
1059 }
1060 return $r;
1061 }
1062
1063 /**
1064 * This function gets time difference between the two datetime object.
1065 *
1066 * @param DateTime $startDate
1067 * Start Date .
1068 * @param DateTime $endDate
1069 * End Date .
1070 *
1071 *
1072 * @return object
1073 * DateTime object which contain time difference
1074 */
1075 public static 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 *
1092 * @return object
1093 */
1094 public static function getReminderDetailsByEntityId($entityId, $used_for) {
1095 if ($entityId) {
1096 $query = "
1097 SELECT *
1098 FROM civicrm_action_schedule
1099 WHERE entity_value = %1";
1100 if ($used_for) {
1101 $query .= " AND used_for = %2";
1102 }
1103 $params = [
1104 1 => [$entityId, 'Integer'],
1105 2 => [$used_for, 'String'],
1106 ];
1107 $dao = CRM_Core_DAO::executeQuery($query, $params);
1108 $dao->fetch();
1109 }
1110 return $dao;
1111 }
1112
1113 /**
1114 * Update mode column in civicrm_recurring_entity table for event related tabs.
1115 *
1116 * @param int $entityId
1117 * Event id .
1118 * @param string $linkedEntityTable
1119 * Linked entity table name for this event .
1120 * @param string $mainEntityTable
1121 *
1122 * @return array
1123 */
1124 public static function updateModeLinkedEntity($entityId, $linkedEntityTable, $mainEntityTable) {
1125 $result = [];
1126 if ($entityId && $linkedEntityTable && $mainEntityTable) {
1127 if (!empty(self::$_tableDAOMapper[$linkedEntityTable])) {
1128 $dao = self::$_tableDAOMapper[$linkedEntityTable];
1129 }
1130 else {
1131 CRM_Core_Session::setStatus('Could not update mode for linked entities');
1132 return NULL;
1133 }
1134 $entityTable = $linkedEntityTable;
1135 $params = [
1136 'entity_id' => $entityId,
1137 'entity_table' => $mainEntityTable,
1138 ];
1139 $defaults = [];
1140 CRM_Core_DAO::commonRetrieve($dao, $params, $defaults);
1141 if (!empty($defaults['id'])) {
1142 $result['entityId'] = $defaults['id'];
1143 $result['entityTable'] = $entityTable;
1144 }
1145 }
1146 return $result;
1147 }
1148
1149 /**
1150 * Update mode in civicrm_recurring_entity table for event related data and price set in civicrm_price_set_entity.
1151 *
1152 * @param int $entityId
1153 * Event id .
1154 * @param string $entityTable
1155 * @param string $mode
1156 * @param string $linkedEntityTable
1157 * Linked entity table name for this event .
1158 * @param string $priceSet
1159 * Price set of the event .
1160 *
1161 * @return array
1162 */
1163 public static function updateModeAndPriceSet($entityId, $entityTable, $mode, $linkedEntityTable, $priceSet) {
1164 $finalResult = [];
1165
1166 if (!empty($linkedEntityTable)) {
1167 $result = CRM_Core_BAO_RecurringEntity::updateModeLinkedEntity($entityId, $linkedEntityTable, $entityTable);
1168 }
1169
1170 $dao = new CRM_Core_DAO_RecurringEntity();
1171 if (!empty($result)) {
1172 $dao->entity_id = $result['entityId'];
1173 $dao->entity_table = $result['entityTable'];
1174 }
1175 else {
1176 $dao->entity_id = $entityId;
1177 $dao->entity_table = $entityTable;
1178 }
1179
1180 if ($dao->find(TRUE)) {
1181 $dao->mode = $mode;
1182 $dao->save();
1183
1184 if ($priceSet) {
1185 //CRM-20787 Fix
1186 //I am not sure about other fields, if mode = 3 apply for an event then other fields
1187 //should be save for all other series events or not so applying for price set only for now here.
1188 if (CRM_Core_BAO_RecurringEntity::MODE_ALL_ENTITY_IN_SERIES === $mode) {
1189 //Step-1: Get all events of series
1190 $seriesEventRecords = CRM_Core_BAO_RecurringEntity::getEntitiesFor($entityId, $entityTable);
1191 foreach ($seriesEventRecords as $event) {
1192 //Step-2: Save price set in other series events
1193 //Remove existing priceset
1194 if (CRM_Price_BAO_PriceSet::removeFrom($event['table'], $event['id'])) {
1195 CRM_Core_BAO_Discount::del($event['id'], $event['table']);
1196 }
1197 //Add new price set
1198 CRM_Price_BAO_PriceSet::addTo($event['table'], $event['id'], $priceSet);
1199 }
1200 }
1201
1202 if (CRM_Core_BAO_RecurringEntity::MODE_NEXT_ALL_ENTITY === $mode) {
1203 //Step-1: Get all events of series
1204 $seriesEventRecords = CRM_Core_BAO_RecurringEntity::getEntitiesFor($entityId, $entityTable);
1205 foreach ($seriesEventRecords as $event) {
1206 //Step-2: Save price set in other series events
1207 if ($entityId < $event["id"]) {
1208 //Remove existing priceset
1209 if (CRM_Price_BAO_PriceSet::removeFrom($event['table'], $event['id'])) {
1210 CRM_Core_BAO_Discount::del($event['id'], $event['table']);
1211 }
1212 //Add new price set
1213 CRM_Price_BAO_PriceSet::addTo($event['table'], $event['id'], $priceSet);
1214 }
1215 }
1216 }
1217 }
1218
1219 //CRM-20787 - Fix end
1220 $finalResult['status'] = 'Done';
1221 }
1222 else {
1223 $finalResult['status'] = 'Error';
1224 }
1225
1226 return $finalResult;
1227 }
1228
1229 /**
1230 * Get next occurrence for the given date
1231 *
1232 * @param \DateTime $occurDate
1233 * @param bool $strictly_after
1234 *
1235 * @return bool
1236 */
1237 private function getNextOccurrence($occurDate, $strictly_after = TRUE) {
1238 try {
1239 return $this->recursion->getNextOccurrence($occurDate, $strictly_after);
1240 }
1241 catch (Exception $exception) {
1242 CRM_Core_Session::setStatus(ts($exception->getMessage()));
1243 }
1244 return FALSE;
1245 }
1246
1247 }