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