forked from igneramos/ign_password_protect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathign_password_protect.php
2165 lines (1773 loc) · 63.8 KB
/
ign_password_protect.php
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This is a PLUGIN TEMPLATE.
// Copy this file to a new name like abc_myplugin.php. Edit the code, then
// run this file at the command line to produce a plugin for distribution:
// $ php abc_myplugin.php > abc_myplugin-0.1.txt
// 0 = Plugin help is in Textile format, no raw HTML allowed (default).
// 1 = Plugin help is in raw HTML. Not recommended.
$plugin['allow_html_help'] = 1;
$plugin['name'] = 'ign_password_protect';
$plugin['version'] = '0.6.2';
$plugin['author'] = 'Jeremy Amos';
$plugin['author_uri'] = 'http://www.igneramos.com';
$plugin['description'] = 'Password protect articles or sections; authenticates against txp_users or alternate database (ign_users) ';
// Plugin types:
// 0 = regular plugin; loaded on the public web side only
// 1 = admin plugin; loaded on both the public and admin side
// 2 = library; loaded only when include_plugin() or require_plugin() is called
$plugin['type'] = '1';
if (!defined('txpinterface'))
@include_once('zem_tpl.php');
# --- BEGIN PLUGIN CODE ---
/*------------------------------------
Portions of this code Copyright 2004 by Dean Allen. All rights reserved.
Use of this software denotes acceptance of the Textpattern license agreement
Copyright 2005-2006 by Jeremy Amos. All rights reserved.
Use of this plugin denotes acceptance of the Textpattern license agreement
------------------------------------*/
//-----------------------------------------------
// user editable settings
//Define privilege levels
global $ign_levels, $ign_privs, $ign_err;
$ign_levels = array(
1 => 'Level 1',
2 => 'Level 2',
3 => 'Level 3',
4 => 'Level 4',
5 => 'Level 5',
6 => 'Level 6',
0 => gTxt('none')
);
// define privs for tab and tab-functions, privs tied to txp_user privs for current admin area user
$ign_privs = array(
'tab' => '1,2,3,4',
'new_user' => '1,2,3',
'reset_pass' => '1,2,3',
'change_pass' => '1,2,3,4',
'edit_users' => '1,2,3,4'
);
$ign_error_codes = array(
'success' => 0,
'logout' => 1,
'auth' => 2,
'cookie' => 3,
'privs' => 4
);
// Default message text
define('IGN_LOGIN_ERR','Sorry, the username and/or password entered is not valid, or you do not have privileges to access this resource.');
define('IGN_LOGOUT_LINK', 'Click here to logout.');
/* this is needed for installations where REQUEST_URI is not avaliable - thanks to Dave Harper www.hikebox.com*/
if (empty($_SERVER['REQUEST_URI'])) {
if (!empty($_SERVER['SCRIPT_NAME'])) {
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
} else if (!empty($_SERVER['PHP_SELF'])) {
$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'];
} else if (!empty($_ENV['PATH_INFO'])) {
$_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO'];
}
}
//-----------------------------------------------
/**
* Returns string, used for localization, much of this is deprecated, content moved to forms to allow easier localization
*
*
**/
function ign_gTxt($what)
{
$lang = array(
'manage_users' => 'Manage Users',
'user_db' => 'Use Alternate Database?',
'users' => 'Users',
'add_new_user' => 'Add New User',
'could_not_update_user' => 'Could not update user',
'reset_user_password' => 'Reset User Password',
'error_adding_new_user' => 'Could not add new user',
'new_pass' => 'Enter new password',
'confirm_pass' => 'Re-enter new password to confirm',
'a_message_will_be_sent_with_login' => 'A message will be sent with login information',
'email_pass' => 'Mail it to me',
'fallback' => 'Also authenticate against txp_users?',
//for email confirmations, values available are:
//1 - real name
//2 - user name
//3 - password
//4 - site name
//5 - site url
// see http://www.php.net/sprintf for more information on how to format the string
'new_user_email' => "Dear %1\$s,\r\n\r\nYou have been registered as a user of %4\$s.\r\nYour username is: %2\$s\r\nYour password is: %3\$s\r\n\r\nVisit the site at %5\$s",
'change_email' => "Dear %1\$s,\r\n\r\nYour password has been changed. Your new password is: %3\$s\r\n\r\nVisit the site at %5\$s"
);
return $lang[$what];
}
//--------------do not edit below this line------------------
//generate admin interface
if (txpinterface == 'admin')
{
if(!isset($prefs['ign_pp_version']) || $prefs['ign_pp_version'] != $plugins_ver['ign_password_protect'])
{
//TODO: Update Prefs, run forms check and install forms if necessary.
//TODO: add form pref for designating an alternate form
}
if (empty($prefs['ign_user_db']))
{
ign_pp_install();
}
//assign privs for interfaces
add_privs('ign_user_mgmt', '1,2,3,4');
//create tabs, register callback functions for those tabs
register_tab('admin', 'ign_user_mgmt', ign_gtxt('manage_users'));
register_callback('ign_manageUsers', 'ign_user_mgmt');
register_callback('ign_file_tab','file','file_edit');
if($prefs['ign_user_db'] == 'txp_users') {
register_callback('ign_admin_logout','admin_side','head_end');
}
}
if (txpinterface == 'public')
{
// disable caching for all pages
// FIXME: find more selective method for disabling caching
header("Cache-Control: must-revalidate");
$prefs['send_lastmod'] = false;
//register file_download callback to filter download requests
register_callback('ign_filter_downloads', 'file_download');
//fire off validation routine, since most functionality is dependent on it:
$ign_err = ign_doTxpValidate();
}
//---------------------public tags--------------------------
//-----------------------------------------------
/**
* Wrap content to protect, deprecated, use ign_login_form and ign_if_logged_in constructs instead if possible
*
*
**/
function ign_password_protect($atts, $thing='')
{
if(empty($thing)) $atts['login_type']='page';
$out = ign_doAuth($atts, $thing);
if($out) return $out;
}
//-----------------------------------------------
/**
* Displays currently logged-in user
*
*
**/
function ign_current_user($atts)
{
global $ign_user, $ign_err;
extract(lAtts(array(
'display' => 'name',
'verbose' => false,
'greeting' => gtxt('logged_in_as'),
'form' => 'current_user'
), $atts, 0));
if ( !$ign_err ) {
$use_form = @fetch_form($form);
if(empty($use_form))
{
$use_form = ign_default_form('current_user');
}
return parse($use_form);
} else {
return false;
}
}
//-----------------------------------------------
/**
* display login form
*
*
**/
function ign_show_login($atts)
{
// FIXME: Fix form presentation when calling current user
// currently takes the form passed in for login.
// options to solve this are:
// 1. use the show_logged param to pass in a new form
// 2. add a conditional to the forms to determine whether a user's logged in or not
global $ign_user, $ign_err;
$logout = gps('logout');
extract(lAtts(array(
'show_logged'=> 'true'
),$atts, 0)
);
if ($ign_user) {
$out = (strtolower($show_logged)=='true' || $show_logged==1) ? ign_current_user($atts) : '';
} else {
$out = ign_doLoginForm($atts);
}
return $out;
}
//-----------------------------------------------
/**
* Returns list of active users
*
*
**/
// FIXME: Move this to a form?
function ign_active_users($atts, $thing='')
{
global $ign_user_db;
extract(lAtts(
array(
'privs' => '',
'display' => 'name',
'wraptag' => 'p',
'break' => 'br',
'class' => '',
), $atts, 0));
$match = array('/[^0-9\,]/', '/\,\,/', '/\,$/');
$replacement = array('',',');
$privs = preg_replace($match, $replacement, $privs);
if(strtolower($display) != 'realname') {
$display = 'name';
}
$sql = '';
if(!empty($privs)) {
$sql .= "privs in ($privs) and ";
}
$sql .= "last_access > date_add(now(), interval -2 minute)";
$r = safe_rows($display, $ign_user_db, $sql);
if(count($r) < 1) {
return false;
} else {
foreach($r as $user) {
$users[] = $user[$display];
}
$out = !empty($thing) ? $thing : '';
return $out.n.doWrap($users, $wraptag, $break, $class).n;
}
}
//-----------------------------------------------
/**
* Tag for creating a public self-edit form to allow end users to change their password
*
*
**/
function ign_self_edit($atts)
{
global $ign_user_db, $ign_user, $ign_err, $ign_use_custom, $step;
extract(lAtts(array(
'form' => 'self_edit_form',
), $atts, 0)
);
//requires custom db (doesn't work on txp_users)
if (!$ign_use_custom) return ''; //exit if not ign_use_custom
$step = gps('step');
//check if user is logged in
if (!empty($ign_user))
{
if (!empty($step) && $step == 'ign_update_self')
{
//do update routine
$out = ign_update_self($atts);
return $out;
}
list($form_action) = explode('?', $_SERVER['REQUEST_URI']);
$use_form = @fetch_form($form);
if(empty($use_form) || $use_form == "<p>form <strong>$form</strong> does not exist</p>")
{
$use_form = ign_default_form('self_edit');
}
return
"<form action='{$form_action}' method='post'>".
eInput('ign_self_edit'). n .sInput('ign_update_self').
n.parse($use_form).n.
'</form>';
}
return '';
}
//-----------------------------------------------
/**
* Conditional tag, displays content if user is not logged in, can be deprecated?
*
*
**/
function ign_if_not_logged_in($atts,$thing)
{
global $ign_user, $ign_err;
if (!empty($ign_user))
{
return '';
}
return parse($thing);
}
//-----------------------------------------------
/**
* Conditional tag, shows or hides content depending on user's logged status
*
*
**/
function ign_if_logged_in($atts, $thing)
{
global $ign_user, $ign_page_privs;
extract(lAtts(array(
'privs' => ''
), $atts, 0));
if (empty($privs) && !empty($ign_page_privs))
{
$privs = $ign_page_privs;
}
//eval privs
$out = (!empty($ign_user)) ?
parse ( evalelse ( $thing, ( ign_checkPrivs($privs) ))) :
parse ( evalelse ( $thing, false ));
return $out;
}
//-----------------------------------------------
/**
* Tag to set page-wide privileges
* accepts comma delimited string of integers
*
*
**/
function ign_page_privs($atts)
{
global $ign_page_privs;
extract(lAtts(array(
'privs' => ''
), $atts, 0));
$ign_page_privs = $privs;
}
//---------------------internal functions--------------------------
//-----------------------------------------------
/**
* Fires off validation routine OR forces browser to request credentials
*
*
**/
function ign_doAuth($atts, $thing)
{
global $ign_user, $ign_err, $ign_page_privs, $ign_user_db;
extract(lAtts(array(
'hide_login' => 0,
'show_err' => 0,
'login_type' => '',
'login_msg' => '',
'err_msg' => '',
'privs' => ''
), $atts, 0));
if (!empty($ign_page_privs) && empty($privs))
{
$privs = $ign_page_privs;
}
if($ign_user && ign_checkPrivs($privs)) {
return parse($thing);
} else { //invalid user or privs
switch ($login_type) {
case 'page':
header('WWW-Authenticate: Basic realm="Private"');
header('HTTP/1.0 401 Unauthorized');
exit(gTxt('auth_required'));
default:
$out = (!$hide_login) ? ign_doLoginForm($atts) : '';
return $out;
break;
}
}
}
// -------------------------------------------------------------
/**
* ign_doTxpValidate strictly validates cookie or passed in credentials, does NOT check privilege levels,
* make certain to call ign_checkPrivs after validating the user for protected elements
* returns value depending type of failure or 0 on success
* 0 - successful validation
* 1 - logout process (display login?)
* 2 - invalid user / password
* 3 - bad cookie
*
**/
function ign_doTxpValidate()
{
global $logout, $txpcfg, $ign_user_db;
if(!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) //if credentials are being passed in from browser
{
$p_userid = serverSet('PHP_AUTH_USER');
$p_password = serverSet('PHP_AUTH_PW');
} else {
$p_userid = ps('p_userid');
$p_password = ps('p_password');
}
$p_reset = ps('p_reset');
$logout = gps('logout');
$stay = ps('stay');
$now = time()+3600*24*365;
// $d = explode('.', $_SERVER['HTTP_HOST']);
// $d = '.' . join('.', array_slice($d, 1-count($d), count($d)-1));
$domain = ign_getDomain();
if ($logout) {
//TODO: Should logout also clear txp_login_public?
$path = preg_replace('|//$|','/', rhu.'/');
setcookie('ign_login',' ',time()-3600,$path, $domain);
$GLOBALS['ign_user'] = '';
// logout from Vanilla
if(load_plugin("ddh_vanilla_integration"))
{
ddh_vanilla_logout();
}
//clear admin side cookies too, if using the txp database
if($ign_user_db == 'txp_users') {
$pub_path = preg_replace('|//$|','/', rhu.'/');
setcookie('txp_login', '', time()-3600, $pub_path.'textpattern/');
setcookie('txp_login_public', '', time()-3600, $pub_path);
}
return 1;
}
//test for public login if txp_user_db
if($ign_user_db == 'txp_users' && isset($_COOKIE['txp_login_public'])) {
$name = substr(cs('txp_login_public'), 10);
$u = is_logged_in($name);
// hackish - if this is a valid user, we need to populate the cookie
if($u) {
$acct = safe_row('name, privs, realname, nonce, last_access, email', $ign_user_db, "name='{$u['name']}'");
if(cs('ign_stay')) {
// don't override the txp_login
if(!ign_setCookie($acct, $now, true)) return 3;
} else {
if(!ign_setCookie($acct, NULL, true)) return 3;
}
$GLOBALS['ign_user'] = $u['name'];
ign_update_access($acct);
return 0;
}
}
if (isset($_COOKIE['ign_login']) and !$logout) // cookie exists
{
//parse cookie
list($c_userid,$c_privs,$c_realname, $cookie_hash) = ign_getCookie();
//get account info
$acct = safe_row('name, privs, realname, nonce, last_access, email', $ign_user_db, "name='" . doSlash($c_userid) . "'");
$nonce = $acct['nonce'];
if ($nonce === md5($c_userid.pack('H*', $cookie_hash))) {
$GLOBALS['ign_user'] = $c_userid; // cookie is good, create $txp_user
if($c_privs != $acct['privs']) //if privs have changed since cookie was created
{
if ($_COOKIE['ign_stay'])
{
if(!ign_setCookie($acct, $now)) return 3;
} else {
if(!ign_setCookie($acct)) return 3;
}
}
ign_update_access($acct);
return 0;
} else {
// something's gone wrong
$GLOBALS['ign_user'] = '';
setcookie('ign_login',' ',time()-3600,'/', $domain);
if($p_userid) {
//hackish - test userids in case we had a stale cookie
sleep(3); // should grind dictionary attacks to a halt
$valid_usr = ign_validate($p_userid,$p_password);
if ($valid_usr) {
if ($stay) { // persistent cookie required
if(!ign_setCookie($valid_usr, $now)) return 3;
setcookie('ign_stay', '1', $now, '/', $domain);
} else { // session-only cookie required`
if(!ign_setCookie($valid_usr)) return 3;
setcookie('ign_stay','0',-1, '/', $domain);
}
$GLOBALS['ign_user'] = $p_userid; // login is good, create $txp_user
return 0;
}
}
return 3;
}
} elseif ($p_userid) { // no cookie, but incoming login vars
sleep(3); // should grind dictionary attacks to a halt
$valid_usr = ign_validate($p_userid,$p_password);
if ($valid_usr) {
$nonce = $valid_usr['nonce']; //get nonce
if ($stay) { // persistent cookie required
//if(!ign_setCookie($valid_usr, $now, $stay)) return 3;
if(!ign_setCookie($valid_usr, $now)) return 3;
setcookie('ign_stay', '1', $now, '/', $domain);
} else { // session-only cookie required`
if(!ign_setCookie($valid_usr)) return 3;
setcookie('ign_stay','0',-1, '/', $domain);
}
$GLOBALS['ign_user'] = $p_userid; // login is good, create $txp_user
return 0;
} else {
$GLOBALS['ign_user'] = '';
return 2;
}
} elseif ($p_reset) {
// reset code?
sleep(3);
} elseif (gps('ign_reset')) {
// reset
} else {
$GLOBALS['ign_user'] = '';
return -1;
}
}
// -------------------------------------------------------------
function ign_validate($user,$password)
{
global $ign_user_db, $prefs;
$log = true;
include_once txpath.'/lib/PasswordHash.php';
$fallback = false;
$safe_user = doSlash($user);
$safe_pass = doSlash($password);
$hash = safe_field('pass', $ign_user_db, "name = '$safe_user'");
$phpass = new PasswordHash(PASSWORD_COMPLEXITY, PASSWORD_PORTABILITY);
// check post-4.3-style passwords
if ($phpass->CheckPassword($password, $hash)) {
if ($log) {
$name = safe_field("name", $ign_user_db, "name = '$safe_user' and privs > 0");
} else {
$name = $user;
}
} else {
// no good password: check 4.3-style passwords
$passwords = array();
$passwords[] = "password(lower('".doSlash($password)."'))";
$passwords[] = "password('".doSlash($password)."')";
if (version_compare(mysql_get_server_info(), '4.1.0', '>='))
{
$passwords[] = "old_password(lower('".doSlash($password)."'))";
$passwords[] = "old_password('".doSlash($password)."')";
}
$name = safe_field("name", $ign_user_db,
"name = '$safe_user' and (pass = ".join(' or pass = ', $passwords).") and privs > 0");
// old password is good: migrate password to phpass
if ($name !== FALSE) {
safe_update($ign_user_db, "pass = '".doSlash($phpass->HashPassword($password))."'", "name = '$safe_user'");
}
}
if ($name !== FALSE)
{
// Create session & cookies for Vanilla forum
if(load_plugin("ddh_vanilla_integration")) {
ddh_vanilla_login($safe_user, $password);
}
$r = safe_row('name, realname, privs, nonce, last_access, email', $ign_user_db, "`name` LIKE '{$safe_user}'");
if ($r)
{
ign_update_access($r);
return $r;
}
}
return false;
}
function ign_filter_downloads() //callback routine called by file_download
{
global $id, $file_error, $ign_user, $pretext, $s;
if(empty($id)) {
//no $id means we need to reparse the URL...
extract($pretext);
if($prefs['permlink_mode']=='messy') {
$id = gps('id'); //get $id from GET
} else { //we need to parse the uri
extract(chopurl($_SERVER['REQUEST_URI']));
$id = $u2; //should probably test for failure here...
}
}
//let's check to see if this file has permissions set and get the category
$file = safe_row('permissions, category', 'txp_file', "id='$id'");
$parent = (!empty($file['category'])) ? safe_field('parent','txp_category', "name='{$file['category']}'") : '';
if(!empty($file['permissions'])) // permissions set, carry on
{
if(empty($ign_user) || !ign_checkPrivs($file['permissions'])) //if any check fails, give 'em the boot
$file_error = '403';
} else if($parent == 'client'){ // let's fire off a quick category comparison for client-specific setups...
if(empty($ign_user) || $file['category'] != $ign_user)
$file_error = '403';
}
//return to let file_download do its thing...
return;
}
// -------------------------------------------------------------
function ign_update_access($acct, $nonce=null)
{
global $ign_pp_updated, $ign_user, $ign_user_db;
if (!$ign_pp_updated) { //update last access if necessary
if(!empty($_COOKIE['ign_login']))
{
list(,,,$hash,$cookie_time) = ign_getCookie();
if(strtotime($acct['last_access'])-strtotime($cookie_time) > 60) ign_setCookie($acct,null,false,$hash); // pass hash to preserve nonce
}
$safe_user = strtr(addslashes($ign_user),array('_' => '\_', '%' => '\%'));
safe_update($ign_user_db, "last_access = now()", "name = '$safe_user'");
$ign_pp_updated = true;
}
}
// -------------------------------------------------------------
function ign_checkPrivs($privs)
{
global $ign_err;
if(!empty($privs) && preg_match('/[0-9]+/', $privs)) //if privs attribute is set and contains numerical values
{
$match = array('/[^0-9\,]/', '/\,\,/', '/\,$/');
$replacement = array('',',');
$privs = preg_replace($match, $replacement, $privs);
$privs = explode(',', $privs);
}
ign_stopCache();
list($c_userid,$c_privs,$c_realname, $cookie_hash,) = ign_getCookie();
if (empty($privs) || in_array($c_privs, $privs))
{
return true;
}
$ign_err = 4;
return false;
}
// -------------------------------------------------------------
function ign_createDb()
{
global $txpcfg;
//function to create database
$version = mysql_get_server_info();
$dbcharset = $txpcfg['dbcharset'];
//Use "ENGINE" if version of MySQL > (4.0.18 or 4.1.2)
$tabletype = ( intval($version[0]) >= 5 || preg_match('#^4\.(0\.[2-9]|(1[89]))|(1\.[2-9])#',$version))
? " ENGINE=MyISAM "
: " TYPE=MyISAM ";
// On 4.1 or greater use utf8-tables
if ( isset($dbcharset) && (intval($version[0]) >= 5 || preg_match('#^4\.[1-9]#',$version)))
{
$tabletype .= " CHARACTER SET = $dbcharset ";
if (isset($dbcollate))
$tabletype .= " COLLATE $dbcollate ";
mysql_query("SET NAMES ".$dbcharset);
}
$create_sql = "CREATE TABLE IF NOT EXISTS `".PFX."ign_users` (
`user_id` int(4) NOT NULL auto_increment,
`name` varchar(64) NOT NULL default '',
`pass` varchar(128) NOT NULL default '',
`RealName` varchar(64) NOT NULL default '',
`email` varchar(100) NOT NULL default '',
`privs` tinyint(2) NOT NULL default '1',
`last_access` datetime NOT NULL default '0000-00-00 00:00:00',
`nonce` varchar(64) NOT NULL default '',
PRIMARY KEY (`user_id`),
UNIQUE KEY `name` (`name`)
) $tabletype PACK_KEYS=1 AUTO_INCREMENT=2 ";
$r = safe_query($create_sql);
$sql = "insert into ".PFX."ign_users (name, pass, RealName, email, privs, last_access, nonce)
select name, pass, RealName, email, privs, last_access, nonce from ".PFX."txp_users
where not exists (select name, pass, RealName, email, privs, last_access, nonce from ".PFX."ign_users where 1)";
$r = safe_query($sql);
}
//-----------------------------------------------
function ign_pp_install()
{
if(!isset($ign_user_db)) //if no db defined, default to txp_users
{
$ign_user_db = 'txp_users';
if(safe_insert('txp_prefs', "prefs_id=1, name='ign_user_db', val='$ign_user_db', html='text_input'"))
{
$log[] = "User database set to {$ign_user_db}";
}
}
if(!isset($ign_use_custom))
{
if(safe_insert('txp_prefs', "prefs_id=1, name='ign_use_custom', val='0', html='yesnoradio'"))
{
$log[] = "Use custom database set to 0";
}
}
}
//-----------------------------------------------
function ign_update_prefs()
{
global $ign_user_db;
$ign_use_custom = ps('ign_use_custom');
$ign_fallback = ps('fallback');
if($ign_use_custom == 1)
{
safe_update('txp_prefs', "val = 'ign_users'","name = 'ign_user_db'");
safe_update('txp_prefs', "val = 1", "name = 'ign_use_custom'");
safe_update('txp_prefs', 'val = 1', "name = 'ign_fallback'");
ign_createDb();
$ign_user_db = 'ign_users';
} elseif ($ign_use_custom == 0) {
safe_update('txp_prefs', "val = 'txp_users'", "name = 'ign_user_db'");
safe_update('txp_prefs', "val = 0", "name = 'ign_use_custom'");
safe_update('txp_prefs', 'val = 0', "name = 'ign_fallback'");
$ign_user_db = 'txp_users';
}
ign_admin('Database preference updated');
}
//-----------------------------------------------
function ign_useCustomDbForm()
{
global $ign_user_db, $prefs;
extract(lAtts(array(
'ign_use_custom' => '',
'ign_fallback' => ''
), $prefs, 0)
);
if(isset($_POST['ign_use_custom']))
{
$ign_use_custom = $_POST['ign_use_custom'];
} else {
$ign_use_custom = (empty($ign_use_custom)) ? '0' : $ign_use_custom;
}
return n.'<div style="margin: 3em auto auto auto; width: 40em; text-align: center;">'.
n.n.form(
n.eInput('ign_user_mgmt').
n.sInput('ign_update_prefs').
ign_gTxt('user_db').br.yesnoRadio('ign_use_custom',$ign_use_custom).
br.ign_gTxt('fallback').ign_checkbox(array('name'=>'fallback','checked'=>'true')).
br.
n.fInput('submit', 'ign_update_prefs', 'Update', 'smallerbox')
).n.'</div>';
}
//-----------------------------------------------
function ign_manageUsers($event, $step) //
{
global $ign_user_db, $ign_user, $txp_user, $myprivs, $ign_levels;
if ($event == 'ign_user_mgmt') {
require_privs('article.publish');
$myprivs = fetch('privs','txp_users','name',$txp_user);
if(!$step or !in_array($step,
array('ign_admin','ign_user_delete','ign_userList','ign_userSave','ign_userSaveNew','ign_changeEmail','ign_changePass', 'ign_update_prefs', 'ign_userChangePass')))
{
ign_admin();
} else $step();
}
}
//-----------------------------------------------
function ign_get_pref($pref) //selective preference retrieval
{
global $ign_user_db;
$r = safe_field('val', $ign_user_db, 'prefs_id=1 and name=\'$pref\'');
if ($r) {
return $r;
}
return false;
}
//-----------------------------------------------
// the following code is essentially lifted from txp_admin.php.
function ign_admin($message='')
{
global $myprivs,$ign_user, $ign_user_db, $ign_privs;
pagetop(ign_gTxt('manage_users'),$message);
$themail = fetch('email',$ign_user_db,'name',$ign_user);
$table_exists = safe_query("show table status like 'ign_users'");
echo ign_useCustomDbForm();
if ( $ign_user_db == 'ign_users' && $table_exists )
{
echo ign_userList();
echo (in_array($myprivs, explode(',', $ign_privs['new_user']))) ? ign_new_user_form(): '';
echo (in_array($myprivs, explode(',', $ign_privs['reset_pass']))) ? ign_resetUserPassForm() : '';
} else {
echo '<div align="center" style="margin-top:3em">User management functions only available here when using custom database.<br />Use <a href="?event=admin">site admin</a> tab instead.</div>';
}
}
// -------------------------------------------------------------
function ign_changeEmail()
{
global $ign_user, $ign_user_db;
$new_email = gps('new_email');
if (safe_update($ign_user_db, "email = '$new_email'", "name = '$ign_user'")) {
ign_admin('email address changed to '.$new_email);
} else {
ign_admin('Failed to change email address.');
}
}
// -------------------------------------------------------------
function ign_userSave()
{
global $ign_user_db;
extract(doSlash(psa(array('privs','user_id','RealName','email'))));
$rs = safe_update($ign_user_db,
"privs = $privs,
RealName = '$RealName',
email = '$email'",
"user_id='$user_id'");
if ($rs) ign_admin(messenger('user',$RealName,'updated'));
}
// -------------------------------------------------------------
function ign_changePass()
{
global $ign_user, $ign_user_db;
$message = '';
$themail = fetch('email',$ign_user_db,'name',$ign_user);
if (!empty($_POST["new_pass"])) {
$NewPass = $_POST["new_pass"];
if (safe_update($ign_user_db, "pass = password(lower('$NewPass'))", "name='$ign_user'"))
{
$message .= gTxt('password_changed');
if ($_POST['mailpassword']==1) {
ign_sendNewPassword($NewPass,$themail,$ign_user);
$message .= sp.gTxt('and_mailed_to').sp.$themail;
}
$message .= ".";
} else echo comment(mysql_error());
ign_admin($message);
}
}
// -------------------------------------------------------------
function ign_userSaveNew()
{
global $ign_user_db;
extract(doSlash(psa(array('privs','name','email','RealName'))));
$pw = ign_generatePassword(8);
$nonce = md5( uniqid( rand(), true ) );
if ($name) {
$rs = safe_insert(
$ign_user_db,
"privs = '$privs',
name = '$name',
email = '$email',
RealName = '$RealName',
pass = password(lower('$pw')),
nonce = '$nonce'"
);
}
if ($name && $rs) {
ign_send_password($pw,$email);
ign_admin(gTxt('password_sent_to').sp.$email);
} else {
ign_admin(ign_gTxt('error_adding_new_user'));
}
}
// -------------------------------------------------------------
function ign_privList($priv='')
{
global $ign_levels;
return selectInput("privs", $ign_levels, $priv);
}
// -------------------------------------------------------------
function ign_getPrivLevel($priv)
{
global $ign_levels;
return $ign_levels[$priv];
}
// -------------------------------------------------------------
function ign_send_password($pw,$email)
{
global $sitename,$ign_user, $ign_user_db;