-
Notifications
You must be signed in to change notification settings - Fork 4
/
smd_user_manager.php
executable file
·1696 lines (1420 loc) · 69.2 KB
/
smd_user_manager.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 for Textpattern CMS.
// 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
// Plugin name is optional. If unset, it will be extracted from the current
// file name. Plugin names should start with a three letter prefix which is
// unique and reserved for each plugin author ("abc" is just an example).
// Uncomment and edit this line to override:
$plugin['name'] = 'smd_user_manager';
// Allow raw HTML help, as opposed to Textile.
// 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['version'] = '0.4.0';
$plugin['author'] = 'Stef Dawson';
$plugin['author_uri'] = 'https://stefdawson.com/';
$plugin['description'] = 'Manage user accounts, groups and privileges';
// Plugin load order:
// The default value of 5 would fit most plugins, while for instance comment
// spam evaluators or URL redirectors would probably want to run earlier
// (1...4) to prepare the environment for everything else that follows.
// Values 6...9 should be considered for plugins which would work late.
// This order is user-overrideable.
$plugin['order'] = '8';
// Plugin 'type' defines where the plugin is loaded
// 0 = public : only on the public side of the website (default)
// 1 = public+admin : on both the public and admin side
// 2 = library : only when include_plugin() or require_plugin() is called
// 3 = admin : only on the admin side (no AJAX)
// 4 = admin+ajax : only on the admin side (AJAX supported)
// 5 = public+admin+ajax : on both the public and admin side (AJAX supported)
$plugin['type'] = '5';
// Plugin "flags" signal the presence of optional capabilities to the core plugin loader.
// Use an appropriately OR-ed combination of these flags.
// The four high-order bits 0xf000 are available for this plugin's private use
if (!defined('PLUGIN_HAS_PREFS')) define('PLUGIN_HAS_PREFS', 0x0001); // This plugin wants to receive "plugin_prefs.{$plugin['name']}" events
if (!defined('PLUGIN_LIFECYCLE_NOTIFY')) define('PLUGIN_LIFECYCLE_NOTIFY', 0x0002); // This plugin wants to receive "plugin_lifecycle.{$plugin['name']}" events
$plugin['flags'] = '3';
// Plugin 'textpack' is optional. It provides i18n strings to be used in conjunction with gTxt().
// Syntax:
// ## arbitrary comment
// #@event
// #@language ISO-LANGUAGE-CODE
// abc_string_name => Localized String
$plugin['textpack'] = <<<EOT
#@owner smd_user_manager
#@language en, en-gb, en-us
#@admin-side
smd_um_active => Currently active: {users}
#@admin
smd_um_article_count => Articles
smd_um_based_on => based on
smd_um_file_count => Files
smd_um_grp_affected => . Users affected: {num}
smd_um_grp_created => Group "{name}" created
smd_um_grp_deleted => Group deleted
smd_um_grp_exists => Group already exists as priv ID {id}
smd_um_grp_lbl => Groups
smd_um_grp_new => New group title
smd_um_grp_new_name => name
smd_um_grp_not_deleted => Core groups cannot be deleted
smd_um_grp_saved => Group info updated
smd_um_heading_grp => User groups
smd_um_heading_prf => User manager settings
smd_um_heading_prv => User privileges
smd_um_image_count => Images
smd_um_link_count => Links
smd_um_name_required => A name is required
smd_um_prf_lbl => Prefs
smd_um_prv_created => Priv area "{area}" created
smd_um_prv_exists => Priv area already exist
smd_um_prv_lbl => Privs
smd_um_prv_new => New priv area
smd_um_prv_saved => Privs updated
smd_um_prv_smd_um => Cannot create privs for smd_user_manager
smd_um_reset => [R]
smd_um_sel_all => Select the entire area then (c)heck, (u)ncheck or (t)oggle highlighted checkboxes
smd_um_sel_grp => Select this group then (c)heck, (u)ncheck or (t)oggle highlighted checkboxes
smd_um_sel_prv => Select this area set then (c)heck, (u)ncheck or (t)oggle highlighted checkboxes
smd_um_sel_reset => Reset: any checked area sets will revert to their defaults after Save
smd_um_settings => Settings
smd_um_tbl_installed => Tables installed
smd_um_tbl_not_installed => Tables not installed
smd_um_tbl_not_removed => Tables not removed
smd_um_tbl_removed => Tables removed
smd_um_user_count => Users in this group:
smd_um_usr_lbl => Users
#@prefs
smd_user_manager => User manager
smd_um_active_timeout => Activity timeout (seconds)
smd_um_admin_group => Protected administrator group
smd_um_hierarchical_groups => Assume hierarchical groups (levels)
smd_um_self_alter => Allow smd_um privs to be altered
#@language fr
#@admin-side
smd_um_active => Utilisateurs actuellement actifs {users}
#@admin
smd_um_article_count => Articles
smd_um_based_on => basé sur
smd_um_file_count => Fichiers
smd_um_grp_affected => . Utilisateurs affectés : {num}
smd_um_grp_created => Groupe "{name}" créé
smd_um_grp_deleted => Groupe supprimé
smd_um_grp_exists => Ce groupe existe déjà sous l'ID {id}
smd_um_grp_lbl => Groupes
smd_um_grp_new => Titre du nouveau groupe
smd_um_grp_new_name => nom
smd_um_grp_saved => Infos du groupe mises à jour
smd_um_heading_grp => Groupe d'utilisateurs
smd_um_heading_prf => Paramètres utilisateurs
smd_um_heading_prv => Privilèges utilisateurs
smd_um_image_count => Images
smd_um_link_count => Liens
smd_um_name_required => Un nom est requis
smd_um_prf_lbl => Préférences
smd_um_prv_created => Définition de privilèges "{area}" créée
smd_um_prv_exists => Cette définition de privilèges existe déjà
smd_um_prv_lbl => Privilèges
smd_um_prv_new => Nouvelle définition de privilège
smd_um_prv_saved => Privilèges mis à jour
smd_um_prv_smd_um => Impossible de créer les privilèges pour smd_user_manager
smd_um_reset => [R]
smd_um_sel_all => Sélectionnez la zone entière puis cocher (c), décocher (u) ou basculer les cases en surbrillance (t)
smd_um_sel_grp => Sélectionnez le groupe puis cocher (c), décocher (u) ou basculer les cases en surbrillance (t)
smd_um_sel_prv => Sélectionnez la zone puis cocher (c), décocher (u) ou basculer les cases en surbrillance (t)
smd_um_sel_reset => Réinitialiser : toutes les sélections verront leurs réglages rétablis par défaut après enregistrement
smd_um_settings => Paramètres
smd_um_tbl_installed => Tables installées
smd_um_tbl_not_installed => Tables non installées
smd_um_tbl_not_removed => Tables non supprimées
smd_um_tbl_removed => Tables supprimées
smd_um_user_count => Utilisateurs de ce groupe :
smd_um_usr_lbl => Utilisateurs
#@prefs
smd_um_active_timeout => Durée d'activité (secondes)
smd_um_admin_group => Groupe protégé d'administrateurs
smd_um_hierarchical_groups => Chargé de la hiérarchie des groupes (levels)
smd_um_self_alter => Accès aux privilèges de smd_um
#@language es
#@admin-side
smd_um_active => Usuarios actualmente conectados: {users}
#@admin
smd_um_article_count => Artículos
smd_um_based_on => basado en
smd_um_file_count => Ficheros
smd_um_grp_affected => . Usuarios afectados: {num}
smd_um_grp_created => Grupo "{name}" creado
smd_um_grp_deleted => Grupo eliminado
smd_um_grp_exists => El grupo ya existe, su ID de privilegios es {id}
smd_um_grp_lbl => Grupos
smd_um_grp_new => Nuevo nombre de grupo
smd_um_grp_new_name => nombre
smd_um_grp_saved => Información de grupo actualizada
smd_um_heading_grp => Grupos de usuarios
smd_um_heading_prf => Preferencias del gestor de usuarios
smd_um_heading_prv => Privilegios de usuarios
smd_um_image_count => Imágenes
smd_um_link_count => Enlaces
smd_um_name_required => Se requiere un nombre
smd_um_prf_lbl => Preferencias
smd_um_prv_created => Área de privilegios "{area}" creada
smd_um_prv_exists => Área de privilegios ya existe
smd_um_prv_lbl => Privilegios
smd_um_prv_new => Nuevo área de privilegios
smd_um_prv_saved => Privilegios actualizados
smd_um_prv_smd_um => Imposible crear privilegios para smd_user_manager
smd_um_reset => [R]
smd_um_sel_all => Selecciona esta área completa, luego marca (c), desmarca (u) o invierte (t) la selección
smd_um_sel_grp => Selecciona este grupo, luego marca (c), desmarca (u) o invierte (t) la selección
smd_um_sel_prv => Selecciona este área, luego marca (c), desmarca (u) o invierte (t) la selección
smd_um_sel_reset => Reajustar: todas las áreas marcadas volverán a sus valores por defecto después de guardar
smd_um_settings => Preferencias
smd_um_tbl_installed => Tablas instaladas
smd_um_tbl_not_installed => Tablas no instaladas
smd_um_tbl_not_removed => Tablas no eliminadas
smd_um_tbl_removed => Tablas eliminadas
smd_um_user_count => Usuarios en este grupo:
smd_um_usr_lbl => Usuarios
#@prefs
smd_um_active_timeout => Desconectar a los usuarios después de (segundos)
smd_um_admin_group => Grupo protegido de administradores
smd_um_hierarchical_groups => Asumir grupos jerárquicos (niveles)
smd_um_self_alter => Permitir cambiar privilegios a smd_um
EOT;
if (!defined('txpinterface'))
@include_once('zem_tpl.php');
# --- BEGIN PLUGIN CODE ---
//<?php
/**
* smd_user_manager
*
* A Textpattern CMS plugin for complete user administration:
* -> Search / filter / alter info on users (with asset counts)
* -> Create / alter groups (roles)
* -> Create / customise privs (areas)
* -> Online user list
*
* @author Stef Dawson
* @link https://stefdawson.com/
*/
// TODO:
// -> Why does multi-edit fire twice? Is it still attached to the Admin->Users table?
use \Textpattern\Search\Filter;
if (!defined('SMD_UM_PRIVS')) {
define("SMD_UM_PRIVS", 'smd_um_privs');
}
if (!defined('SMD_UM_GROUPS')) {
define("SMD_UM_GROUPS", 'smd_um_groups');
}
if (txpinterface === 'admin') {
new smd_um();
}
if (class_exists('\Textpattern\Tag\Registry')) {
Txp::get('\Textpattern\Tag\Registry')
->register('smd_um_has_privs');
}
/**
* Public tag: Conditionally check privs and take action.
*
* Though we could load all $txp_permissions / $txp_groups to the public side for speed,
* exposing permissions to the world is not such a hot idea. Therefore the privs are
* fetched ad-hoc and cached.
*
* @param array $atts Tag attributes
* @param string $thing Tag container content
*/
function smd_um_has_privs($atts, $thing = null)
{
global $txp_user;
static $smd_um_permissions;
static $smd_um_groups;
static $smd_ili = 0;
extract(lAtts(array(
'name' => '',
'group' => '',
'area' => '',
'debug' => 0,
),$atts));
$ret = false;
$smd_ili = ($smd_ili === 0) ? is_logged_in() : $smd_ili;
if ($smd_ili) {
$names = do_list($name);
$groups = do_list($group);
$areas = do_list($area);
// Handle > and < groups.
$grplist = array();
foreach ($groups as $grp) {
if ((strpos($grp, '>') === 0) || (strpos($grp, '<') === 0)) {
if (!isset($smd_um_groups)) {
$smd_um_groups = safe_column('id', SMD_UM_GROUPS, '1=1 ORDER BY id');
}
$val = substr($grp, 1);
// Pull out all groups higher than this one.
if (substr($grp, 0, 1) === '>') {
foreach ($smd_um_groups as $ug) {
if ($ug > $val) $grplist[] = $ug;
}
}
// Pull out all groups lower than this one.
if (substr($grp, 0, 1) === '<') {
foreach ($smd_um_groups as $ug) {
if (($ug < $val) && ($ug != '0')) $grplist[] = $ug;
}
}
} else {
$grplist[] = $grp;
}
}
$groups = array_unique($grplist);
if ($debug) {
echo '++ LOGGED IN CREDENTIALS / PERMISSION AREAS / ALL GROUP IDs / NAME ATTR / GROUP ATTR / AREA ATTR ++';
dmp($smd_ili, $smd_um_permissions, $smd_um_groups, $names, $groups, $areas);
}
$isname = ($name && in_array($smd_ili['name'], $names));
$isgroup = (($group != '') && in_array($smd_ili['privs'], $groups));
$isarea = false;
// Build up a cached array of privs by area.
if ($areas) {
// TODO: would be nice to do this in one query somehow
foreach ($areas as $place) {
if (!isset($smd_um_permissions[$place])) {
$prv = safe_field('GROUP_CONCAT(priv) AS privs', SMD_UM_PRIVS, "area = '" . doSlash($place) . "'");
$smd_um_permissions[$place] = $prv;
}
$isarea = ($isarea || (in_array($smd_ili['privs'], do_list($smd_um_permissions[$place]))));
}
}
if ($debug) {
echo '++ TEST AGAINST NAME / GROUP / AREA ++';
dmp($isname, $isgroup, $isarea);
}
// Compare the current logged in credentials against the relevant passed-in attribute combinations.
if ($name) {
if ($group) {
if ($area) {
$debug && dmp('CHECK NAME AND GROUP AND AREA');
$ret = ($isname && $isgroup && $isarea);
} else {
$debug && dmp('CHECK NAME AND GROUP');
$ret = ($isname && $isgroup);
}
} elseif ($area) {
$debug && dmp('CHECK NAME AND AREA');
$ret = ($isname && $isarea);
} else {
$debug && dmp('CHECK NAME');
$ret = $isname;
}
} elseif ($group) {
if ($area) {
$debug && dmp('CHECK GROUP AND AREA');
$ret = ($isgroup && $isarea);
} else {
$debug && dmp('CHECK GROUP');
$ret = $isgroup;
}
} elseif ($area) {
$debug && dmp('CHECK AREA');
$ret = $isarea;
} else {
$debug && dmp('NO CHECKS (ANY USER)');
$ret = true;
}
}
return parse($thing, $ret);
}
/**
* User manager admin interface.
*/
class smd_um
{
/**
* The plugin's event as registered in Txp.
*
* @var string
*/
protected $event = 'admin';
/**
* The plugin's version.
*
* @var string
*/
protected $version = '0.4.0';
/**
* The plugin's privileges.
*
* @var string
*/
protected $privs = '1';
/**
* Any UI message to announce.
*
* @var string
*/
protected $message = '';
/**
* Constructor to set up callbacks and environment.
*
* Access is also logged so we know who's logged in and active.
*/
public function __construct()
{
global $event, $txp_user, $step;
if ($event === 'prefs') {
add_privs('prefs.smd_user_manager', $this->privs);
} elseif ($event === 'plugin_prefs.smd_user_manager') {
add_privs('plugin_prefs.smd_user_manager', $this->privs);
} elseif ($event === $this->event) {
add_privs($this->event.'.smd_um_grp', $this->privs);
add_privs($this->event.'.smd_um_prv', $this->privs);
register_callback(array($this, 'steps'), 'user', 'steps');
register_callback(array($this, 'buttons'), 'user', 'controls', 'panel');
register_callback(array($this, 'groups'), 'admin', 'smd_um_groups', 1);
register_callback(array($this, 'group_add'), 'admin', 'smd_um_group_add', 1);
register_callback(array($this, 'group_del'), 'admin', 'smd_um_group_del', 1);
register_callback(array($this, 'group_save'), 'admin', 'smd_um_group_save', 1);
register_callback(array($this, 'privs'), 'admin', 'smd_um_privs', 1);
register_callback(array($this, 'priv_add'), 'admin', 'smd_um_priv_add', 1);
register_callback(array($this, 'priv_save'), 'admin', 'smd_um_priv_save', 1);
}
add_privs($this->event.'.smd_um_active', $this->privs);
register_callback(array($this, 'welcome'), 'plugin_lifecycle.smd_user_manager');
register_callback(array($this, 'options'), 'plugin_prefs.smd_user_manager', null, 1);
register_callback(array($this, 'inject_css'), 'admin_side', 'head_end');
$has_footer = callback_handlers('admin_side', 'footer');
if (has_privs($this->event.'.smd_um_active') && !in_array(__CLASS__.'->active_users', $has_footer)) {
register_callback(array($this, 'active_users'), 'admin_side', 'footer');
}
// Call the installer in case the lifecycle event didn't fire.
$this->install();
// Log the time of this access attempt.
$curr_users = json_decode(get_pref('smd_um_current_users', ''), true);
if (!$curr_users) {
$curr_users = array();
}
$curr_users[$txp_user] = time();
set_pref('smd_um_current_users', json_encode($curr_users), 'smd_um', PREF_HIDDEN, '', 0);
// Merge in the groups only for now.
$this->priv_merge(true, false);
// Permit user self-editing.
$smd_um_grps = array_keys($this->get_groups(0));
// Remove None user.
unset($smd_um_grps[0]);
// Now the privs are established for all admin steps so we can go ahead
// and merge in the changes. One caveat: if we're saving the privs we
// need to delay the database merge until after the resets have been applied,
// otherwise we won't know what the defaults (in admin_config.php) are.
$do_privs = ($step === 'smd_um_priv_save') ? false : true;
$this->priv_merge(false, $do_privs);
}
/**
* CSS definitions: hopefully kind to themers.
*
* @return string Style rules
*/
protected function get_style_rules()
{
$smd_um_styles = array(
'control-panel' => '
.smd_um_privgroup { position:relative; }
.smd_um_privgroup h3 { text-align:left; font-weight:bold; }
.smd_um_privsave { position:absolute; left:25px; top:2rem; }
.smd_um_selected { background-color:#e2dfce; }
.smd_um_grp_name, .smd_um_prv_name, .smd_um_reset_col { cursor:pointer; }
.smd_um_checkbox, .smd_um_prv_hdr { text-align:center!important; }
',
);
return $smd_um_styles;
}
/**
* Inject style rules into the <head> of the page.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
* @return string Style rules, or nothing if not the correct $event
*/
public function inject_css($evt, $stp)
{
global $event;
if ($event === $this->event || $event === 'admin') {
$smd_um_styles = $this->get_style_rules();
if (class_exists('\Textpattern\UI\Style')) {
echo Txp::get('\Textpattern\UI\Style')->setContent($smd_um_styles['control-panel']);
} else {
echo '<style>' . $smd_um_styles['control-panel'] . '</style>';
}
}
return;
}
/**
* Register the plugin's steps with the core panel.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
* @param array &$plugin_steps Current set of steps to be modified
*/
public function steps($evt, $stp, &$plugin_steps)
{
if (has_privs('admin.edit')) {
$plugin_steps += array(
'smd_um_groups' => false,
'smd_um_group_add' => true,
'smd_um_group_del' => true,
'smd_um_group_save' => true,
'smd_um_privs' => false,
'smd_um_priv_add' => true,
'smd_um_priv_save' => true,
);
}
}
/**
* Lifecycle handling, post-install / delete.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
* @return string Success/failure message
*/
public function welcome($evt, $stp)
{
$msg = '';
switch ($stp) {
case 'installed':
$this->install();
$msg = 'Super duper users!';
break;
case 'deleted':
$this->remove();
break;
}
return $msg;
}
/**
* Add a new user group.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
public function group_add($evt, $stp)
{
global $txp_permissions;
require_privs($this->event.'.smd_um_grp');
$title = ps('smd_um_new_grp');
$name = ps('smd_um_new_grp_name');
$name = ($name == '') ? strtolower(sanitizeForUrl($title)) : $name;
if ($name) {
$exists = safe_field('id', SMD_UM_GROUPS, "name='".doSlash($name)."'");
if ($exists) {
$this->message = array(gTxt('smd_um_grp_exists', array('{id}' => $exists)), E_USER_WARNING);
} else {
// It's not atomic but it'll do, given that:
// a) normally only one person administers this plugin.
// b) groups are added one at a time.
$curr_max = safe_field("MAX(id)", SMD_UM_GROUPS, '1=1');
$new_priv = ($curr_max + 1);
safe_insert(SMD_UM_GROUPS, "id='" . $new_priv . "', name='" . doSlash($name) . "'");
$this->upsert_lang($title, $name);
$based_on = ps('smd_um_new_grp_based_on');
if ($based_on != '') {
assert_int($based_on);
// Can't rely on the privs being in the database so resort to the (merged) array.
foreach ($txp_permissions as $area => $privs) {
$privs = do_list($privs);
$safe_area = doSlash($area);
if (in_array($based_on, $privs, true)) {
$current_privs = safe_column('priv', SMD_UM_PRIVS, "area='{$safe_area}'");
if (empty($current_privs)) {
$priv_set = array_unique(array_merge($privs, array($new_priv)));
} else {
$priv_set = array($new_priv);
}
foreach ($priv_set as $np) {
safe_insert(SMD_UM_PRIVS, "area='{$safe_area}', priv='" . doSlash($np) . "'");
}
}
}
}
$this->message = gTxt('smd_um_grp_created', array('{name}' => $name));
}
} else {
$this->message = array(gTxt('smd_um_name_required'), E_ERROR);
}
$this->groups($evt);
}
/**
* Delete a group if it's not in the core set.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
public function group_del($evt, $stp)
{
require_privs($this->event.'.smd_um_grp');
$id = assert_int(gps('id'));
$name = safe_field('name', SMD_UM_GROUPS, "id='".$id."' AND core!=1");
if ($name) {
// @todo Make atomic.
$red = safe_delete(SMD_UM_GROUPS, "id=$id AND core!=1");
safe_delete('txp_lang', "name='".doSlash($name)."'");
$affected_users = safe_column('user_id', 'txp_users', "privs = $id");
if ($affected_users) {
// Set all orphaned users to no privs -- can always assign them a new group from the main screen later
$ret = safe_update('txp_users', "privs=0", "user_id IN ('". implode("','", doSlash($affected_users)) ."')");
}
if ($red) {
$ret = safe_delete(SMD_UM_PRIVS, "priv=$id");
$this->message = gTxt('smd_um_grp_deleted') . ($affected_users ? gTxt('smd_um_grp_affected', array('{num}' => count($affected_users))) : '');
}
} else {
$this->message = array(gTxt('smd_um_grp_not_deleted'), E_ERROR);
}
$this->groups($evt);
}
/**
* Save the group set.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
public function group_save($evt, $stp)
{
require_privs($this->event.'.smd_um_grp');
$excluded = $this->get_groups(0);
$ids = ps('smd_um_group_id');
$names = ps('smd_um_group_name');
$titles = ps('smd_um_group_title');
foreach ($ids as $idx => $id) {
$title = $titles[$idx];
$name = strtolower(sanitizeForUrl($names[$idx]));
// Can't create duplicate types
if (!in_array($name, $excluded)) {
safe_update(SMD_UM_GROUPS, "name='" . doSlash($name) . "'", "id='" . doSlash($id) . "'");
}
$this->upsert_lang($title, $name);
}
$this->message = gTxt('smd_um_grp_saved');
$this->groups($evt);
}
/**
* Group management panel.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
public function groups($evt, $stp = '')
{
require_privs($this->event.'.smd_um_grp');
$msg = $this->message;
// Render the page.
pagetop(gTxt('smd_um_tab_name').' » '.gTxt('smd_um_grp_lbl'), $msg);
$btnbar = array();
$this->buttons($this->event, '', $btnbar);
$allgroups = $this->get_groups(1, true);
$grouplist = selectInput('smd_um_new_grp_based_on', $allgroups, '', true, '', 'smd_um_new_grp_based_on');
// New group.
echo '<h1 class="txp-heading">', gTxt('smd_um_heading_grp'), '</h1>',
n. '<div id="'.$this->event.'_control" class="txp-control-panel">',
n. implode(n, $btnbar),
n. form(
graf(
'<label for="smd_um_new_grp">' . gTxt('smd_um_grp_new') . '</label>'
.n.fInput('text', 'smd_um_new_grp', '', '', '', '', '', '', 'smd_um_new_grp')
.n.'<label for="smd_um_new_grp_name">' . gTxt('smd_um_grp_new_name') . '</label>'
.n.fInput('text', 'smd_um_new_grp_name', '', '', '', '', '', '', 'smd_um_new_grp_name')
.n.'<label for="smd_um_new_grp_based_on">' . gTxt('smd_um_based_on') . '</label>'
.n.$grouplist
.n.fInput('submit', 'smd_um_group_add', gTxt('create'))
.n.eInput($this->event)
.n.sInput('smd_um_group_add')
)
, '','','post','search-form'
),
n, '</div>';
// Retrieve the group info and user counts per privilege level.
$fields = 'smdg.id, smdg.name, smdg.core, txu.total AS user_count';
$clause = ' FROM '.PFX.'smd_um_groups AS smdg
LEFT JOIN (SELECT privs, count(privs) AS total FROM '.PFX.'txp_users GROUP BY privs) AS txu ON smdg.id = txu.privs';
$rs = getRows('SELECT ' . $fields.$clause . ' ORDER BY id');
if ($rs) {
echo n. '<div class="plugin-column">'
.n. '<form action="index.php" id="smd_um_grp_form" method="post" name="longform" onsubmit="return verify(\''.gTxt('are_you_sure').'\')">'
.n.'<div class="txp-listtables">'
.n. startTable('', '', 'txp-list')
.n. '<thead>'
.n. tr(
hCell('ID', '', ' class="id"').
hCell(gTxt('title'), '', ' class="name"').
hCell(gTxt('name'), '', ' class="name"').
hCell('', '', '')
)
.n. '</thead>'
.n. '<tbody>';
foreach ($rs as $row) {
extract(doSpecial($row));
$user_count = empty($user_count) ? 0 : $user_count;
$dLink = ($core) ? ' ' : dLink($this->event, 'smd_um_group_del', 'id', $id, false, null, null, true);
echo tr(
tda(
hInput('smd_um_group_id[]', $id)
.(($user_count) ? eLink($this->event, '', 'search_method', 'privs', $id, 'crit', $id) : $id)
, ' class="id"'
.(($user_count) ? ' title="' . gTxt('smd_um_user_count') . $user_count . '"': '')
)
.td(fInput('text', 'smd_um_group_title[]', gTxt($name)), '', 'name')
.td(fInput('text', 'smd_um_group_name[]', $name), '', 'name')
.td($dLink)
);
}
echo n. '</tbody>'
.n. endTable()
.n. '</div>'
.n. graf(fInput('submit', 'smd_um_group_save', gTxt('save'), 'publish'))
.n. fInput('hidden', 'smd_um_grp_del', '', '', '', '', '', '', 'smd_um_grp_del')
.n. eInput($this->event)
.n. sInput('smd_um_group_save')
.n. tInput()
.n. '</form>'
.n. '</div>';
}
}
/**
* Save the given privilege set.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
public function priv_save($evt, $stp)
{
global $txp_permissions;
require_privs($this->event.'.smd_um_prv');
$areas = ps('smd_um_areas');
foreach ($areas as $area) {
$ar_fakename = '__'.str_replace('.', '---', $area);
$privs = ps($ar_fakename);
$privs = $privs ? $privs: array();
$area = strtolower(sanitizeForPage($area));
$safe_area = doSlash($area);
$current_privs = safe_column('priv', SMD_UM_PRIVS, "area='{$safe_area}'");
$default_privs = isset($txp_permissions[$area]) ? do_list($txp_permissions[$area]) : array();
$diff_added = array_diff($privs, $default_privs);
$diff_removed = array_diff($current_privs, $privs);
// Only alter privs if they differ from what's already stored.
if ($diff_added || $diff_removed) {
// Delete the old area privs if they exist.
safe_delete(SMD_UM_PRIVS, "area='{$safe_area}'");
if (is_array($privs)) {
foreach ($privs as $priv) {
// Reset should always be first in the list since it's the first checkbox col.
// If reset, don't add the privs again (thus they will be read from admin_config.php).
if ($priv == 'smd_um_reset') {
break;
} else {
assert_int($priv);
safe_insert(SMD_UM_PRIVS, "area='{$safe_area}', priv='" . doSlash($priv) . "'");
}
}
}
}
}
// Merge the changes into the priv table
$this->priv_merge(false, true);
$this->message = gTxt('smd_um_prv_saved');
$this->privs($evt, $stp);
}
/**
* Add a privilege set.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
public function priv_add($evt, $stp)
{
global $txp_permissions;
require_privs($this->event.'.smd_um_prv');
$name = ps('smd_um_new_prv');
$name = strtolower(sanitizeForPage($name));
if ($name) {
if (strpos($name, 'smd_um') === 0) {
// Can't create privs for this plugin
$this->message = array(gTxt('smd_um_prv_smd_um'), E_USER_WARNING);
} else {
$exists = array_key_exists($name, $txp_permissions);
if ($exists) {
$this->message = array(gTxt('smd_um_prv_exists'), E_USER_WARNING);
} else {
safe_insert(SMD_UM_PRIVS, "area='" . doSlash($name) . "'");
$this->priv_merge(false, true);
$this->message = gTxt('smd_um_prv_created', array('{area}' => $name));
}
}
} else {
$this->message = array(gTxt('smd_um_name_required'), E_ERROR);
}
$this->privs($evt, $stp);
}
/**
* Privs management panel.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
public function privs($evt, $stp = '')
{
global $txp_permissions;
require_privs($this->event.'.smd_um_prv');
$msg = $this->message;
$grouplist_name = $this->get_groups(0);
$grouplist_title = $this->get_groups(1);
unset($grouplist_name[0]); // Don't want None privs
unset($grouplist_title[0]); // Ditto
$curr_area = '';
$area_count = 0;
$thatts = ' class="smd_um_grp_name" title="' . gTxt('smd_um_sel_grp') . '"';
$headers = '<thead>'.tr(
hCell('', '', ' class="smd_um_sel_area" title="' . gTxt('smd_um_sel_all') . '"')
.hCell(gTxt('smd_um_reset'), '', ' class="smd_um_reset_col" title="' . gTxt('smd_um_sel_reset') . '"')
.hCell(implode('</th><th'.$thatts.'>', $grouplist_title), '', $thatts)
, ' class="smd_um_prv_hdr"'). '</thead>';
$viz = do_list(get_pref('pane_smd_um_priv_visible'));
pagetop(gTxt('smd_um_tab_name').' » '.gTxt('smd_um_prv_lbl'), $msg);
$btnbar = array();
$this->buttons($this->event, '', $btnbar);
$formToken = form_token();
echo '<h1 class="txp-heading">', gTxt('smd_um_heading_prv'), '</h1>',
n. '<div id="'.$this->event.'_control" class="txp-control-panel">',
n. implode(n, $btnbar).
n. form(
graf(
'<label for="smd_um_new_prv">' . gTxt('smd_um_prv_new') . '</label>'
.n.fInput('text', 'smd_um_new_prv', '', '', '', '', '', '', 'smd_um_new_prv')
.n.fInput('submit', 'smd_um_priv_add', gTxt('create'))
.n.eInput($this->event)
.n.sInput('smd_um_priv_add')
)
, '','','post','search-form'
).
n. '</div>';
echo n. '<form action="index.php" id="smd_um_privilege_form" method="post" name="longform" onsubmit="return verify(\''.gTxt('are_you_sure').'\')">'
.n. eInput($this->event).sInput('smd_um_priv_save').tInput();
foreach ($txp_permissions as $area => $privs) {
$priv_list = do_list($privs);
$area_parts = do_list($area, '.');
if (preg_match('/^([A-Za-z0-9]{3,3})\_/', $area_parts[0], $matches)) {
// Plugin.
$area_parts[0] = $matches[1];
}
// Start of a new area so close the previous one and start a new block
if ($curr_area != $area_parts[0]) {
if ($area_count > 0) {
echo '</tbody>' . endTable() . '</div></div>';
}
$area_head = gTxt($area_parts[0]);
$is_viz = in_array($area_parts[0], $viz);
$ref = 'smd_um_priv_'.$area_parts[0];
echo n. '<div class="smd_um_privgroup"><h3 class="txp-summary lever'. ($is_viz ? ' expanded' : ''). '"><a href="#'. $ref. '">'. $area_parts[0]. (($area_parts[0] != $area_head) ? ' ('. gTxt($area_parts[0]). ')' : ''). '</a></h3>'
.n. '<div id="'. $ref. '" class="toggle" style="display:'. ($is_viz ? 'block' : 'none'). '">'
.n. fInput('submit', 'smd_um_priv_save', gTxt('save'), 'smd_um_privsave publish')
.n. startTable('', '', 'txp-list')
.n. $headers
.n. '<tbody>';
}
$privboxes = array();
// Dots aren't valid characters for a name so replace them now and swap them back upon Save.
// Similarly, area names like 'lang' clash with core variables, so prefix them with __ here.
$safe_area = '__'.str_replace('.', '---', $area).'[]';
foreach ($grouplist_name as $id => $priv) {
$privboxes[] = td(checkbox($safe_area, $id, (in_array($id, $priv_list))), '', 'smd_um_checkbox');
}
echo tr(
tda($area.hInput('smd_um_areas[]', $area), ' class="smd_um_prv_name" title="' . gTxt('smd_um_sel_prv') . '"')
.td(checkbox($safe_area, 'smd_um_reset', 0), '', 'smd_um_resetbox')
.implode(n, $privboxes)
);
$curr_area = $area_parts[0];
$area_count++;
}
echo n. endTable()
.n. '</div></div>'
.n. fInput('hidden', 'smd_um_prv_del', '', '', '', '', '', '', 'smd_um_prv_del')
.n. '</form>';
echo script_js(<<<EOJS
jQuery.fn.smd_um_rowsel = function(idx) {
return jQuery('tr:nth-child('+(idx+1)+') td.smd_um_checkbox', this);
}
jQuery.fn.smd_um_colsel = function(idx) {
return jQuery('tr td:nth-child('+(idx+1)+')', this);
}
// Affect all highlighted checkboxes on keypress
function smd_um_toggleCheckbox(ev) {
key = ev.keyCode;
obj = jQuery('.smd_um_selected :checkbox');
switch(key) {
case 67:
// (c)heck selected boxes
obj.prop('checked', true);
break;
case 68:
// (d)eselect all selected rows/cols
jQuery('.smd_um_selected, .smd_um_rsel, .smd_um_csel').removeClass('smd_um_selected smd_um_rsel smd_um_csel');
break;
case 84:
// (t)oggle selected boxes
obj.each(function() {
cb = jQuery(this);
if (cb.prop('checked') == true) {
cb.prop('checked', false);
} else {
cb.prop('checked', true);