-
Notifications
You must be signed in to change notification settings - Fork 2
/
stanford_cap_api.module
370 lines (326 loc) · 11.1 KB
/
stanford_cap_api.module
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
<?php
/**
* @file
* Code for the Stanford CAP API feature.
*/
/**
* Time of the current request in seconds elapsed since the Unix Epoch.
*
* This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
* since PHP 5.4.0. Float timestamps confuse most PHP functions
* (including date_create()).
*
* @see http://php.net/manual/reserved.variables.server.php
* @see http://php.net/manual/function.time.php
*/
define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
/**
* Implements hook_menu().
*/
function stanford_cap_api_menu() {
$items = array();
$items['admin/settings/cap'] = array(
'title' => 'Community Academic Profiles',
'description' => 'Community Academic Profiles API screens.',
'position' => 'right',
'weight' => -5,
'page callback' => 'system_admin_menu_block_page',
'access arguments' => array('access administration pages'),
'file' => 'system.admin.inc',
'file path' => drupal_get_path('module', 'system'),
);
if (!variable_get('stanford_cap_api_configured', FALSE)) {
$items['admin/settings/cap/config'] = array(
'title' => 'CAP API Settings',
'description' => 'Provides administrators ability to change CAP API access settings.',
'page callback' => 'drupal_get_form',
'page arguments' => array('stanford_cap_api_settings_form'),
'access arguments' => array('administer cap api'),
'weight' => -10,
'file' => 'stanford_cap_api.admin.inc',
);
$items['admin/settings/cap/config/settings'] = array(
'title' => 'Settings',
'description' => 'Provides administrators ability to change CAP API access settings.',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
}
else {
$items['admin/settings/cap/config'] = array(
'title' => 'Details',
'description' => "Displays information about the site's connection to the CAP API.",
'weight' => -10,
'page callback' => 'drupal_get_form',
'page arguments' => array('stanford_cap_api_details_form'),
'access arguments' => array('administer cap api'),
'file' => 'stanford_cap_api.admin.inc',
);
$items['admin/settings/cap/config/details'] = array(
'title' => 'Details',
'description' => "Displays information about the site's connection to the CAP API.",
'weight' => -10,
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['admin/settings/cap/config/settings'] = array(
'title' => 'Settings',
'description' => 'Provides administrators ability to change CAP API access settings.',
'page callback' => 'drupal_get_form',
'page arguments' => array('stanford_cap_api_settings_form'),
'access arguments' => array('administer cap api'),
'weight' => 10,
'file' => 'stanford_cap_api.admin.inc',
'type' => MENU_LOCAL_TASK,
);
}
return $items;
}
/**
* Implements hook_permission().
*/
function stanford_cap_api_permission() {
$permissions = array(
'administer cap api' => array(
'title' => t('Administer CAP API'),
),
);
return $permissions;
}
/**
* Authenticate with CAP and return an authentication token.
*
* @param string $user
* User name to use to authenticate in CAP API instead of saved one.
* @param string $pass
* Password to use to authenticate in CAP API instead of saved one.
* @param string $auth_uri
* Authentication URI to use to authenticate in CAP API instead of saved one.
*
* @return string
* An authentication token that can be used for API calls or FALSE.
*/
function stanford_cap_api_auth($user = '', $pass = '', $auth_uri = '') {
$token_expire = variable_get('stanford_cap_api_token_expire', REQUEST_TIME);
if ($token_expire <= REQUEST_TIME || !empty($user) || !empty($pass)) {
$auth_uri = empty($auth_uri) ? variable_get('stanford_cap_api_auth_uri', 'https://authz.stanford.edu/oauth/token') : $auth_uri;
$user = empty($user) ? variable_get('stanford_cap_api_username', '') : $user;
$pass = empty($pass) ? variable_get('stanford_cap_api_password', '') : $pass;
$params = array(
'grant_type' => 'client_credentials',
);
if (empty($user) || empty($pass)) {
return FALSE;
}
// Append user/pass, some system doesn't support http_build_url.
$uri = parse_url($auth_uri);
$host = $user . ':' . $pass . '@' . $uri['host'];
$auth_url = str_replace($uri['host'], $host, $auth_uri);
$auth_url = url($auth_url, array('query' => $params, 'external' => TRUE));
$response = drupal_http_request($auth_url);
// Error could be here as well.
if (property_exists($response, 'error')) {
$error_msg = 'Failed to authenticate at CAP API service. Error code is'
. ' %code, error message is "%msg", request string was "%request".' .
' Additional data from response: @data';
$vars = array(
'%code' => $response->code,
'%msg' => isset($response->status_message) ? $response->status_message : $response->error,
'%request' => $auth_url,
'@data' => isset($response->data) ? $response->data : '',
);
watchdog('stanford_cap_api', $error_msg, $vars, WATCHDOG_WARNING);
return FALSE;
}
// Log bad API authentication.
$data = json_decode($response->data, TRUE);
if (array_key_exists('error', $data)) {
$error_msg = 'Error found in CAP API response. Error message is "%msg",'
. ' response data was "%data".';
$vars = array(
'%msg' => $data['error_description'],
'%data' => print_r($data, TRUE),
);
watchdog('stanford_cap_api', $error_msg, $vars, WATCHDOG_WARNING);
return FALSE;
}
// Authentication successful, return the access token.
if (array_key_exists('access_token', $data)) {
variable_set('stanford_cap_api_token_expire', REQUEST_TIME + $data['expires_in']);
variable_set('stanford_cap_api_token', $data['access_token']);
return $data['access_token'];
}
return FALSE;
}
else {
return variable_get('stanford_cap_api_token', '');
}
}
/**
* Issue an API call against an API endpoint.
*
* @param string $endpoint
* Endpoint string.
* @param array $params
* Additional parameters for request.
* @param bool $raw
* Indicates in which form data should be returned, case TRUE JSON will be
* returned, array otherwise.
*
* @return array
* Decoded JSON response or FALSE.
*/
function stanford_cap_api_request($endpoint, $params = array(), $raw = FALSE) {
$api_base = variable_get('stanford_cap_api_base_url', 'https://api.stanford.edu');
$access_token = stanford_cap_api_auth();
// Unable to fetch an auth token.
if (empty($access_token)) {
return FALSE;
}
$params['access_token'] = $access_token;
$request_url = url($api_base . $endpoint, array(
'query' => $params,
'external' => TRUE,
));
$response = drupal_http_request($request_url);
// Error could be here as well.
if (property_exists($response, 'error')) {
$error_msg = 'Failed to fetch data from CAP API service. Error code is'
. ' %code, error message is "%msg", request string was "%request".';
$vars = array(
'%code' => $response->code,
'%msg' => isset($response->status_message) ? $response->status_message : $response->error,
'%request' => $request_url,
);
watchdog('stanford_cap_api', $error_msg, $vars, WATCHDOG_WARNING);
return FALSE;
}
// Log bad API authentication.
$data = json_decode($response->data, TRUE);
if (empty($data)) {
// JSON from response cannot be decoded.
$message = '';
switch (json_last_error()) {
case JSON_ERROR_NONE:
$message .= 'No errors';
break;
case JSON_ERROR_DEPTH:
$message .= 'Maximum stack depth exceeded.';
break;
case JSON_ERROR_STATE_MISMATCH:
$message .= 'Underflow or the modes mismatch.';
break;
case JSON_ERROR_CTRL_CHAR:
$message .= 'Unexpected control character found.';
break;
case JSON_ERROR_SYNTAX:
$message .= 'Syntax error, malformed JSON.';
break;
case JSON_ERROR_UTF8:
$message .= 'Malformed UTF-8 characters, possibly incorrectly encoded.';
break;
default:
$message .= 'Unknown error.';
break;
}
if (function_exists('json_last_error_msg')) {
$message .= ' Additional error info "' . json_last_error_msg() . '".';
}
$message .= ' Request string was "%request".';
$vars = array('%request' => $request_url);
watchdog('stanford_cap_api', $message, $vars, WATCHDOG_WARNING);
return FALSE;
}
else {
if (array_key_exists('error', $data)) {
$error_msg = 'Error found in CAP API response. Error message is "%msg", response data was "%data".';
$vars = array(
'%msg' => $data['error_description'],
'%data' => print_r($data, TRUE),
);
watchdog('stanford_cap_api', $error_msg, $vars, WATCHDOG_WARNING);
return FALSE;
}
else {
if ($raw) {
return $response->data;
}
else {
return $data;
}
}
}
}
/**
* Implements hook_theme().
*/
function stanford_cap_api_theme() {
$path = drupal_get_path('module', 'stanford_cap_api') . '/templates';
return array(
'cap_status_item' => array(
'arguments' => array(
'status' => FALSE,
'message' => '',
'additional' => NULL,
),
'path' => $path,
'template' => 'status_item',
),
'cap_info_item' => array(
'arguments' => array(
'info' => NULL,
'message' => '',
'additional' => NULL,
),
'path' => $path,
'template' => 'info_item',
),
);
}
/**
* Implements hook_batch_alter().
*
* In case batch was set in stanford_cap_api_settings_form and module is not
* configured set batch redirect to details page.
*/
function stanford_cap_api_batch_alter(&$batch) {
$username = variable_get('stanford_cap_api_username', '');
if (($batch['source_url'] == 'admin/settings/cap/config' || $batch['source_url'] == 'admin/settings/cap/config/settings')
&& (empty($username)
|| !variable_get('stanford_cap_api_profiles_schema_synchronized', FALSE)
|| !variable_get('stanford_cap_api_profiles_layout_synced', FALSE)
|| !variable_get('stanford_cap_api_orgs_imported', FALSE))) {
$batch['redirect'] = 'admin/settings/cap/config/details';
}
}
/**
* Run tasks in configured hours.
*
* @param array $tasks
* Array of tasks to run in format:
* @code
* array(
* array('my_function_1', array($arg1)),
* array('my_function_2', array($arg2_1, $arg2_2)),
* array('my_function_3'),
* )
* @endcode
*/
function stanford_cap_api_run_cron($tasks = array()) {
$tz = variable_get('date_default_timezone_name', 'UTC');
$date = date_create(NULL, timezone_open($tz));
$hour_of_day = date_format($date, 'G');
$start_hour = variable_get('stanford_cap_api_cron_start', 1);
$stop_hour = variable_get('stanford_cap_api_cron_stop', 5);
if ($hour_of_day >= $start_hour && $hour_of_day <= $stop_hour) {
// Run passed tasks.
foreach ($tasks as $task) {
if (function_exists($task[0])) {
if (isset($task[1])) {
call_user_func_array($task[0], $task[1]);
}
else {
call_user_func($task[0]);
}
}
}
}
}