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