-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathncsuroles.module
More file actions
484 lines (399 loc) · 13 KB
/
Copy pathncsuroles.module
File metadata and controls
484 lines (399 loc) · 13 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
<?php
//$Id$
/* vim: set filetype=php tabstop=2 shiftwidth=2 : */
/**
* ncsuroles.module
* Automatically adds user roles from NCSU sources.
*/
define('NCSUROLES_CRON_DEBUG', 0);
/**
* Implementation of hook_menu().
*/
function ncsuroles_menu() {
$items ['admin/config/people/ncsuroles'] = array (
'title' => 'Roles at NCSU',
'description' => 'Configure settings for roles to be applied from sources at NCSU.',
'page callback' => 'drupal_get_form',
'page arguments' => array ('ncsuroles_settings' ),
'access arguments' => array ('administer site configuration' )
);
return $items;
}
/**
* Implementation of hook_settings().
*/
function ncsuroles_settings($form) {
$form['ncsuroles_refresh'] = array(
'#type' => 'select',
'#title' => t('Role Update Period'),
'#default_value' => variable_get('ncsuroles_refresh', '24'),
'#options' => array(
'4' => ' 4 hours',
'8' => ' 8 hours',
'24' => '24 hours',
),
'#description' => t('Select how often the cron process is allowed to look for changes in the roles.'),
);
return system_settings_form($form);
}
/**
* Implementation of hook_user()
*/
function ncsuroles_user($type, &$edit, &$user, $category = NULL) {
// update user roles on new/edited user
if ($type == 'insert' || $type == 'update') {
if ($user && $user->uid > 0) {
$user = user_load(array('uid' => (int)$user->uid));
sync_ncsuroles( $user->uid );
$user = user_load(array('uid' => (int)$user->uid));
// poor-mans merge
$rolelist = ncsuroles_list_roles();
foreach ($rolelist as $role) {
$rid = $role->rid;
if (isset($user->roles[$rid])) {
$edit['roles'][$rid] = $user->roles[$rid];
}
}
}
}
}
/**
* Implementation of hook_cron()
*/
function ncsuroles_cron() {
if (NCSUROLES_CRON_DEBUG) {
print "<pre>====NCSU Roles starting cron updates...\n\n";
}
$lastupdate = variable_get('ncsuroles_lastcron', 0);
$nextupdate = $lastupdate + 3600 * variable_get('ncsuroles_refresh', 24) - 300;
if (time() > $nextupdate ) {
// make sure our roles have not been deleted
rebuild_ncsuroles();
// run update on all users/roles
sync_ncsuroles();
variable_set('ncsuroles_lastcron', time() );
}
else {
if (NCSUROLES_CRON_DEBUG) {
print "Cron refresh has not expired.\n";
}
}
if (NCSUROLES_CRON_DEBUG) {
print "\n====NCSU Roles finished.</pre>\n";
}
}
/*
* Implements db_select()
*
* Returns an associative array with RID as the key, and name as the value.
* This matches the behavior of user_roles()
*
* http://api.drupal.org/api/drupal/includes--database--database.inc/function/db_select/7
*
*/
function get_ncsu_roles($orderBy = 'rid')
{
$query = db_select('ncsuroles', 'n');
$query->fields('n',array('rid','name'))//SELECT the fields from ncsuroles
->orderBy('rid', 'ASC');
$result = $query->execute();
$returnArray = array();
while($record = $result->fetchAssoc()) {
$returnArray[$record['rid']] = $record['name'];
}
return $returnArray;
}
/*
* Synchronize the module ncsuroles entries with the drupal-core
* role table, in case any entries got changed.
*/
function rebuild_ncsuroles() {
drupal_load("module", "user"); //required to call user_role()
$allRoles = user_roles();
$allNCSURoles = get_ncsu_roles();
//iterate through all NCSU Roles
foreach($allNCSURoles as $rid => $name)
{
if(!isset($allRoles[$rid])) {
// set Role weight to be +1 to the highest number that exists in the role table
$query = db_select('role');
$query->addExpression('MAX(weight)');
$weight = $query->execute()->fetchField() + 1;
$insert = db_insert ( 'role' )
->fields ( array (
'rid' => $rid,
'name' => $name,
'weight' => $weight
)
)
->execute ();
if (NCSUROLES_CRON_DEBUG) {
print "(re)inserting rid name weight = $rid $name $weight \n";
}
}
}
}
/*
* Retrieve a list of roles managed by this module
* returns array of rid's
*/
function ncsuroles_list_roles() {
$query = db_select('ncsuroles', 'n');
$query->fields('n')//SELECT the fields from ncsuroles
->orderBy('rid', 'ASC');
$result = $query->execute();
$returnArray = array();
foreach($result as $role) {
$returnArray[$role->rid] = $role;
}
return $returnArray;
}
/*
* Update the roles in drupal for the given user or for all users
* when no uid is passed.
*/
function sync_ncsuroles($uid = 0) {
drupal_load("module", "user"); //required to call different methods in this function
// first, build a list of desired/known users
$userlist = array();
$sqlcond = "status != 0 AND name LIKE '%%.ncsu.edu'";
if ($uid > 0) {
$sqlcond = "uid = $uid";
}
$result = db_query("SELECT uid, name FROM {users} WHERE $sqlcond ORDER BY uid");
foreach($result as $account) {
if ($account && preg_match ( '/^[\f\t]*([a-z0-9_-]{3,8})\.ncsu\.edu/', strtolower ( $account->name ), $parts )) {
$userlist[$parts[1]] = $account->uid;
if (NCSUROLES_CRON_DEBUG) {
print "+ userlist[ $parts[1] ] = $account->uid\n";
}
}
}
// no point in continuing with no users
if (count($userlist) < 1) {
return;
}
// next, build a list of roles to keep updated
$rolelist = ncsuroles_list_roles();
// need our SOAP client
$client = ncsuroles_soap_client();
// some rules for each source type
$byuser = array( "hesiod" => 1, "ldap" => 1 );
$bygroup = array( "afspts" => 1, "systools" => 1 );
// build a sparse 2-D array of role settings
// i.e. $ugrole[uid][rid] = 1
$ugrole = array();
foreach ($userlist as $uid) {
$ugrole[$uid] = array();
}
// handle the by-group roles
foreach ($rolelist as $role) {
if (isset($bygroup[ $role->grouptype ]) && $bygroup[ $role->grouptype ]) {
if (NCSUROLES_CRON_DEBUG) {
print "Looking for members of role $role->rid = $role->name\n";
}
$users = $client->group_members(ncsuroles_soap_auth( $role->grouptype, $role->groupkey ));
foreach ($users as $unity) {
if ( $userlist[$unity] ) {
$uid = $userlist[$unity];
$ugrole[$uid][$role->rid] = 1;
if (NCSUROLES_CRON_DEBUG) {
print " found role: $unity in $role->name\n";
}
}
}
}
} // end of foreach rolelist byrole
// handle the by-user roles
foreach ($byuser as $srctype => $srcval) {
// prebuild a key-to-rid array
$ridname = array();
foreach ($rolelist as $role) {
if ($role->grouptype == $srctype) {
$ridname[ $role->groupkey ] = $role->rid;
}
}
// now do a type lookup on each user to fill in our ugrole
if (count( $ridname ) > 0) {
foreach ($userlist as $unity => $uid) {
$groups = $client->user_groups(ncsuroles_soap_auth($srctype, $unity));
foreach ($groups as $grpkey) {
if (isset($ridname[$grpkey]) && $ridname[$grpkey]) {
$ugrole[$uid][ $ridname[$grpkey] ] = 1;
if (NCSUROLES_CRON_DEBUG) {
print "found role: $unity in $srctype $grpkey\n";
}
}
}
}
}
} // end of foreach byuser
// now update the roles for each user
if (NCSUROLES_CRON_DEBUG) {
print "\nUpdating roles...\n";
}
foreach ($userlist as $uid) {
$account = user_load($uid);
$roles = $account->roles;
if ($account !== FALSE) {
$changes = 0;
foreach ($rolelist as $role) {
$rid = $role->rid;
if (isset($roles[$rid]) && !isset($ugrole[$uid][$rid])) {
unset($roles[$rid]);
$changes++;
watchdog('ncsuroles', "removing role $rid from $uid");
if (NCSUROLES_CRON_DEBUG) {
print " removing role $rid from $uid\n";
}
}
else if (!isset($roles[$rid]) && isset($ugrole[$uid][$rid])) {
$roles[$rid] = "role number $rid";
$changes++;
watchdog('ncsuroles', "adding role $rid to $uid");
if (NCSUROLES_CRON_DEBUG) {
print " adding role $rid to $uid\n";
}
}
}
if ($changes) {
// note: this code is based on user_save, which we
// cannot call here lest we create a loop on our hook_user
foreach ($rolelist as $role) {
$rid = $role->rid;
db_delete ( 'users_roles' )
->condition ( 'rid', $rid )
->condition ( 'uid', $uid )
->execute ();
if (isset($roles[$rid])) {
db_insert ( 'users_roles' )
->fields ( array (
'uid' => $uid,
'rid' => $rid,
))
->execute();
}
}
if (NCSUROLES_CRON_DEBUG) {
print " Saved roles changes for user $uid\n";
}
}
}
}
}
function ncsuroles_soap_auth () {
$soap_auth_key = '225bddea6c2cb7c0a1b966769fd968da';
$args = func_get_args();
$code = md5( $soap_auth_key . implode('',$args) );
array_unshift($args, $code);
return $args;
}
function ncsuroles_soap_client () {
// need our SOAP client
$soapConfig = array(
'location' => 'http://sysnews.ncsu.edu/rpc/soapgroups',
'uri' => 'NCSUGroups',
'trace' => 1,
);
$client = new SoapClient(null, $soapConfig);
return $client;
}
function ncsuroles_form_alter(&$form, $edit, $form_id) {
if ($form_id == 'user_admin_role') {
// look for existing entry to pre-fill the form values
$defaults = array(
'use' => 0,
'type' => 'afspts',
'key' => '',
);
$rid = $form['rid']['#value'];
if ($rid) {
$ncsurole = db_query('SELECT * FROM {ncsuroles} WHERE rid = :rid', array(':rid' => $rid));
foreach($ncsurole as $role) {
if ($role) {
$defaults['use'] = 1;
$defaults['type'] = $role->grouptype;
$defaults['key'] = $role->groupkey;
}
}
}
// shift the name up to make room for our form
$form['name']['#weight'] = -10;
$form['ncsuroles'] = array(
'#type' => 'fieldset',
'#title' => 'NCSU Roles',
'#weight' => -5,
);
$form['ncsuroles']['ncsuroles_use'] = array(
'#type' => 'checkbox',
'#title' => 'Enable NCSU Role Source',
'#default_value' => $defaults['use'],
'#description' => 'If this is checked, this role will be automatically populated using the NCSU group defined by the options below.',
'#weight' => -10,
);
$form['ncsuroles']['ncsuroles_type'] = array(
'#type' => 'select',
'#title' => 'Source Type',
'#default_value' => $defaults['type'],
'#options' => array(
'afspts' => 'AFS PTS Group',
'hesiod' => 'Hesiod Group',
'ldap' => 'LDAP Group',
'systools' => 'SysNews Group',
),
'#description' => 'Select which type of group you want to import for this role.',
'#weight' => -5,
);
$form['ncsuroles']['ncsuroles_key'] = array(
'#type' => 'textfield',
'#title' => 'Group Key',
'#default_value' => $defaults['key'],
'#size' => '40',
'#maxlength' => '80',
'#description' => 'Enter the group identifier for the source group.<br/>'
.'<strong>AFS PTS:</strong> use owner:group@cell, e.g. www:webxteam@unity<br/>'
.'<strong>Hesiod:</strong> use the group id, e.g. ncsu_staff<br/>'
.'<strong>LDAP:</strong> use the group id, e.g. primary_role_E<br/>'
.'<strong>SysNews:</strong> use the systools group id, e.g. oit-iso<br/>',
'#weight' => 0,
);
// add some handlers for the new form pieces
$form['#submit'][] = 'ncsuroles_form_submit';
$form['#validate'][] = 'ncsuroles_form_validate';
}
}
function ncsuroles_form_submit ( $form_id, &$form_state ) {
$vals = $form_state['values'];
// delete entry regardless of setting
$result = db_delete ( 'ncsuroles' )
->condition ( 'rid', $vals['rid'] )
->execute ();
// re-insert entry if use is checked
if ($form_state['values']['ncsuroles_use']) {
$result = db_insert ( 'ncsuroles' )
->fields ( array (
'rid' => $vals['rid'],
'name' => $vals['name'],
'grouptype' => $vals['ncsuroles_type'],
'groupkey' => $vals['ncsuroles_key']
))
->execute();
drupal_set_message('The role source has been updated. The role members will be updated on the next cron run.', 'status');
}
}
function ncsuroles_form_validate ( $form_id, &$form_state ) {
if (!$form_state['values']['ncsuroles_use']) {
return;
}
$type = $form_state['values']['ncsuroles_type'];
$key = $form_state['values']['ncsuroles_key'];
if (!$key) {
form_set_error('ncsuroles_key', t('You must specify a valid group key.'));
return;
}
$client = ncsuroles_soap_client();
$valid = $client->group_exists(ncsuroles_soap_auth( $type, $key ));
if ($valid !== 1) {
form_set_error('ncsuroles_key', 'This group key does not appear to be valid.');
}
}