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