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