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

Contents of /contributions/modules/fudforum/fudforum.module

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


Revision 1.21 - (show annotations) (download) (as text)
Mon Oct 26 20:33:50 2009 UTC (4 weeks, 2 days ago) by naudefj
Branch: MAIN
CVS Tags: HEAD
Changes since 1.20: +3 -3 lines
File MIME type: text/x-php
Make it easier to translate strings
1 <?php
2 // $Id: fudforum.module,v 1.20 2009/10/26 19:30:23 naudefj Exp $
3 // Code based on http://books.google.co.za/books?id=VmZrdGuBZCMC&pg=PA130
4
5 function _fudforum_settings() {
6 /* load forum config */
7 $fudinc = variable_get('fudforum_inc', '/path/to/GLOBALS.php');
8 $data = file_get_contents($fudinc);
9 eval(str_replace('<?php', '', substr_replace($data, '', strpos($data, 'require'))));
10
11 /* Export variables required later */
12 $GLOBALS['FUD_HOST'] = $DBHOST;
13 $GLOBALS['FUD_USER'] = $DBHOST_USER;
14 $GLOBALS['FUD_PASS'] = $DBHOST_PASSWORD;
15 $GLOBALS['FUD_DB'] = $DBHOST_DBNAME;
16 $GLOBALS['FUD_PREFIX'] = $DBHOST_TBL_PREFIX;
17 $GLOBALS['COOKIE_NAME'] = $COOKIE_NAME;
18 $GLOBALS['COOKIE_DOMAIN'] = $COOKIE_DOMAIN;
19 $GLOBALS['FUD_TIMEOUT'] = $LOGEDIN_TIMEOUT;
20 $GLOBALS['FUD_URL'] = $WWW_ROOT . variable_get('fudforum_root', 'index.php') .'/';
21 $GLOBALS['FUD_URL'] = preg_replace('/\/\/$/', '/', $GLOBALS['FUD_URL']);
22 }
23
24 function _fudforum_connect() {
25 _fudforum_settings();
26
27 // mysql_query("SET NAMES 'utf8'");
28 $fuddb = mysql_connect($GLOBALS['FUD_HOST'], $GLOBALS['FUD_USER'], $GLOBALS['FUD_PASS'], true);
29 if (!$fuddb) {
30 watchdog('FUDforum', 'Unable to connect to database!');
31 return FALSE;
32 }
33
34 $db_selected = mysql_select_db($GLOBALS['FUD_DB'], $fuddb);
35 if (!$db_selected) {
36 watchdog('FUDforum', 'Unable to select database!');
37 return FALSE;
38 }
39
40 return $fuddb;
41 }
42
43 function _fudforum_query($qstr) {
44 $qstr = preg_replace('/{([^}]+)}/', $GLOBALS['FUD_PREFIX'] .'\\1', $qstr);
45 $q = mysql_query($qstr);
46 return $q;
47 }
48
49 function _fudforum_disconnect($fuddb) {
50 mysql_close($fuddb);
51 }
52
53 function fudforum_help($path, $arg) {
54 $output = '';
55
56 switch ($path) {
57 case 'admin/help#fudforum':
58 break;
59 case 'admin/modules#description':
60 $output .= t('This module provides integration with FUDforum: New forum posts, Forum statistics, Login block and extenal authentication against the forum user base.');
61 break;
62 }
63
64 return $output;
65 }
66
67 function fudforum_menu() {
68 $items = array();
69 $items['admin/settings/fudforum'] = array(
70 'title' => 'FUDforum settings',
71 'description' => t('Change FUDforum integration settings'),
72 'page callback' => 'drupal_get_form',
73 'page arguments' => array('fudforum_admin_settings'),
74 'access arguments' => array('administer site configuration'),
75 'type' => MENU_NORMAL_ITEM,
76 );
77 return $items;
78 }
79
80 // function fudforum_admin_settings($form_state) {
81 function fudforum_admin_settings() {
82 // Only administrators can access this page
83 if (!user_access('access administration pages'))
84 return message_access();
85
86 $form = array();
87 $form['fudstatus'] = array('#type' => 'fieldset',
88 '#title' => t('FUDforum status'),
89 '#collapsible' => TRUE,
90 '#collapsed' => FALSE);
91
92 $roles = user_roles(1);
93 if ( array_search('forum user', $roles) === FALSE)
94 $form['fudstatus']['info1'] = array('#type' => 'markup',
95 '#value' => '<div class="error">Please create a "forum user" role as per install instructions!</div>');
96 if ( array_search('forum moderator', $roles) === FALSE)
97 $form['fudstatus']['info2'] = array('#type' => 'markup',
98 '#value' => '<div class="error">Please create a "forum moderator" role as per install instructions!</div>');
99
100 $fudinc = variable_get('fudforum_inc', '/path/to/GLOBALS.php');
101 if (file_exists($fudinc)) {
102
103 $fuddb = _fudforum_connect();
104 if (!$fuddb)
105 $form['fudstatus']['info3'] = array('#type' => 'markup',
106 '#value' => '<div class="error">Unable to connect to the FUDforum database. Please fix your forum settings!</div>');
107 else {
108 $form['fudstatus']['info4'] = array('#type' => 'markup',
109 '#value' => '<div class="ok">Successfully connected to the FUDforum database.</div>');
110 _fudforum_disconnect($fuddb);
111 }
112
113 } else {
114 $form['fudstatus']['info5'] = array('#type' => 'markup',
115 '#value' => '<div class="error">Error locating GLOBALS.php. Please fix your settings!</div>');
116 }
117
118 $form['fudsettings'] = array('#type' => 'fieldset',
119 '#title' => t('FUDforum settings'),
120 '#collapsible' => TRUE,
121 '#collapsed' => FALSE);
122
123 $form['fudsettings']['fudforum_inc'] = array('#type' => 'textfield',
124 '#title' => t('Path to GLOBALS.php'),
125 '#maxlength' => '128', '#size' => '60',
126 '#default_value' => $fudinc,
127 '#description' => t('Enter the full directory path where FUDforum\'s GLOBALS.php file is located.'));
128 $form['fudsettings']['fudforum_root'] = array('#type' => 'textfield',
129 '#title' => t('FUDforum root'),
130 '#maxlength' => '30', '#size' => '30',
131 '#default_value' => variable_get('fudforum_root', 'index.php'),
132 '#description' => t('File to call in forum directory. This setting is used when linking to the forum.'));
133
134 return system_settings_form($form);
135 }
136
137 function fudforum_init() {
138 global $user;
139
140 // Try to log user in
141 if (!$user->uid) {
142 _fudforum_settings(); // Get FUDforum's cookie name
143 if ( ! empty($_COOKIE[ $GLOBALS['COOKIE_NAME'] ]) ) {
144 // drupal_set_message("Forum cookie found, try autologin");
145 $fuddb = _fudforum_connect();
146 $sess = $_COOKIE[ $GLOBALS['COOKIE_NAME'] ];
147 $q = _fudforum_query('SELECT u.login, u.passwd FROM {ses} s INNER JOIN {users} u ON u.id=(CASE WHEN u.id > 1 AND s.user_id>2000000000 THEN 1 ELSE s.user_id END) WHERE s.ses_id = "'. mysql_real_escape_string($sess) . '"');
148 $r = mysql_fetch_row($q);
149 fudforum_authenticate( array("name" => $r[0], "pass" => $r[1]) );
150 }
151 }
152 }
153
154 function fudforum_block($op = 'list', $delta = 0, $edit = array()) {
155 if ($op == 'list') {
156 $blocks[0]['info'] = t('FUDforum: User login');
157 $blocks[1]['info'] = t('FUDforum: New forum posts');
158 $blocks[2]['info'] = t('FUDforum: Online forum users');
159 $blocks[3]['info'] = t('FUDforum: Forum statistics');
160 return $blocks;
161 }
162 else if ($op == 'view') {
163 global $user;
164 $block = array();
165
166 switch ($delta) {
167 case 0:
168 // avoid showing two login forms on one page.
169 if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
170 $block['subject'] = t('User login');
171 $block['content'] = drupal_get_form('fudforum_login_form');
172 }
173 return $block;
174
175 case 1:
176 $fuddb = _fudforum_connect();
177 if ($fuddb) {
178 $q = _fudforum_query('SELECT distinct thread_id, subject FROM {msg} ORDER BY post_stamp DESC LIMIT 10');
179 $c = '<div class="item-list"><ul>';
180 while ( $r = mysql_fetch_row($q) ) {
181 $c .= '<li><a href="'. $GLOBALS['FUD_URL'] .'t/' . $r[0] . '/0/">' . $r[1] . '</a><br/>';
182 }
183 _fudforum_disconnect($fuddb);
184 $c .= '</ul></div>';
185 $c .= '<div class="more-link"><a href="'. $GLOBALS['FUD_URL'] .'" title="Enter the Forum.">more</a></div>';
186 }
187
188 $block['subject'] = t('New forum posts');
189 $block['content'] = $c;
190 return $block;
191
192 case 2:
193 $fuddb = _fudforum_connect();
194 if ($fuddb) {
195 $tm_expire = time() - ($GLOBALS['FUD_TIMEOUT'] * 60);
196 $q = _fudforum_query('SELECT u.id, u.alias, s.time_sec, (u.users_opt &32768) as private FROM {ses} s INNER JOIN {users} u ON s.user_id=u.id WHERE time_sec>'.$tm_expire);
197 while ( $r = mysql_fetch_row($q) ) {
198 $c .= '<li><a href="'. $GLOBALS['FUD_URL'] .'u/' . $r[0] . '/0/">' . $r[1] . '</a><br/>';
199 }
200 _fudforum_disconnect($fuddb);
201 if (isset($c))
202 $c = '<div class="item-list"><ul>'. $c .'</ul></div>';
203 else
204 $c = 'Nobody';
205 }
206 $block['subject'] = t('Online forum users');
207 $block['content'] = $c;
208 return $block;
209
210 case 3:
211 $fuddb = _fudforum_connect();
212 if ($fuddb) {
213 $q = _fudforum_query('SELECT count(*) FROM {users}');
214 $r = mysql_fetch_row($q);
215 $c = 'Registered users: '. $r[0] . '<br />';
216 $q = _fudforum_query('SELECT count(*) FROM {msg}');
217 $r = mysql_fetch_row($q);
218 $c .= 'Messages posted: '. $r[0] . '<br />';
219 $q = _fudforum_query('SELECT count(*) FROM {thread}');
220 $r = mysql_fetch_row($q);
221 $c .= 'Threads: '. $r[0] . '<br />';
222 $tm_expire = time() - ($GLOBALS['FUD_TIMEOUT'] * 60);
223 $q = _fudforum_query('SELECT count(*) FROM {ses} WHERE time_sec>'.$tm_expire.' AND user_id<2000000000');
224 $r = mysql_fetch_row($q);
225 $c .= 'Users online: '. $r[0] . '<br />';
226 $q = _fudforum_query('SELECT MAX(id) FROM {users}');
227 $r = mysql_fetch_row($q);
228 $q = _fudforum_query('SELECT id, alias FROM {users} WHERE id='. $r[0]);
229 $r = mysql_fetch_row($q);
230 $c .= 'Newest user: <a href="'. $GLOBALS['FUD_URL'] .'u/' . $r[0] . '/0/">' . $r[1] . '</a><br />';
231 }
232
233 $block['subject'] = t('Forum statistics');
234 $block['content'] = $c;
235 return $block;
236 }
237 }
238 }
239
240 function fudforum_login_form($form_state) {
241 $form = array(
242 '#action' => url($_GET['q'], array('query' => drupal_get_destination())),
243 '#id' => 'user-login-form',
244 '#validate' => array('fudforum_login_validate') + user_login_default_validators(),
245 '#submit' => array('user_login_submit'),
246 );
247 $form['name'] = array('#type' => 'textfield',
248 '#title' => t('User'),
249 '#maxlength' => 30,
250 '#size' => 15,
251 '#required' => TRUE,
252 );
253 $form['pass'] = array('#type' => 'password',
254 '#title' => t('Password'),
255 '#size' => 15,
256 '#maxlength' => 16, // FUDforum's limit
257 '#required' => TRUE,
258 );
259 $form['submit'] = array('#type' => 'submit',
260 '#value' => t('Login'),
261 );
262
263 _fudforum_settings(); // Get forum URL
264 $form['links'] = array('#value' => '<br />' .
265 '[ <a href="'. $GLOBALS['FUD_URL'] .'re/0/">Register</a> ] '.
266 '[ <a href="'. $GLOBALS['FUD_URL'] .'rst/0/">Forgot password</a> ]'
267 );
268 # $links['register'] = array(
269 # 'title' => t('Register'),
270 # 'href' => $GLOBALS['FUD_URL'] .'re/0/',
271 # 'attributes' => array('title' => t('Create a new user account.'))
272 # );
273 # $links['reset_password'] = array(
274 # 'title' => t('Forgot password'),
275 # 'href' => $GLOBALS['FUD_URL'] .'rst/0/',
276 # 'attributes' => array('title' => t('Request new password via e-mail.'))
277 # );
278 # $form['links'] = array('#value' => theme('links', $links));
279
280 return $form;
281 }
282
283 /**
284 * Implementation of hook_form_alter().
285 * We replace the local login validation handler with our own.
286 */
287 function fudforum_form_alter(&$form, $form_state, $form_id) {
288 if ($form_id == 'user_login' || $form_id == 'user_login_block') {
289
290 // If the user login form is being submitted, add our validation handler.
291 if (isset($form_state['post']['name'])) {
292 // Find the local validation function's entry so we can replace it.
293 $array_key = array_search('user_login_authenticate_validate', $form['#validate']);
294
295 if ($array_key === FALSE) {
296 // Could not find it. Some other module must have run form_alter().
297 // We will simply add our validation just before the final validator.
298 $final_validator = array_pop($form['#validate']);
299 $form['#validate'][] = 'fudforum_login_validate';
300 $form['#validate'][] = $final_validator;
301 }
302 else {
303 // Found the local validation function, replace with ours
304 $form['#validate'][$array_key] = 'fudforum_login_validate';
305 }
306 }
307 }
308 }
309
310 /**
311 * Login form validation handler.
312 */
313 function fudforum_login_validate($form, &$form_state) {
314 global $user;
315 if (!empty($user->uid)) {
316 // Another module already handles authentication
317 return;
318 }
319 // Call our custom authentication function
320 if (!fudforum_authenticate($form_state['values'])) {
321 // Authentication failed
322 form_set_error('user', t('Invalid login/password combination.'));
323 }
324 }
325
326 /**
327 * Custom authentication function
328 */
329 function fudforum_authenticate($form_values) {
330 global $user;
331
332 $login = $form_values['name'];
333 $passwd = $form_values['pass'];
334
335 $fuddb = _fudforum_connect();
336 if ($fuddb) {
337 $q = _fudforum_query('SELECT email, join_date, time_zone, sig, ban_expiry, name, location, occupation, users_opt FROM {users} WHERE login=\''.$login.'\' AND passwd=\''.md5($passwd).'\' OR passwd=\''.$passwd.'\'');
338 $r = mysql_fetch_row($q);
339 _fudforum_disconnect($fuddb);
340 }
341
342 if (!$r)
343 return FALSE; // user not found
344
345 // User status: 1=active, 0=banned
346 $status = ($r[4] == 0) ? 1 : 0;
347 if ($status != 1)
348 return FALSE; // user is banned
349
350 // Convert timezone
351 $SaveZone = getenv ('TZ');
352 putenv('TZ='.$r[2]);
353 $Offset = date('Z');
354 putenv('TZ='.$SaveZone);
355
356 // Get role
357 $roles = user_roles(1);
358 if ($r[8] &524288 || $r[8] &1048576 ) // 524288=is_mod, 1048576=is_admin
359 $rname = 'forum moderator';
360 else
361 $rname = 'forum user';
362 $rid = array_search($rname, $roles);
363
364 // Load user to see if it was previously registered
365 $user = user_load(array('name' => $login));
366
367 if (!$user->uid) { // Register new user
368 $user_default = array(
369 'name' => $login,
370 // 'pass' => '', !!!NEVER SET PASSWORD, NOT EVEN TO ''!!!
371 'mail' => $r[0],
372 'created' => $r[1],
373 'timezone' => $Offset,
374 'signature' => $r[3],
375 'init' => db_escape_string($login),
376 'status' => $status,
377 'authname_module' => 'fudforum',
378 'roles' => array($rid => $rname),
379 'profile_name' => $r[5],
380 'profile_location' => $r[6],
381 'profile_occupation' => $r[7]);
382
383 // Become user 1 to be able to save profile information
384 session_save_session(false);
385 $admin= array('uid' => 1);
386 $user = user_load($admin);
387
388 // now save the user and become the new user.
389 $user = user_save('', $user_default);
390 session_save_session(true);
391
392 watchdog('FUDforum', 'Regiser new user: '. $login, WATCHDOG_NOTICE, l('edit', 'user/'. $user->uid .'/edit'));
393 }
394 else {
395 // Update changed user settings
396 if ( $user->mail != $r[0] )
397 $user = user_save($user, array('mail' => 'REMOVE-'. $r[0]));
398 if ( $user->status != $status )
399 $user = user_save($user, array('status' => $status));
400 if ( $user->timezone != $Offset )
401 $user = user_save($user, array('timezone' => $Offset));
402 if ( $user->profile_name != $r[5] )
403 $user = user_save($user, array('profile_name' => $r[5]));
404 if ( $user->profile_location != $r[6] )
405 $user = user_save($user, array('profile_location' => $r[6]));
406 if ( $user->profile_occupation != $r[7] )
407 $user = user_save($user, array('profile_occupation' => $r[7]));
408 if ( ! isset($user->roles[$rid]) )
409 $user = user_save($user, array('roles' => array($rid=>$rname)));
410 }
411
412 drupal_set_message('Successfully authenticated from forum DB.');
413 return TRUE;
414 }
415
416 function fudforum_user($op, &$edit, &$account, $category = NULL) {
417 if ($op == 'logout') {
418 drupal_set_message('Logout and remove the forum cookie.');
419 _fudforum_settings();
420 setcookie($GLOBALS['COOKIE_NAME'], FALSE, time() - 86400, '/', $GLOBALS['COOKIE_DOMAIN']);
421 }
422
423 // New user added to Drupal - register user in forum DB
424 /* UNTESTED CODE - for future implementation
425 if ($op == 'insert' && $account->authname_module != 'fudforum') {
426 $users_opt = 4|16|128|256|512|2048|4096|8192|16384|131072|4194304;
427 $q = _fudforum_query('INSERT INTO {users}
428 (login,alias,passwd,name,email,join_date,users_opt) VALUES (
429 \''. $account->name .'\',
430 \''. $account->name .'\',
431 \''. md5($edit['pass']) .'\''
432 \''. $account->name .'\',.
433 \''. $account->mail .'\',
434 time(), $users_opt );
435 // SET 'authname_module' => 'fudforum',
436 // SET ROLES
437
438 if (!q)
439 drupal_set_error('Unable to add new Drupal user to forum DB');
440 else
441 drupal_set_message('User account created in forum DB');
442 }
443 */
444
445 if ($op == 'update' && $category == 'account') {
446 if ($account->authname_module == 'fudforum') {
447 // Sync e-mail and password changes back to FUDforum
448 if ($account->mail != $edit['mail'] || $edit['pass'] != '') {
449 $fuddb = _fudforum_connect();
450
451 // Update email address in forum DB
452 if ($account->mail != $edit['mail']) {
453 if (substr($edit['mail'], 0, 7) == 'REMOVE-') {
454 $edit['mail'] = substr($edit['mail'], 7);
455 drupal_set_message('Receive new E-mail address from forum DB');
456 }
457 else {
458 $q = _fudforum_query('UPDATE {users} SET email = \''. $edit['mail'] .'\' WHERE login=\''. $account->name .'\'');
459 if (!$q)
460 drupal_set_error('Unable to sync new email address to forum DB');
461 else
462 drupal_set_message('E-mail address synced to forum DB');
463 }
464 }
465
466 // Update password in forum DB
467 if ($edit['pass'] != '') {
468 $q = _fudforum_query('UPDATE {users} SET passwd = \''. md5($edit['pass']) .'\' WHERE login=\''. $account->name .'\'');
469 if (!q)
470 drupal_set_error('Unable to sync new password to forum DB');
471 else
472 drupal_set_message('Password synced to forum DB');
473 }
474
475 _fudforum_disconnect($fuddb);
476 watchdog('FUDforum', 'Sync password and email for '. $account->name .' to forum DB', WATCHDOG_NOTICE, l('edit', 'user/'. $user->uid .'/edit'));
477 }
478
479 // Unset Drupal password to prevent it from authenticating this user in future
480 $edit['pass'] = NULL;
481 }
482 }
483 }

  ViewVC Help
Powered by ViewVC 1.1.2