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