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