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