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