forked from archived-shomeya/box_api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbox_api.module
More file actions
327 lines (279 loc) · 9.02 KB
/
box_api.module
File metadata and controls
327 lines (279 loc) · 9.02 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
<?php
use Guzzle\Http\Client;
use Guzzle\Http\Exception;
use Box\BoxAPI\BoxAPIClient;
use Box\BoxAPI;
use Guzzle\Log\Zf2LogAdapter;
use Guzzle\Plugin\Log\LogPlugin;
use Guzzle\Log\MessageFormatter;
use Zend\Log\Logger;
use Zend\Log\Writer\Stream;
// Define the lifetime of a refresh token in seconds.
define('BOX_API_REFRESH_TOKEN_LIFETIME', 60*60*24*14); // 14 days
/**
* @file
* Functionality related to Box.com API integration.
*/
/**
* Implements hook_init().
*/
function box_api_init() {
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
}
elseif (!function_exists('drush_main') && module_exists('composer_manager')) {
composer_manager_register_autoloader();
}
}
/**
* Implements hook_entity_info().
*/
function box_api_entity_info() {
$return = array();
$return['box_api_creds'] = array(
'label' => t('Credentials'),
'plural label' => t('Credentials'),
'description' => t('Entity representing a set of Box API credentials'),
'entity class' => 'BoxAPICreds',
'controller class' => 'EntityAPIController',
'base table' => 'box_api_creds',
'fieldable' => TRUE,
'entity keys' => array(
'id' => 'id',
),
// Make use the class' label() and uri() implementation by default.
'label callback' => 'entity_class_label',
'uri callback' => 'entity_class_uri',
'bundles' => array(
'box_api_creds' => array(
'label' => t('Credentials'),
),
),
'module' => 'box_api',
);
return $return;
}
/**
* Implements hook_permission().
*/
function box_api_permission() {
return array(
'administer box api authorization' => array(
'title' => t('Administer Box API authorization'),
'description' => t('Perform authorization tasks for my Box API via OAUTH 2.0.'),
),
);
}
/**
* Implements hook_menu().
*/
function box_api_menu() {
$items = array();
$items['admin/config/media/box'] = array(
'title' => 'Box.com',
'description' => 'Configure your Box.com integration',
'page callback' => 'drupal_get_form',
'page arguments' => array('box_api_settings'),
'access arguments' => array('access administration pages'),
);
$items['admin/config/media/box/settings'] = array(
'title' => 'Settings',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -50,
);
$items['box_api/authorization_token'] = array(
'title' => 'Authorization token',
'page callback' => 'box_api_authorization_token_callback',
'access arguments' => array('administer box api authorization'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Form callback for settings form.
*/
function box_api_settings() {
$form = array();
$form['box_api_cache_requests'] = array(
'#type' => 'checkbox',
'#title' => t('Cache requests'),
'#default_value' => variable_get('box_api_cache_requests', FALSE),
);
$form['box_api_cache_time'] = array(
'#type' => 'textfield',
'#title' => t('Cache time'),
'#description' => t('Enter time for requests to be cached in seconds.'),
'#default_value' => variable_get('box_api_cache_time', 3600),
'#element_validate' => array('_box_api_cache_time_validate'),
'#states' => array(
'visible' => array(
':input[name="box_api_cache_requests"]' => array('checked' => TRUE),
),
),
);
$form['box_api_log_watchdog'] = array(
'#type' => 'checkbox',
'#title' => 'Log requests to watchdog',
'#default_value' => variable_get('box_api_log_watchdog', FALSE),
);
$form['clear_cache'] = array(
'#type' => 'submit',
'#value' => t('Clear Box.com object cache'),
'#submit' => array('_box_api_clear_cache'),
);
return system_settings_form($form);
}
/**
* Validate the cache time on the settings page.
*/
function _box_api_cache_time_validate($element, &$form_state) {
if (empty($element['#value']) || !is_numeric($element['#value'])) {
form_error($element, t('Cache time must be a number.'));
}
}
/**
* Clear the box object cache.
*/
function _box_api_clear_cache() {
cache_clear_all('*', 'cache_box_object', TRUE);
drupal_set_message('Box.com object cache cleared.');
}
/**
* Start Authentication with Box.com via OAUTH 2.0.
*
* This function performs a drupal_goto() which redirects to api.box.com.
*
* @param string $key
* The unique key for this set of creds. This should usually be
* prefixed with the name of the module requests this set of credentials. If
* the set already exists, then it will be updated.
* @param string $client_id
* The OAUTH 2.0 client id.
* @param string $client_secret
* The OAUTH 2.0 client secret.
* @param $options
* An options array with config options such as:
* - 'redirect': an internal Drupal path to redirect to upon success or
* failure of the OAuth access_token request.
* - 'auto_refresh': boolean indicating whether or not this set of credentials
* should be automatically refreshed before the refresh token expires. This
* relies on cron running on a regular schedule. Defaults to TRUE.
*
* @return none
* This function redirects and exits via drupal_goto().
*/
function box_api_generate_creds_set($key, $client_id, $client_secret, $options) {
$creds = BoxAPICreds::findByKeyOrNew($key);
$creds->client_id = $client_id;
$creds->client_secret = $client_secret;
$creds->setOptions($options);
$creds->setDrupalToken();
$creds->save();
$query = array(
'client_id' => $client_id,
'response_type' => 'code',
'redirect_uri' => url('box_api/authorization_token', array('absolute' => TRUE, 'https' => TRUE)),
'state' => $creds->token,
);
drupal_goto('https://api.box.com/oauth2/authorize', array('absolute' => TRUE, 'query' => $query));
}
/**
* Menu callback for authorization token.
*/
function box_api_authorization_token_callback() {
if (!isset($_GET['state']) && !isset($_GET['code'])) {
return drupal_not_found();
}
$creds = BoxAPICreds::findByToken($_GET['state']);
if (!$creds) {
return drupal_not_found();
}
$code = $_GET['code'];
$post_data = array(
'grant_type' => 'authorization_code',
'code' => str_replace('@', '', $code),
'client_id' => str_replace('@', '', $creds->client_id),
'client_secret' => str_replace('@', '', $creds->client_secret),
);
$client = new Client('https://api.box.com');
$request = $client->post('/oauth2/token', NULL, $post_data);
try {
$response = $request->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
$response = $e->getResponse();
$response_data = json_decode($response->getBody());
watchdog('box_api', 'Error retrieving access token from Box: !exception', array('!exception' => $e->getMessage()));
if (isset($response_data->error_description)) {
drupal_set_message(t('There was a problem communicating with the Box API: !error', array('!error' => $response_data->error_description)), 'error');
}
else {
drupal_set_message(t('There was a problem communicating with the Box API: !exception', array('!exception' => $e->getMessage())), 'error');
}
drupal_goto($creds->getOption('redirect'));
}
$response_data = json_decode($response->getBody());
if (!empty($response_data->error)) {
drupal_set_message(t('There was a problem authorizing with the Box API: @error', array('@error' => $response_data->error_description)), 'error');
drupal_goto($creds->getOption('redirect'));
}
$creds->access_token = $response_data->access_token;
$creds->refresh_token = $response_data->refresh_token;
$creds->token_status = TRUE;
$creds->timestamp = REQUEST_TIME;
$creds->expires = $response_data->expires_in;
$creds->save();
drupal_goto($creds->getOption('redirect'));
}
/**
* Implements hook_cron().
*/
function box_api_cron() {
$creds = BoxAPICreds::all();
$queue = $queue = DrupalQueue::get('box_api_refresh');
foreach ($creds as $cred_set) {
if ($cred_set->options['auto_refresh']) {
$queue->createItem($cred_set->id);
}
}
}
/**
* Implements hook_cron_queue_info().
*/
function box_api_cron_queue_info() {
return array(
'box_api_refresh' => array(
'worker callback' => 'box_api_token_refresh',
'time' => 30,
),
);
}
/**
* Worker callback for cron queue.
*
* @param $cred_id int The ID of the credential set to refresh.
*/
function box_api_token_refresh($cred_id) {
$creds = BoxAPICreds::findById($cred_id);
$creds->refreshToken();
}
/**
* Test function
*
* @return BoxAPIClient;
*/
function box_api_factory($creds_key) {
$creds = BoxAPICreds::findByKeyOrNew($creds_key);
if ($creds->tokenIsValid()) {
$client = BoxAPIClient::factory(array('token' => $creds->access_token));
if (variable_get('box_api_log_watchdog', FALSE)) {
$adapter = new BoxAPIWatchdogLogAdapter;
$logPlugin = new LogPlugin($adapter, MessageFormatter::DEBUG_FORMAT);
$client->addSubscriber($logPlugin);
}
$drupal_client = new DrupalBoxAPIClient($client, variable_get('box_api_cache_requests', FALSE), variable_get('box_api_cache_time', 3600));
return $drupal_client;
}
else {
return FALSE;
}
}