/[drupal]/contributions/modules/og_reg_keys/og_reg_keys.module
ViewVC logotype

Contents of /contributions/modules/og_reg_keys/og_reg_keys.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.2 - (show annotations) (download) (as text)
Wed Nov 26 19:42:21 2008 UTC (12 months ago) by marcp
Branch: MAIN
CVS Tags: DRUPAL-6--1-0, DRUPAL-6--1-1, HEAD
Branch point for: DRUPAL-6--1
Changes since 1.1: +109 -211 lines
File MIME type: text/x-php
Drupal 6.x port.
1 <?php
2 // $Id$
3
4 /**
5 * @file
6 * Provides group registration keys to restrict group access.
7 */
8
9 /**
10 * Implementation of hook_help().
11 */
12 function og_reg_keys_help($path, $arg) {
13 global $user;
14 switch ($path) {
15 case 'admin/og/reg-keys-settings':
16 $output = '<p>'. t('Settings for Organic Groups registration keys. A user will be auto-approved as member of a group set to <strong>closed</strong> or <strong>moderated</strong> when they supply a group key. Users may also visit the !join page to join a group using a key.', array('!join' => l('join a group', 'og/reg-key-join')));
17 $output .= '</p><p>'. t('You may combine this feature with the usual use of groups in the registration form.') .'</p>';
18 return $output;
19 break;
20 case 'og/reg-key-join':
21 $output = '<p>'. t('You may check a group key by entering it below.');
22 if ($user->uid) {
23 $output .= ' '. t('You may also join a group by submitting its key.');
24 }
25 return $output .'</p>';
26 break;
27 }
28 }
29
30 /**
31 * Implementation of hook_menu().
32 */
33 function og_reg_keys_menu() {
34 $items = array();
35
36 $items['og/reg-key-join'] = array(
37 'title' => 'Use registration key',
38 'page callback' => 'drupal_get_form',
39 'page arguments' => array('og_reg_keys_join'),
40 'weight' => 10,
41 'type' => MENU_LOCAL_TASK,
42 'access callback' => 'user_is_logged_in',
43 );
44 $items['admin/og/reg-keys-settings'] = array(
45 'title' => 'OG Reg Keys Settings',
46 'description' => 'Configure group registration key settings.',
47 'page callback' => 'drupal_get_form',
48 'page arguments' => array('og_reg_keys_settings'),
49 'access callback' => 'user_access',
50 'access arguments' => array('administer organic groups'),
51 );
52 $items['admin/og/reg-keys-edit'] = array(
53 'title' => 'Edit Registration Keys',
54 'description' => 'Edit group registration keys.',
55 'page callback' => 'og_reg_keys_edit_reg_keys',
56 'page arguments' => array(),
57 'access callback' => 'user_access',
58 'access arguments' => array('administer organic groups'),
59 );
60
61 return $items;
62 }
63
64 /**
65 * Implementation of hook_form_$form-id_alter().
66 */
67 function og_reg_keys_form_views_filters_alter(&$form, &$form_state) {
68 if ($form['view']['#value']->name == 'og_reg_keys_edit') {
69 // need to push the return value as setting this in the view overrides the access control
70 $form['#action'] = url('admin/og/reg-keys-edit');
71 }
72 }
73
74 /**
75 * Implementation of hook_form_alter().
76 */
77 function og_reg_keys_form_alter(&$form, &$form_state, $form_id) {
78 if ($form_id == 'og_invite_form') {
79 $key = og_reg_keys_get_key($form['gid']['#value']);
80 if (!empty($key)) {
81 $form['pmessage']['#default_value'] .= strtr(_og_reg_keys_message(), array('%reg_key' => $key)). "\n\n";
82 }
83 }
84 else if (og_is_group_type($form['type']['#value'])) {
85 $result = db_query("SELECT (code) FROM {og_reg_keys} WHERE nid = %d", $form['nid']['#value']);
86 if ($result) {
87 $value = db_fetch_array($result);
88 $value = $value['code'];
89 }
90 else {
91 $value = '';
92 }
93 $form['og_reg_keys'] = array(
94 '#type' => 'textfield',
95 '#title' => t('Group registration key'),
96 '#default_value' => $value,
97 '#description' => t('Enter a registration key if you want to allow users to enter a key to join this group. Leave this field blank if you do not want to allow users to join this group with a registration key.'),
98 '#size' => 64,
99 );
100 }
101 }
102
103 /**
104 * Implementation of hook_user().
105 */
106 function og_reg_keys_user($op, &$edit, &$account, $category = NULL) {
107 if (!module_exists('og')) {
108 return;
109 }
110
111 switch ($op) {
112 case 'validate':
113 // Reg key is only present during registration
114 if (isset($edit['og_reg_key'])) {
115 if ($edit['og_reg_key'] != '') {
116 if (!og_reg_keys_valid_key($edit['og_reg_key'])) {
117 form_set_error('og_reg_key', t('Not a valid group registration key.'));
118 }
119 }
120 }
121 break;
122 case 'insert':
123 // Reg key is only present during registration
124 if (isset($edit['og_reg_key']) && og_reg_keys_valid_key($edit['og_reg_key'])) {
125 $gid = og_reg_keys_get_gid($edit['og_reg_key']);
126 $return = og_save_subscription($gid, $account->uid, array('is_active' => 1));
127 if (!empty($return['message'])) {
128 drupal_set_message($return['message']);
129 }
130 $rid = variable_get('og_reg_keys_role', 0);
131 if ($rid) {
132 // Pass to user_save() the roles where the key is role id (value doesn't matter eg. 1)
133 $account = user_save($account, array('roles' => array($rid => $rid)));
134 }
135 }
136 // no redirect to node as this is someone adding users through the standard interface
137 break;
138 case 'register':
139 $form['og_reg_key'] = array(
140 '#type' => 'textfield',
141 '#title' => t('Group registration key'),
142 '#required' => variable_get('og_reg_key_required', 1),
143 '#description' => '',
144 '#size' => 64,
145 );
146
147 return $form;
148 break;
149 }
150 }
151
152 /**
153 * Implementation of hook_nodeapi().
154 */
155 function og_reg_keys_nodeapi(&$node, $op) {
156 if (og_is_group_type($node->type)) {
157 switch ($op) {
158 case 'load':
159 $result = db_query('SELECT code FROM {og_reg_keys} WHERE nid = %d', $node->nid);
160 $r = db_fetch_array($result);
161 if ($r) {
162 return array('og_reg_keys' => $r['code']);
163 }
164 break;
165 case 'validate': // validate used on group updates
166 if (!og_reg_keys_validate_key($node)) {
167 form_set_error('og_reg_keys', t("The key '!og_reg_keys' is already in use by a different group", array('!og_reg_keys' => $node->og_reg_keys)));
168 }
169 break;
170 case 'insert': // insert used on new group inserts
171 case 'update': // submit used on group updates
172 if (!empty($node->nid)) {
173 $result = db_query('SELECT (nid) FROM {og_reg_keys} WHERE nid = %d', $node->nid);
174 $r = db_fetch_array($result);
175
176 if ($node->og_reg_keys != '') {
177 if ($r) {
178 db_query("UPDATE {og_reg_keys} SET code = '%s' WHERE nid = %d", $node->og_reg_keys, $node->nid);
179 }
180 else {
181 db_query("INSERT INTO {og_reg_keys} VALUES (%d, '%s')", $node->nid, $node->og_reg_keys);
182 }
183 }
184 elseif ($r) {
185 db_query("DELETE FROM {og_reg_keys} WHERE nid = %d", $node->nid); // remove the key
186 }
187 }
188 break;
189 case 'delete': // node deletion
190 db_query('DELETE FROM {og_reg_keys} WHERE nid = %d', $node->nid);
191 break;
192 }
193 }
194 }
195
196 /**
197 * Implementation of hook_views_api().
198 */
199 function og_reg_keys_views_api() {
200 return array(
201 'api' => 2,
202 );
203 }
204
205 /**
206 * Menu callback for 'admin/og/reg-keys-edit'
207 */
208 function og_reg_keys_edit_reg_keys() {
209 if (user_access('administer organic groups')) {
210 return views_embed_view('og_reg_keys_edit', 'page');
211 }
212 else {
213 drupal_access_denied();
214 }
215 }
216
217
218 /**
219 * Menu callback for 'admin/og/reg-keys-settings'
220 */
221 function og_reg_keys_settings() {
222
223 $roles = user_roles(TRUE);
224 $roles[DRUPAL_AUTHENTICATED_RID] = '<'. t('None') .'>';
225
226 $form['og_reg_keys_role'] = array(
227 '#type' => 'select',
228 '#title' => t('Role for new registrants'),
229 '#default_value' => variable_get('og_reg_keys_role', DRUPAL_AUTHENTICATED_RID),
230 '#options' => $roles,
231 '#description' => t('Pick an additional user role that will be assigned to all new users registering with a valid group registration key.'),
232 );
233
234 $form['og_reg_keys_message'] = array(
235 '#type' => 'textarea',
236 '#title' => t('Text to be added to group invitation e-mails'),
237 '#default_value' => _og_reg_keys_message(),
238 '#required' => TRUE,
239 '#description' => t("The token '%reg_key' must be included and will be replaced by the group's registration key."),
240 );
241
242 $form['og_reg_key_required'] = array(
243 '#type' => 'checkbox',
244 '#title' => t('Registration Key Required for new account creation'),
245 '#default_value' => variable_get('og_reg_key_required', 1),
246 );
247
248 return system_settings_form($form);
249
250 }
251
252 /**
253 * Validation routine for form submission of 'admin/og/reg-keys-settings'
254 */
255 function og_reg_keys_settings_validate($form, &$form_state) {
256 $op = isset($_POST['op']) ? $_POST['op'] : '';
257
258 if ($op == t('Save configuration') && !strstr($form_state['values']['og_reg_keys_message'], '%reg_key')) {
259 form_set_error('og_reg_keys_message', t("You must include in your message the token '%reg_key'"));
260 }
261 }
262
263
264 /**
265 * Menu callback function for "check group" and "join a group" page.
266 * 'og/reg-key-join' this is also used by og_reg_keys_contents()
267 */
268 function og_reg_keys_join($size = 64) {
269 global $user;
270 $form['og_reg_key'] = array(
271 '#type' => 'textfield',
272 '#title' => t('Group registration key'),
273 '#required' => TRUE,
274 '#size' => $size,
275 );
276
277 $form['#after_build'] = array('og_reg_keys_add_preview');
278
279 $form['preview'] = array(
280 '#type' => 'button',
281 '#value' => t('Check key'),
282 );
283
284 if ($user->uid > 0) {
285 $form['submit'] = array(
286 '#type' => 'submit',
287 '#value' => t('Join'),
288 );
289 }
290 return $form;
291 }
292
293 /**
294 * Validation routine for 'og/reg-key-join' and the block submitted reg-key form
295 */
296 function og_reg_keys_join_validate($form, &$form_state) {
297 $result = db_query("SELECT (nid) FROM {og_reg_keys} WHERE code = '%s'", $form_state['values']['og_reg_key']);
298 $r = db_fetch_array($result);
299 if (!$r) {
300 form_set_error('og_reg_key', t('This is not a valid group registration key.'));
301 }
302 }
303
304 /**
305 * Routine to handle form submission for 'og/reg-key-join' and the block submitted reg-key form
306 */
307 function og_reg_keys_join_submit($form, &$form_state) {
308 global $user;
309 if ($user->uid) {
310 $gid = og_reg_keys_get_gid($form_state['values']['og_reg_key']);
311
312 // Use og_save_subscription() to get around og_subscribe_user()'s
313 // selectivity checks.
314 og_save_subscription($gid, $user->uid, array('is_active' => 1));
315
316 // Existing user so preserve roles as user_save is destructive
317 $roles = $user->roles + array(variable_get('og_reg_keys_role', DRUPAL_AUTHENTICATED_RID) => 1);
318 user_save($user, array('roles' => $roles));
319
320 // Delete the user's menu cache in order to provide access
321 // to menu items secured by their newly granted role.
322 cache_clear_all($user->uid .':', 'cache_menu', TRUE);
323
324 // Load the group node to get the name of the group.
325 $group = node_load(array('nid' => $gid));
326 drupal_set_message(t('You are now a member of !group_name.', array('!group_name' => $group->title)));
327 drupal_goto('node/'. $gid);
328 }
329 else {
330 drupal_access_denied();
331 }
332 }
333
334 /**
335 * Routine used to build preview info for what would happen if the user submitted the form
336 * with og_reg_key present
337 */
338 function og_reg_keys_add_preview($form, &$form_state) {
339 $op = isset($form['#post']['op']) ? $form['#post']['op'] : '';
340 if ($op == t('Check key')) {
341 drupal_validate_form($form['form_id']['#value'], $form, $form_state);
342 if (!form_get_errors()) {
343 $gid = og_reg_keys_get_gid($form['og_reg_key']['#value']);
344 $node = node_load(array('nid' => $gid));
345 $preview = theme('og_reg_keys_join_preview', $node);
346 $form['#prefix'] = isset($form['#prefix']) ? $preview . $form['#prefix'] : $preview;
347 }
348 }
349 return $form;
350 }
351
352 /**
353 * Routine used to appropriately theme the node information for purposes of previewing
354 * form submission with a reg-key present
355 */
356 function theme_og_reg_keys_join_preview($node) {
357 $output = '<div class="preview">';
358 $output .= '<h3>'. t('By submitting this key, you will join this group:') .'</h3>';
359 $output .= node_view($node, TRUE, FALSE, FALSE);
360 $output .= "</div>\n";
361
362 return $output;
363 }
364
365 /**
366 * Implementation of hook_theme().
367 */
368 function og_reg_keys_theme() {
369 return array(
370 'og_reg_keys_join_preview' => array(
371 'arguments' => array('node' => NULL),
372 ),
373 );
374 }
375
376 /**
377 * Implementation of hook_block().
378 */
379 function og_reg_keys_block($op = 'list', $delta = 0, $edit = array()) {
380 global $user;
381 switch ($op) {
382 case 'list' :
383 $blocks = array();
384 $blocks[0] = array('info' => t('Enroll with registration key'));
385 return $blocks;
386 break;
387 case 'view' :
388 if ($user->uid > 0) {
389 // user is logged in just show them the reg key form
390 $block['subject'] = t('Enroll in a group');
391 $block['content'] = _og_reg_keys_logged_in_message();
392 $block['content'] .= og_reg_keys_contents(1);
393 }
394 else {
395 // user is not logged in
396 $block = array();
397 $block['subject'] = t('Create a new account');
398 $block['content'] = _og_reg_keys_register_message();
399 $block['content'] .= og_reg_keys_contents(0);
400 }
401 return $block;
402 break;
403 case 'configure' :
404 $items['og_reg_keys_register_settings'] = array(
405 '#type' => 'fieldset',
406 '#title' => t('User is not logged in'),
407 '#collapsible' => TRUE,
408 );
409 $items['og_reg_keys_register_settings']['og_reg_keys_register_message'] = array(
410 '#type' => 'textarea',
411 '#rows' => 3,
412 '#title' => t('Message to display to users who are registering for the site with a key'),
413 '#default_value' => _og_reg_keys_register_message(),
414 );
415 $items['og_reg_keys_logged_in_settings'] = array(
416 '#type' => 'fieldset',
417 '#title' => t('User is logged in'),
418 '#collapsible' => TRUE,
419 );
420 $items['og_reg_keys_logged_in_settings']['og_reg_keys_logged_in_message'] = array(
421 '#type' => 'textarea',
422 '#rows' => 3,
423 '#title' => t('Message to display to logged in users who are joining a group'),
424 '#default_value' => _og_reg_keys_logged_in_message(),
425 );
426 return $items;
427 break;
428 case 'save' :
429 if (isset($edit['og_reg_keys_register_message'])) {
430 variable_set('og_reg_keys_register_message', $edit['og_reg_keys_register_message']);
431 }
432 if (isset($edit['og_reg_keys_logged_in_message'])) {
433 variable_set('og_reg_keys_logged_in_message', $edit['og_reg_keys_logged_in_message']);
434 }
435 break;
436 }
437 }
438
439 /**
440 * Helper function for hook_block
441 * @param int $block 0 => return form for new user 1=> return form for authenticated user
442 * @return string Returns a rendered drupal form via drupal_get_form()
443 */
444 function og_reg_keys_contents($block) {
445 switch ($block) {
446 case 0:
447 // new user register
448 return drupal_get_form('og_reg_keys_register');
449 break;
450 case 1:
451 // existing user just show registration code
452 return drupal_get_form('og_reg_keys_join', 28);
453 break;
454 }
455 }
456
457 /**
458 * Form definition for registration form called indirectly via hook_block for new users
459 */
460 function og_reg_keys_register() {
461 $form['name'] = array(
462 '#type' => 'textfield',
463 '#title' => t('Username'),
464 '#required' => TRUE,
465 '#default_value' => '',
466 '#size' => 16,
467 '#maxlength' => 60
468 );
469
470 $form['pass'] = array(
471 '#type' => 'password',
472 '#title' => t('Password'),
473 '#required' => TRUE,
474 '#default_value' => '',
475 '#size' => 16,
476 '#maxlength' => 32
477 );
478
479 $form['mail'] = array(
480 '#type' => 'textfield',
481 '#title' => t('Email'),
482 '#description' => t('email address is optional'),
483 '#default_value' => '',
484 '#size' => 28,
485 '#maxlength' => 64
486 );
487
488 $form['og_reg_key'] = array(
489 '#type' => 'textfield',
490 '#title' => t('Group registration key'),
491 '#required' => variable_get('og_reg_key_required', 1),
492 '#size' => 28,
493 );
494
495 $form['submit'] = array('#type' => 'submit', '#value' => t('Create account'));
496 return $form;
497 }
498
499 /**
500 * Validation routine for new user registration form
501 */
502 function og_reg_keys_register_validate($form, &$form_state) {
503 $error = _og_reg_keys_validate_user($form_state['values']['name'], $form_state['values']['mail']);
504
505 if (!empty($error)) {
506 foreach ($error as $errkey => $errval) {
507 form_set_error($errkey, $errval);
508 }
509 }
510
511 if (!og_reg_keys_valid_key($form_state['values']['og_reg_key'])) {
512 form_set_error('og_reg_key', t('This is not a valid group registration key, or group membership is by invite only.'));
513 }
514 }
515
516 /**
517 * Routine to submit new user registration form. This process creates new users, and adds og subscriptions
518 */
519 function og_reg_keys_register_submit($form, &$form_state) {
520 watchdog('user', 'New user: %name %email.', array('%name' => $form_state['values']['name'], '%email' => '<'. $form_state['values']['mail'] .'>'));
521
522 user_save('', array('name' => $form_state['values']['name'],
523 'pass' => $form_state['values']['pass'],
524 'init' => $form_state['values']['mail'],
525 'mail' => $form_state['values']['mail'],
526 'roles' => array(variable_get('og_reg_keys_role', DRUPAL_AUTHENTICATED_RID) => 1),
527 'status' => 1));
528 $user = user_authenticate($form_state['values']);
529
530 $gid = og_reg_keys_get_gid($form_state['values']['og_reg_key']);
531
532 // Use og_save_subscription() to get around og_subscribe_user()'s
533 // selectivity checks.
534 og_save_subscription($gid, $user->uid, array('is_active' => 1));
535
536 // Load the group node to get the name of the group.
537 $group = node_load(array('nid' => $gid));
538 drupal_set_message(t('You are now a member of !group_name.', array('!group_name' => $group->title)));
539 drupal_goto('node/'. $gid);
540 }
541
542 /**
543 * Given a particular group registration key this will return the corresponding
544 * group node id. If no group is associated with that key then 0 is returned
545 * @param string $key A group registration key
546 * @return int 0 if no match found otherwise a nodeid for the corresponding group
547 */
548 function og_reg_keys_get_gid($key) {
549 $result = db_query("SELECT (nid) FROM {og_reg_keys} WHERE code = '%s'", $key);
550 $r = db_result($result);
551 if ($r && $key != '') {
552 return $r;
553 }
554 else {
555 return 0;
556 }
557 }
558
559 /**
560 * Get the registration key for a given group. If no key is present '' is returned
561 * @param int $gid The group id to lookup the key for
562 * @return string Either a group registration key or '' if no key set for $gid
563 */
564 function og_reg_keys_get_key($gid) {
565 $result = db_query("SELECT (code) FROM {og_reg_keys} WHERE nid = %d", $gid);
566 $r = db_result($result);
567 if ($r) {
568 return $r;
569 }
570 else {
571 return '';
572 }
573 }
574
575 /**
576 * Checks to see if a given og_reg_key is valid and has a corresponding group
577 * @param string $key The key to check for validity.
578 * @return bool True if $key != '' and $key is a valid key for one group False otherwise
579 */
580 function og_reg_keys_valid_key($key) {
581 $gid = og_reg_keys_get_gid($key);
582 if (!empty($gid) && og_reg_keys_get_key($gid) == $key) {
583 return TRUE;
584 }
585 else {
586 return FALSE;
587 }
588 }
589
590 /**
591 * This function returns true if the key in question is valid for a group to use.
592 * returns false if the key is in use by another node
593 * returns true otherwise or if == ''
594 */
595 function og_reg_keys_validate_key($node) {
596 if ($node->og_reg_keys != '') {
597 // see if the key is already in use by another group
598 $result = db_query("SELECT (nid) FROM {og_reg_keys} WHERE nid <> %d AND code = '%s'", $node->nid, $node->og_reg_keys);
599 $r = db_fetch_array($result);
600 if ($r) {
601 return FALSE; // key is in use
602 }
603 else {
604 return TRUE;
605 }
606 }
607 else {
608 return TRUE;
609 }
610 }
611
612 /**
613 * Return the group join message.
614 */
615 function _og_reg_keys_message() {
616 return variable_get('og_reg_keys_message', t("To join this group, use the registration key %reg_key"));
617 }
618
619 /**
620 * Return the message in the registration block for logged in users.
621 */
622 function _og_reg_keys_logged_in_message() {
623 return variable_get('og_reg_keys_logged_in_message', t('Use a registration key to enroll in a group.'));
624 }
625
626 /**
627 * Return the message in the registration block for users who are registering for the site.
628 */
629 function _og_reg_keys_register_message() {
630 return variable_get('og_reg_keys_register_message', t('Use a registration key to join the site and enroll in a group. If you are already a member, sign in first, and then use your registration key.'));
631 }
632
633 /*
634 * _reg_keys_validate_user() is based on _userplus_validate_user().
635 *
636 * returns array with errors set or empty on valid
637 */
638 function _og_reg_keys_validate_user($name = NULL, $mail = NULL) {
639 $error = array();
640 if ($name) {
641 // Validate the username:
642 if ($err = user_validate_name($name)) {
643 $error['name'] = $err;
644 }
645 else if (db_result(db_query('SELECT COUNT(*) FROM {users} WHERE LOWER(name) = LOWER("%s")', $name)) > 0) {
646 $error['name'] = t('The name %name is already taken.', array('%name' => $name));
647 }
648 else if (drupal_is_denied('user', $name)) {
649 $error['name'] = t('The name %name has been denied access.', array('%name' => $name));
650 }
651 }
652
653 // Validate the e-mail address: (empty is okay);
654 if (!empty($mail)) {
655 if ($err = user_validate_mail($mail)) {
656 $error['mail'] = $err;
657 }
658 else if (db_result(db_query('SELECT COUNT(*) FROM {users} WHERE LOWER(mail) = LOWER("%s")', $mail)) > 0) {
659 $error['mail'] = t('The e-mail address %email is already taken.', array('%email' => $mail));
660 }
661 else if (drupal_is_denied('mail', $mail)) {
662 $error['mail'] = t('The e-mail address %email has been denied access.', array('%email' => $mail));
663 }
664 }
665
666 return $error;
667 }

  ViewVC Help
Powered by ViewVC 1.1.2