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