Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2014-12-16-01-08-03
[civicrm-core.git] / CRM / Contribute / BAO / ContributionRecur.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Contribute_BAO_ContributionRecur extends CRM_Contribute_DAO_ContributionRecur {
36
37 /**
38 * Create recurring contribution
39 *
40 * @param array $params (reference ) an assoc array of name/value pairs
41 *
42 * @return object activity contact object
43 * @access public
44 *
45 */
46 static function create(&$params) {
47 return self::add($params);
48 }
49
50 /**
51 * Takes an associative array and creates a contribution object
52 *
53 * the function extract all the params it needs to initialize the create a
54 * contribution object. the params array could contain additional unused name/value
55 * pairs
56 *
57 * @param array $params (reference ) an assoc array of name/value pairs
58 *
59 * @return CRM_Contribute_BAO_Contribution object
60 * @access public
61 * @static
62 * @todo move hook calls / extended logic to create - requires changing calls to call create not add
63 */
64 static function add(&$params) {
65 if (!empty($params['id'])) {
66 CRM_Utils_Hook::pre('edit', 'ContributionRecur', $params['id'], $params);
67 }
68 else {
69 CRM_Utils_Hook::pre('create', 'ContributionRecur', NULL, $params);
70 }
71
72 // make sure we're not creating a new recurring contribution with the same transaction ID
73 // or invoice ID as an existing recurring contribution
74 $duplicates = array();
75 if (self::checkDuplicate($params, $duplicates)) {
76 $error = CRM_Core_Error::singleton();
77 $d = implode(', ', $duplicates);
78 $error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
79 'Fatal',
80 array($d),
81 "Found matching recurring contribution(s): $d"
82 );
83 return $error;
84 }
85
86 $recurring = new CRM_Contribute_BAO_ContributionRecur();
87 $recurring->copyValues($params);
88 $recurring->id = CRM_Utils_Array::value('id', $params);
89
90 // set currency for CRM-1496
91 if (!isset($recurring->currency)) {
92 $config = CRM_Core_Config::singleton();
93 $recurring->currency = $config->defaultCurrency;
94 }
95 $result = $recurring->save();
96
97 if (!empty($params['id'])) {
98 CRM_Utils_Hook::post('edit', 'ContributionRecur', $recurring->id, $recurring);
99 }
100 else {
101 CRM_Utils_Hook::post('create', 'ContributionRecur', $recurring->id, $recurring);
102 }
103
104 return $result;
105 }
106
107 /**
108 * Check if there is a recurring contribution with the same trxn_id or invoice_id
109 *
110 * @param array $params (reference ) an assoc array of name/value pairs
111 * @param array $duplicates (reference ) store ids of duplicate contribs
112 *
113 * @return boolean true if duplicate, false otherwise
114 * @access public
115 * static
116 */
117 static function checkDuplicate($params, &$duplicates) {
118 $id = CRM_Utils_Array::value('id', $params);
119 $trxn_id = CRM_Utils_Array::value('trxn_id', $params);
120 $invoice_id = CRM_Utils_Array::value('invoice_id', $params);
121
122 $clause = array();
123 $params = array();
124
125 if ($trxn_id) {
126 $clause[] = "trxn_id = %1";
127 $params[1] = array($trxn_id, 'String');
128 }
129
130 if ($invoice_id) {
131 $clause[] = "invoice_id = %2";
132 $params[2] = array($invoice_id, 'String');
133 }
134
135 if (empty($clause)) {
136 return FALSE;
137 }
138
139 $clause = implode(' OR ', $clause);
140 if ($id) {
141 $clause = "( $clause ) AND id != %3";
142 $params[3] = array($id, 'Integer');
143 }
144
145 $query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
146 $dao = CRM_Core_DAO::executeQuery($query, $params);
147 $result = FALSE;
148 while ($dao->fetch()) {
149 $duplicates[] = $dao->id;
150 $result = TRUE;
151 }
152 return $result;
153 }
154
155 /**
156 * @param int $id
157 * @param $mode
158 *
159 * @return array|null
160 */
161 static function getPaymentProcessor($id, $mode) {
162 //FIX ME:
163 $sql = "
164 SELECT r.payment_processor_id
165 FROM civicrm_contribution_recur r
166 WHERE r.id = %1";
167 $params = array(1 => array($id, 'Integer'));
168 $paymentProcessorID = &CRM_Core_DAO::singleValueQuery($sql,
169 $params
170 );
171 if (!$paymentProcessorID) {
172 return NULL;
173 }
174
175 return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
176 }
177
178 /**
179 * Get the number of installment done/completed for each recurring contribution
180 *
181 * @param array $ids (reference ) an array of recurring contribution ids
182 *
183 * @return array $totalCount an array of recurring ids count
184 * @access public
185 * static
186 */
187 static function getCount(&$ids) {
188 $recurID = implode(',', $ids);
189 $totalCount = array();
190
191 $query = "
192 SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
193 FROM civicrm_contribution
194 WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
195 GROUP BY contribution_recur_id";
196
197 $res = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
198
199 while ($res->fetch()) {
200 $totalCount[$res->contribution_recur_id] = $res->commpleted;
201 }
202 return $totalCount;
203 }
204
205 /**
206 * Delete Recurring contribution.
207 *
208 * @param int $recurId
209 *
210 * @return bool
211 * @access public
212 * @static
213 */
214 static function deleteRecurContribution($recurId) {
215 $result = FALSE;
216 if (!$recurId) {
217 return $result;
218 }
219
220 $recur = new CRM_Contribute_DAO_ContributionRecur();
221 $recur->id = $recurId;
222 $result = $recur->delete();
223
224 return $result;
225 }
226
227 /**
228 * Cancel Recurring contribution.
229 *
230 * @param integer $recurId recur contribution id.
231 * @param array $objects an array of objects that is to be cancelled like
232 * contribution, membership, event. At least contribution object is a must.
233 *
234 * @param array $activityParams
235 *
236 * @return bool
237 * @access public
238 * @static
239 */
240 static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
241 if (!$recurId) {
242 return FALSE;
243 }
244
245 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
246 $canceledId = array_search('Cancelled', $contributionStatus);
247 $recur = new CRM_Contribute_DAO_ContributionRecur();
248 $recur->id = $recurId;
249 $recur->whereAdd("contribution_status_id != $canceledId");
250
251 if ($recur->find(TRUE)) {
252 $transaction = new CRM_Core_Transaction();
253 $recur->contribution_status_id = $canceledId;
254 $recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
255 $recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
256 $recur->modified_date = CRM_Utils_Date::isoToMysql($recur->modified_date);
257 $recur->cancel_date = date('YmdHis');
258 $recur->save();
259
260 $dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
261 if ($dao && $dao->recur_id) {
262 $details = CRM_Utils_Array::value('details', $activityParams);
263 if ($dao->auto_renew && $dao->membership_id) {
264 // its auto-renewal membership mode
265 $membershipTypes = CRM_Member_PseudoConstant::membershipType();
266 $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
267 $membershipType = CRM_Utils_Array::value($membershipType, $membershipTypes);
268 $details .= '
269 <br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
270 }
271 else {
272 $details .= '
273 <br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
274 1 => $dao->amount,
275 2 => $dao->frequency_interval,
276 3 => $dao->frequency_unit
277 ));
278 }
279 $activityParams = array(
280 'source_contact_id' => $dao->contact_id,
281 'source_record_id' => CRM_Utils_Array::value('source_record_id', $activityParams),
282 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
283 'Cancel Recurring Contribution',
284 'name'
285 ),
286 'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
287 'details' => $details,
288 'activity_date_time' => date('YmdHis'),
289 'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
290 'Completed',
291 'name'
292 ),
293 );
294 $session = CRM_Core_Session::singleton();
295 $cid = $session->get('userID');
296 if ($cid) {
297 $activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
298 $activityParams['source_contact_id'] = $cid;
299 }
300 CRM_Activity_BAO_Activity::create($activityParams);
301 }
302
303 // if there are associated objects, cancel them as well
304 if ($objects == CRM_Core_DAO::$_nullObject) {
305 $transaction->commit();
306 return TRUE;
307 }
308 else {
309 $baseIPN = new CRM_Core_Payment_BaseIPN();
310 return $baseIPN->cancelled($objects, $transaction);
311 }
312 }
313 else {
314 // if already cancelled, return true
315 $recur->whereAdd();
316 $recur->whereAdd("contribution_status_id = $canceledId");
317 if ($recur->find(TRUE)) {
318 return TRUE;
319 }
320 }
321
322 return FALSE;
323 }
324
325 /**
326 * Get list of recurring contribution of contact Ids
327 *
328 * @param int $contactId Contact ID
329 *
330 * @return array list of recurring contribution fields
331 *
332 * @access public
333 * @static
334 */
335 static function getRecurContributions($contactId) {
336 $params = array();
337 $recurDAO = new CRM_Contribute_DAO_ContributionRecur();
338 $recurDAO->contact_id = $contactId;
339 $recurDAO->find();
340 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
341
342 while ($recurDAO->fetch()) {
343 $params[$recurDAO->id]['id'] = $recurDAO->id;
344 $params[$recurDAO->id]['contactId'] = $recurDAO->contact_id;
345 $params[$recurDAO->id]['start_date'] = $recurDAO->start_date;
346 $params[$recurDAO->id]['end_date'] = $recurDAO->end_date;
347 $params[$recurDAO->id]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date;
348 $params[$recurDAO->id]['amount'] = $recurDAO->amount;
349 $params[$recurDAO->id]['currency'] = $recurDAO->currency;
350 $params[$recurDAO->id]['frequency_unit'] = $recurDAO->frequency_unit;
351 $params[$recurDAO->id]['frequency_interval'] = $recurDAO->frequency_interval;
352 $params[$recurDAO->id]['installments'] = $recurDAO->installments;
353 $params[$recurDAO->id]['contribution_status_id'] = $recurDAO->contribution_status_id;
354 $params[$recurDAO->id]['contribution_status'] = CRM_Utils_Array::value($recurDAO->contribution_status_id, $contributionStatus);
355 $params[$recurDAO->id]['is_test'] = $recurDAO->is_test;
356 $params[$recurDAO->id]['payment_processor_id'] = $recurDAO->payment_processor_id;
357 }
358
359 return $params;
360 }
361
362 /**
363 * @param int $entityID
364 * @param string $entity
365 *
366 * @return null|Object
367 */
368 static function getSubscriptionDetails($entityID, $entity = 'recur') {
369 $sql = "
370 SELECT rec.id as recur_id,
371 rec.processor_id as subscription_id,
372 rec.frequency_interval,
373 rec.installments,
374 rec.frequency_unit,
375 rec.amount,
376 rec.is_test,
377 rec.auto_renew,
378 rec.currency,
379 con.id as contribution_id,
380 con.contribution_page_id,
381 rec.contact_id,
382 mp.membership_id";
383
384 if ($entity == 'recur') {
385 $sql .= "
386 FROM civicrm_contribution_recur rec
387 LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
388 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
389 WHERE rec.id = %1
390 GROUP BY rec.id";
391 }
392 elseif ($entity == 'contribution') {
393 $sql .= "
394 FROM civicrm_contribution con
395 INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
396 LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
397 WHERE con.id = %1";
398 }
399 elseif ($entity == 'membership') {
400 $sql .= "
401 FROM civicrm_membership_payment mp
402 INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
403 INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
404 INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
405 WHERE mp.membership_id = %1";
406 }
407
408 $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($entityID, 'Integer')));
409 if ($dao->fetch()) {
410 return $dao;
411 }
412 else {
413 return CRM_Core_DAO::$_nullObject;
414 }
415 }
416
417 static function setSubscriptionContext() {
418 // handle context redirection for subscription url
419 $session = CRM_Core_Session::singleton();
420 if ($session->get('userID')) {
421 $url = FALSE;
422 $cid = CRM_Utils_Request::retrieve('cid', 'Integer');
423 $mid = CRM_Utils_Request::retrieve('mid', 'Integer');
424 $qfkey = CRM_Utils_Request::retrieve('key', 'String');
425 $context = CRM_Utils_Request::retrieve('context', 'String');
426 if ($cid) {
427 switch ($context) {
428 case 'contribution':
429 $url = CRM_Utils_System::url('civicrm/contact/view',
430 "reset=1&selectedChild=contribute&cid={$cid}"
431 );
432 break;
433
434 case 'membership':
435 $url = CRM_Utils_System::url('civicrm/contact/view',
436 "reset=1&selectedChild=member&cid={$cid}"
437 );
438 break;
439
440 case 'dashboard':
441 $url = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
442 break;
443 }
444 }
445 if ($mid) {
446 switch ($context) {
447 case 'dashboard':
448 $url = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
449 break;
450
451 case 'search':
452 $url = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
453 break;
454 }
455 }
456 if ($url) {
457 $session->pushUserContext($url);
458 }
459 }
460 }
461 }