-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecurly.module
More file actions
504 lines (448 loc) · 17.9 KB
/
recurly.module
File metadata and controls
504 lines (448 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<?php
/**
* @file
* Uses Recurly's PHP client library to interact with their API and integrate it
* with Drupal user accounts.
*
* This is a D6 backport of the original D7 module. D7 code style is retained
* in an effort to minimize changes to D7 code in order to make merging easier.
*/
/**
* Implements hook_menu().
*/
function recurly_menu() {
$items = array();
// Define an always accessible push notification listener menu item.
$items['recurly/listener/%'] = array(
'page callback' => 'recurly_process_push_notification',
'page arguments' => array(2),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['recurly/listener/%/%'] = array(
'page callback' => 'recurly_process_push_notification',
'page arguments' => array(2, 3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
// Define administrative menu items.
$items['admin/settings/recurly'] = array(
'title' => 'Recurly',
'description' => 'Configure your Recurly API settings and points of integration with Drupal.',
'page callback' => 'drupal_get_form',
'page arguments' => array('recurly_settings_form'),
'access arguments' => array('administer recurly'),
'file' => 'includes/recurly.admin.inc',
);
$items['admin/settings/recurly/settings'] = array(
'title' => 'Settings',
'description' => 'Configure your Recurly API settings and points of integration with Drupal.',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items['admin/settings/recurly/subscription-plans'] = array(
'title' => 'Subscription plans',
'description' => 'View a list of subscription plans defined in your Recurly account.',
'page callback' => 'recurly_subscription_plans_overview',
'access arguments' => array('administer recurly'),
'type' => MENU_LOCAL_TASK,
'weight' => -5,
'file' => 'includes/recurly.admin.inc',
);
return $items;
}
/**
* Implements hook_perm().
*
* This is implemented as a wrapper for the D7 hook_permission function.
* Doing this helps keep the diff between the D7 and D6 versions minimal.
*/
function recurly_perm() {
$out = array();
$permissions = recurly_permission();
foreach ($permissions as $key => $val) {
$out[] = $key;
}
return $out;
}
/**
* Implements hook_permission().
*/
function recurly_permission() {
$permissions = array(
'administer recurly' => array(
'title' => t('Administer Recurly'),
'description' => t('Allows users to configure site-wide Recurly account settings and grants access to all integration activities.'),
'restrict access' => TRUE,
),
'edit subscription plans' => array(
'title' => t('Edit subscription plans'),
'description' => t('Determines whether or not the user should see links to edit subscription plans at Recurly. Grants of this permission should coordinate with user permissions at Recurly.'),
'restrict access' => TRUE,
),
'view all recurly accounts' => array(
'title' => t('View all Recurly accounts'),
'description' => t('Allows users to view the Recurly account information linked to any user on the site.'),
'restrict access' => TRUE,
),
'edit all recurly accounts' => array(
'title' => t('Edit all Recurly accounts'),
'description' => t('Determines whether or not the user should see links to edit accounts in the Recurly administrative interface. Grants of this permission should coordinate with user permissions at Recurly.'),
'restrict access' => TRUE,
),
'view own recurly account' => array(
'title' => t('View own Recurly account'),
'description' => t('Allows users to view Recurly account information linked to their user accounts.'),
),
'edit own recurly account' => array(
'title' => t('Edit own Recurly account'),
'description' => t('Determines whether or not users should see links to edit their own account information on the hosted account management page at Recurly.'),
),
'edit own recurly account without login' => array(
'title' => t('Edit own Recurly account without login'),
'description' => t('Gives users direct edit links for their Recurly accounts if available that bypasses the normal login process on the hosted account management page.'),
)
);
return $permissions;
}
/**
* Implements hook_help().
*/
function recurly_help($path, $arg) {
switch ($path) {
case 'admin/config/services/recurly/subscription-plans':
return '<p>' . t('The subscription plans below are defined for the Recurly account configured in your default account settings. Plans should be defined and updated at Recurly and are cached here for informational purposes only. Edit links and purchase links that may appear in the table redirect to Recurly.') . '</p>';
}
}
/**
* Processes an incoming push notification.
*
* Push notifications are configured at Recurly, where you can setup the URL
* that listens for notifications and an HTTP username and password to use for
* basic authentication. When a notification is received, this function will
* perform some optional processing immediately if it is determined the received
* notification is from the default account.
*
* Other modules can react to incoming push notifications by implementing
* hook_recurly_process_push_notification(). The hook receives the subdomain as
* received in the listener URL; implementations can discern from this what
* Recurly account sent the notification, with a NULL value or the default
* account subdomain indicating the site's default account generated the push
* notification. If the notification was not from the default account, the
* implementations -must- perform their own authentication and parsing of the
* POST XML. If the notification was from the default account, it will have
* already passed HTTP basic authentication, and the hook implementation will
* received an already parsed notification object.
*
* @param $subdomain
* If specified, this is the subdomain of the Recurly account that sent the
* push notification; defaults to NULL indicating it is the default account as
* configured in the Recurly settings.
*/
function recurly_process_push_notification($key, $subdomain = NULL) {
$notification = NULL;
// If no subdomain was derived from the URL or the default account subdomain
// was specified...
if (empty($subdomain) || $subdomain == variable_get('recurly_subdomain', '')) {
// Ensure the push notification was sent to the proper URL.
if ($key != variable_get('recurly_listener_key', '')) {
// Log the failed attempt and bail.
watchdog('recurly', 'Incoming push notification did not contain the proper URL key.', array(), WATCHDOG_WARNING);
return;
}
// Initialize the Recurly client with the default account settings.
recurly_client_initialize();
// Retrieve the POST XML and create a notification object from it.
$post_xml = file_get_contents('php://input');
$notification = new Recurly_PushNotification($post_xml);
// Bail if this is an empty or invalid notification.
if (empty($notification) || empty($notification->type)) {
return;
}
// Log the incoming push notification if enabled.
if (variable_get('recurly_push_logging', FALSE)) {
watchdog('recurly', 'Incoming @type push notification: !notification', array('@type' => $notification->type, '!notification' => '<pre>' . check_plain(print_r($notification, TRUE)) . '</pre>'), WATCHDOG_NOTICE);
}
// If this is a new, canceled, or updated account set the database record.
if (in_array($notification->type, array('new_account_notification', 'canceled_account_notification', 'billing_info_updated_notification'))) {
// Retrieve the full account record from Recurly.
try {
$recurly_account = Recurly_Account::get($notification->account->account_code);
}
catch (Recurly_NotFoundError $e) {
drupal_set_message(t('Account not found'));
//watchdog_exception('recurly', $e);
}
// If we couldn't get anything, just attempt to use the submitted data.
if (empty($recurly_account)) {
$recurly_account = $notification->account;
}
// Look for a pre-existing local record.
$local_account = recurly_account_load(array('account_code' => $recurly_account->account_code), TRUE);
// If no local record exists and we've specified to create it...
if (empty($local_account)) {
$uid = 0;
// Attempt to find a matching user account.
if ($user = user_load_by_mail($recurly_account->email)) {
$uid = $user->uid;
}
// Save the local record now.
recurly_account_save($recurly_account, $uid);
}
elseif (!empty($local_account)) {
// Otherwise if a local record was found and we want to keep it
// synchronized, save it afresh now, preserving any existing data array.
recurly_account_save($recurly_account, $local_account->uid, $local_account->data);
}
}
}
module_invoke_all('recurly_process_push_notification', $subdomain, $notification);
}
/**
* Initializes the Recurly API client with a given set of account settings.
*
* @param $settings
* An array of Recurly account settings including the following keys or NULL
* to use the site-wide account settings.
* - username: the API username to use
* - password: the API password for the given username
* - subdomain: the subdomain configured for your Recurly account.
* - environment: the current environment of the given account, either
* 'sandbox' or 'production'.
*
* @return
* TRUE or FALSE indicating whether or not the client was initialized with the
* specified account settings.
*/
function recurly_client_initialize($settings = NULL) {
$client = NULL;
// If no settings array was given, use the default account settings.
if (empty($settings)) {
$settings = array(
'api_key' => variable_get('recurly_api_key', ''),
'subdomain' => variable_get('recurly_subdomain', ''),
'private_key' => variable_get('recurly_private_key', ''),
);
}
// If we can find a path in the libraries directory to the Recurly PHP client
// library...
$path = libraries_get_path('recurly');
if (($path = libraries_get_path('recurly')) && file_exists($path . '/lib/recurly.php')) {
// Include the library files and configure authentication.
require_once $path . '/lib/recurly.php';
// Required for the API
Recurly_Client::$apiKey = $settings['api_key'];
// Optional for Recurly.js:
Recurly_js::$privateKey = $settings['private_key'];
}
else {
watchdog('recurly', 'Could not find the Recurly PHP client library in sites/all/libraries/recurly.', array(), WATCHDOG_ERROR);
return FALSE;
}
return TRUE;
}
/**
* Determines whether or not the given account has access to perform the
* requested operation on the target account's Recurly account information.
*
* @param $op
* The operation to perform on the Recurly account; 'view' or 'edit'.
* @param $target_account
* The Drupal user account whose Recurly account information would be
* operated on.
* @param $account
* The Drupal user account performing the operation; defaults to the current
* user.
*
* @return
*/
function recurly_account_access($op, $target_account, $account = NULL) {
global $user;
// Initialize the account to the current user if it's empty.
if (empty($account)) {
$account = clone($user);
}
// Allow administrators to perform any operation.
if (user_access('administer recurly', $account)) {
return TRUE;
}
// Allow users with access to view or edit all accounts to perform operations.
if (user_access($op . ' all recurly accounts', $account)) {
return TRUE;
}
// Allow users with access to view or edit their own accounts.
if (user_access($op . ' own recurly account') && $account->uid == $target_account->uid) {
return TRUE;
}
return FALSE;
}
/**
* Loads a Recurly account record based on the given conditions.
*
* @param $conditions
* An associative array of values to look for in the conditions of the query;
* normally used to look-up on account_code or uid.
* @param $local
* Boolean indicating whether or not to only return local data; defaults to
* FALSE, meaning it will attempt to load the full linked account object.
*
* @return
* The fully loaded account object from Recurly if possible. If Recurly cannot
* be accessed, just returns an object representing the data stored locally.
* If the account no longer exists at Recurly, the returned object will
* include an additional 'orphaned' property set to TRUE. Returns FALSE if no
* data can be found locally at all.
*/
function recurly_account_load($conditions = array(), $local = FALSE) {
// Create a base select query object.
$query = db_select('recurly_account', 'ra')->fields('ra');
// Add conditions to it based on the passed array.
foreach ($conditions as $key => $value) {
$query->condition($key, $value);
}
// Retrieve data if available.
$data = $query->execute()->fetchObject();
// Bail now if no data was returned.
if (empty($data)) {
return FALSE;
}
// Unserialize the data array.
$data->data = unserialize($data->data);
// If we only want local data, return it now.
if ($local) {
return $data;
}
// Attempt to load the full account from Recurly.
try {
$recurly_account = Recurly_Account::get($data->account_code);
// Return the orphaned data if no account was found at Recurly.
if (empty($recurly_account)) {
$data->orphaned = TRUE;
return $data;
}
// If any data has changed remotely, update it locally now.
if ($recurly_account->first_name != $data->first_name ||
$recurly_account->last_name != $data->last_name ||
$recurly_account->company_name != $data->company_name ||
$recurly_account->email != $data->email ||
$recurly_account->state != $data->status) {
recurly_account_save($recurly_account, $data->uid);
}
}
catch (Exception $e) {
return $data;
}
return $recurly_account;
}
/**
* Saves an account record, optionally exporting the saved data to Recurly as a
* new account or update request as necessary.
*
* @param $recurly_account
* The Recurly account object to save.
* @param $uid
* The Drupal user ID the account is associated with.
* @param $data
* An array of data to store with the local record.
* @param $export
* Boolean indicating whether or not the saved account information should also
* be exported to Recurly by either creating a new account or updating an
* existing account based on the saved values using the Recurly API.
*
* @return
* FALSE on failure of either the local save or optional export or
* STATUS_INSERT or STATUS_UPDATE indicating the type of query performed to
* save the account information locally.
*/
function recurly_account_save($recurly_account, $uid, $data = array(), $export = FALSE) {
// First attempt to save the data at Recurly if specified. Failing an export
// will prevent local data from being saved so you don't end up with a local
// record that does not match a record at Recurly.
if ($export) {
// Check to see if the record already exists.
$remote_account = Recurly_Account::getAccount($recurly_account->account_code);
// If it does, then update the account.
if (!empty($remote_account)) {
try {
$recurly_account->update();
}
catch (Recurly_NotFoundError $e) {
//watchdog_exception('recurly', $e);
return FALSE;
}
}
else {
// Otherwise create it at Recurly now.
try {
$recurly_account->create();
}
catch (Recurly_NotFoundError $e) {
//watchdog_exception('recurly', $e);
return FALSE;
}
}
}
// Generate an array of data to save.
$fields = array(
'email' => (string) $recurly_account->email,
'first_name' => (string) $recurly_account->first_name,
'last_name' => (string) $recurly_account->last_name,
'company_name' => (string) $recurly_account->company_name,
'uid' => $uid,
'updated' => REQUEST_TIME,
);
// Add the status based on whatever data we have available.
if (!empty($recurly_account->state)) {
$fields['status'] = $recurly_account->state;
}
elseif (!empty($recurly_account->status)) {
$fields['status'] = $recurly_account->status;
}
else {
$fields['status'] = 'active';
}
// Execute a merge query that will either insert a new record or update an
// existing record accordingly.
return db_merge('recurly_account')
->key(array('account_code' => $recurly_account->account_code))
->fields($fields)
->execute();
}
/**
* Returns an array of subscription plan objects for the current account,
* retrieving them from a local cache if possible.
*
* @param $reset_cache
* Boolean indicating whether or not to reset the subscription plan cache when
* retrieving plans.
*
* @return
* An array of subscription plan objects.
*/
function recurly_subscription_plans($reset_cache = FALSE) {
// If we haven't specified a cache reset, attempt to retrieve plans from the
// cache before getting them from Recurly.
if (!$reset_cache) {
$plans = cache_get('recurly-subscription-plans:' . variable_get('recurly_subdomain', ''));
// If plans were found, return them now.
if (!empty($plans->data)) {
return $plans->data;
}
}
// Retrieve the subscription plans from Recurly.
$plans = Recurly_PlanList::get();
// If data was actually returned, cache it for the current subdomain.
if (!empty($plans)) {
cache_set('recurly-subscription-plans:' . variable_get('recurly_subdomain', ''), $plans, 'cache', CACHE_TEMPORARY);
}
return $plans;
}
/**
* Returns the base Recurly URL for the current account with an optional path
* appended to it.
*/
function recurly_url($path = '') {
// Generate the subdomain to use for the current account.
$subdomain = variable_get('recurly_subdomain', '');
return url('https://' . $subdomain . '.recurly.com/' . $path);
}