-
Notifications
You must be signed in to change notification settings - Fork 4
/
smd_access_keys.php
1801 lines (1508 loc) · 76.5 KB
/
smd_access_keys.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_access_keys';
// 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'] = '1.1.1';
$plugin['author'] = 'Stef Dawson';
$plugin['author_uri'] = 'https://stefdawson.com/';
$plugin['description'] = 'Permit access to content for a certain time period/number of access attempts';
// 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'] = '5';
// 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'] = '1';
// 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
#@language en, en-gb, en-us
#@admin-side
smd_akey => Access keys
#@smd_akey
smd_akey_accesses => Access attempts
smd_akey_btn_new => New key
smd_akey_btn_pref => Prefs
smd_akey_deleted => Keys deleted: {deleted}
smd_akey_err_bad_token => Missing or mangled access key
smd_akey_err_expired => Access expired
smd_akey_err_forbidden => Forbidden access
smd_akey_err_invalid_token => Invalid access key
smd_akey_err_limit => Access limit reached
smd_akey_err_missing_timestamp => Missing timestamp
smd_akey_err_unauthorized => Unauthorized access
smd_akey_err_unavailable => Not available
smd_akey_file_download_expires => File download expiry time (seconds)
smd_akey_generated => Access key: {key}
smd_akey_log_ip => Log IP addresses
smd_akey_max => Maximum
smd_akey_need_page => You need to enter a page URL
smd_akey_prefs_some_explain => This is either a new installation or a different version of the plugin to one you had before.
smd_akey_prefs_some_opts => Click "Install table" to add or update the table leaving all existing data untouched.
smd_akey_prefs_some_tbl => Not all table info available.
smd_akey_salt_length => Salt length (characters)
smd_akey_search => Search access keys
smd_akey_tbl_installed => Table installed
smd_akey_tbl_install_lbl => Install table
smd_akey_tbl_not_installed => Table not installed
smd_akey_tbl_not_removed => Table not removed
smd_akey_tbl_removed => Table removed
smd_akey_time => Issued
smd_akey_token_length => Access key length (characters)
smd_akey_trigger => Trigger
#@language it
#@admin-side
smd_akey => Chiavi di accesso
#@smd_akey
smd_akey_accesses => Tentativi di accesso
smd_akey_btn_new => Nuova chiave
smd_akey_btn_pref => Preferenze
smd_akey_deleted => Chiavi eliminate: {deleted}
smd_akey_err_bad_token => Chiavi mancanti o deteriorate
smd_akey_err_expired => Accesso scaduto
smd_akey_err_forbidden => Accesso vietato
smd_akey_err_invalid_token => Chiave di accesso non valida
smd_akey_err_limit => Limite di accesso raggiunto
smd_akey_err_missing_timestamp => Timestamp mancante
smd_akey_err_unauthorized => Accesso non autorizzato
smd_akey_err_unavailable => Non disponibile
smd_akey_file_download_expires => Scadenza File download (in secondi)
smd_akey_generated => Chiave di accesso: {key}
smd_akey_log_ip => Registro indirizzi IP
smd_akey_max => Massimo
smd_akey_need_page => Devi inserire un URL di pagina
smd_akey_prefs_some_explain => Questa è o una nuova installazione o una versione del plugin diversa da quella che avevi prima.
smd_akey_prefs_some_opts => Clicca “Installa tabella” per aggiungere o aggiornare la tabella lasciando intatti tutti i dati esistenti.
smd_akey_prefs_some_tbl => Info tabella non tutte disponibili.
smd_akey_salt_length => Lunghezza salt (in caratteri)
smd_akey_tbl_installed => Tabella installata
smd_akey_tbl_install_lbl => Installazione tabella
smd_akey_tbl_not_installed => Tabella non installata
smd_akey_tbl_not_removed => Tabella non rimossa
smd_akey_tbl_removed => Tabella rimossa
smd_akey_time => Emessa
smd_akey_token_length => Lunghezza chiave di accesso (in caratteri)
smd_akey_trigger => Trigger
EOT;
if (!defined('txpinterface'))
@include_once('zem_tpl.php');
# --- BEGIN PLUGIN CODE ---
/**
* smd_access_keys
*
* A Textpattern CMS plugin for secure tokenized access to resources. Features:
* -> Time-based or access attempt limits
* -> Untamperable URL-based keys
* -> Optional IP logging
*
* @author Stef Dawson
* @link https://stefdawson.com/
* @todo Add shortcut to send a newly-generated admin-side key to a user? (dropdown of users + e-mail template in prefs?)
* @todo Add auto-deletion of expired keys pref:
* -> File download keys can be deleted on any key access (expiry window is known via prefs).
* -> Other key accesses can only be deleted when that key is used.
* -> Configurable grace period after expiry, before deletion.
* @todo Obfuscated URLs?
* @todo Query an access key and separate it into its component parts for convenient testing.
* @todo Make a single key to cover /category/type URLs somehow?
*/
use Textpattern\Search\Filter;
if (txpinterface === 'admin') {
global $smd_akey_event;
$smd_akey_event = 'smd_akey';
add_privs($smd_akey_event, '1');
add_privs('prefs.smd_akey', '1,2,3');
add_privs('plugin_prefs.smd_access_keys', '1');
register_tab('extensions', $smd_akey_event, gTxt('smd_akey'));
register_callback('smd_akey_dispatcher', $smd_akey_event);
register_callback('smd_akey_prefs', 'prefs', '', 1);
register_callback('smd_akey_welcome', 'plugin_lifecycle.smd_access_keys');
register_callback('smd_akey_options', 'plugin_prefs.smd_access_keys');
} elseif (txpinterface === 'public') {
if (class_exists('\Textpattern\Tag\Registry')) {
Txp::get('\Textpattern\Tag\Registry')
->register('smd_access_error')
->register('smd_access_protect')
->register('smd_if_access_error');
}
/**
* Tag: Protect a page resource.
*
* The resource is protected for a given time limit from the moment the
* access token has been generated.
*
* Embed this tag at the top of the page to protect, or wrap it around
* part of a page to protect. The unique URL to unlock the resource
* is generated by <txp:smd_access_key />.
*
* @param array $atts (req) Tag attribute list
* @param array $thing (opt) Tag container content
* @return HTML Protected resource | error
*/
function smd_access_protect($atts, $thing = null)
{
global $smd_access_error, $smd_access_errcode, $smd_akey_protected_info, $permlink_mode, $plugins;
$smd_akey_prefs = smd_akey_get_prefs();
extract(lAtts(array(
'trigger' => 'smd_akey',
'trigger_mode' => 'exact', // exact, begins, ends, contains
'site_name' => '1',
'section_mode' => '0',
'force' => '0',
'expires' => '3600', // in seconds
), $atts));
if (smd_akey_table_exist(1)) {
$url = serverSet('REQUEST_URI');
if ($site_name && (strpos($url, hu) === false)) {
$urlparts = parse_url(hu);
// Can't use raw hu since it contains the subdir (as does the REQUEST_URI)
// so duplicates would occur in the generated URL.
$url = $urlparts['scheme'] . '://' . $urlparts['host'] . (!empty($urlparts['port']) ? ':'.$urlparts['port'] : '') . $url;
}
if ($section_mode == '1') {
$halves = explode('?', $url);
$half1 = explode('/', $halves[0]);
$half2 = (isset($halves[1])) ? explode('/', $halves[1]) : array();
$parts = array_merge($half1, $half2);
} else {
$parts = explode('/', $url);
}
trace_add('[smd_access_key URL elements: ' . join('|', $parts).']');
// Look for one of the triggers in the URL and bomb out if we find it.
$triggers = do_list($trigger);
$trigger = $triggers[0]; // Initialise to the first value in case no others are found.
$trigoff = false;
foreach ($triggers as $trig) {
switch ($trigger_mode) {
case 'exact':
$trigoff = array_search($trig, $parts);
$realTrig = $trig;
break;
case 'begins':
$count = 0;
foreach ($parts as $part) {
if (strpos($part, $trig) === 0) {
$trigoff = $count;
$realTrig = $part;
break;
}
$count++;
}
break;
case 'ends':
$count = 0;
foreach ($parts as $part) {
$re = '/.+'.preg_quote($trig).'$/i';
if (preg_match($re, $part) === 1) {
$trigoff = $count;
$realTrig = $part;
break;
}
$count++;
}
break;
case 'contains':
$count = 0;
foreach ($parts as $part) {
$re = '/.*'.preg_quote($trig).'.*$/i';
if (preg_match($re, $part) === 1) {
$trigoff = $count;
$realTrig = $part;
break;
}
$count++;
}
break;
}
if ($trigoff !== false) {
// Found it so set the trigger to be the current item and jump out.
$trigoff = ($trigger == 'file_download') ? $trigoff + 2 : $trigoff;
$trigger = $realTrig;
break;
}
}
trace_add('[smd_access_key trigger: ' . $trigger . ($trigoff ? ' found at ' . $trigoff : '') . ']');
$ret = false;
$smd_access_error = $smd_access_errcode = '';
$smd_akey_salt_length = get_pref('smd_akey_salt_length', $smd_akey_prefs['smd_akey_salt_length']['default']);
$smd_akey_token_length = max(get_pref('smd_akey_token_length', $smd_akey_prefs['smd_akey_token_length']['default']), 32);
$doip = get_pref('smd_akey_log_ip', $smd_akey_prefs['smd_akey_log_ip']['default']);
if ($trigoff !== false) {
$tokidx = $trigoff + 1;
$timeidx = $trigoff + 2;
$extraidx = $trigoff + 3;
// OK, on a trigger page, so read the token from the URL.
$tok = (isset($parts[$tokidx]) && strlen($parts[$tokidx]) == intval($smd_akey_token_length + $smd_akey_salt_length)) ? $parts[$tokidx] : 0;
trace_add('[smd_access_key token: ' . $tok .']');
if ($tok) {
// The token is present, so read the timestamp from the URL.
$t_hex = (isset($parts[$timeidx])) ? $parts[$timeidx] : 0;
// Is there a download limit? Extract it if so.
$timeparts = do_list($t_hex, '.');
$max = (isset($timeparts[1])) ? $timeparts[1] : '0';
$maxtok = ($max) ? '.'.$max : '';
$t_hex = $timeparts[0];
// Any extra info?
$extras = (isset($parts[$extraidx])) ? array_slice($parts, $extraidx) : array();
// Recreate the original page URL, sans /trigger/token/time.
if ($trigger == 'file_download') {
$trigoff++;
$trigger = '';
}
// gbp_permanent_links sets messy mode behind the scenes but still uses non-messy URLs
// so it requires an exception.
$gbp_pl = (is_array($plugins) && in_array('gbp_permanent_links', $plugins));
if ($permlink_mode == 'messy' && !$gbp_pl) {
// Don't want a slash between site and start of query params.
$page = rtrim(join('/', array_slice($parts, 0, $trigoff-1)), '/') . $parts[$trigoff-1];
} else {
$page = rtrim(join('/', array_slice($parts, 0, $trigoff)), '/');
}
// In case the URL contains non-ascii chars.
$page = rawurldecode($page);
trace_add('[smd_access_key page | timestamp | max | extras: ' . join('|', array($page, $t_hex, $max)+$extras) . ']');
if ($t_hex) {
// The timestamp is present. Next, get the secret key.
$secret = false;
$secring = safe_row('*', SMD_AKEYS, "page='".doSlash($page)."' AND t_hex = '".doSlash($t_hex)."'");
if ($secring) {
$secret = $secring['secret'];
// Extract the salt from the token.
$plen = strlen($page) % $smd_akey_token_length;
$salt = substr($tok, $plen, $smd_akey_salt_length);
$tok = substr($tok, 0, $plen).substr($tok, $plen+$smd_akey_salt_length);
$ext = (($extras) ? urldecode(join('/', $extras)) : '');
// Regenerate the original token...
$check_token = md5($salt.$secret.$page.$trigger.$t_hex.$maxtok.$ext);
trace_add('[smd_access_key reconstructed token: ' . $check_token . ']');
// ... and compare it to the one in the URL.
if ($check_token == $tok) {
// Token is valid. Now check if the page has expired.
// Is there an explicit access key expiry? Extract that if so.
$timeparts = do_list($t_hex, '-');
$t_exp = (isset($timeparts[1])) ? hexdec($timeparts[1]) : '';
$t_beg = $timeparts[0];
$t_dec = hexdec($t_beg);
$now = time();
// Has the resource become available yet?
if ($now < $t_dec) {
$smd_access_error = 'smd_akey_err_unavailable';
$smd_access_errcode = 410;
} else {
// Has token's expiry been reached, or is 'now' greater than 'then' (when token generated) + expiry period?
if ($t_exp) {
$tester = true;
$compare_to = $t_exp;
} else {
$tester = ($expires != 0);
$compare_to = $t_dec + $expires;
}
if ($tester && ($now > $compare_to)) {
$smd_access_error = 'smd_akey_err_expired';
$smd_access_errcode = 410;
} else {
// Check if the download limit has been exceeded.
$vu_qty = $secring['accesses'];
if ($max) {
if ($vu_qty < $max) {
$ret = true;
} else {
$smd_access_error = 'smd_akey_err_limit';
$smd_access_errcode = 410;
}
} else {
$ret = true;
}
// Increment the access counter.
$vu_qty++;
// Grab the IP and add it to the list of IPs so far.
if ($doip) {
$ips = do_list($secring['ip'], ' ');
$ip = remote_addr();
if (!in_array($ip, $ips)) {
$ips[] = $ip;
}
$ipup = ", ip='".doSlash(trim(join(' ', $ips)))."'";
} else {
$ipup = '';
}
safe_update(SMD_AKEYS, "accesses='".doSlash($vu_qty)."'" . $ipup, "page='".doSlash($page)."' AND t_hex = '".doSlash($t_hex)."'");
// Load up the global array so <txp:smd_access_info> and <txp:if_smd_access_info> work.
$smd_akey_protected_info = array(
'page' => $secring['page'],
'hextime' => $secring['t_hex'],
'issued' => $secring['time'],
'now' => $now,
'expires' => $compare_to,
'trigger' => $secring['triggah'],
'maximum' => $secring['maximum'],
'accesses' => $vu_qty,
);
if ($doip) {
$smd_akey_protected_info['ip'] = $ip;
}
if ($extras) {
$smd_akey_protected_info['extra'] = urldecode(join('/', $extras));
foreach ($extras as $idx => $extra) {
$smd_akey_protected_info['extra_'.intval($idx+1)] = urldecode($extra);
}
}
}
}
} else {
$smd_access_error = 'smd_akey_err_invalid_token';
$smd_access_errcode = 403;
}
} else {
$smd_access_error = 'smd_akey_err_unauthorized';
$smd_access_errcode = 401;
}
} else {
$smd_access_error = 'smd_akey_err_missing_timestamp';
$smd_access_errcode = 403;
}
} else {
$smd_access_error = 'smd_akey_err_bad_token';
$smd_access_errcode = 403;
}
} else {
// If we always want to forbid access to this page regardless if the trigger exists.
if ($force === '1') {
$smd_access_error = 'smd_akey_err_forbidden';
$smd_access_errcode = 401;
} elseif ($force === 'partial') {
$ret = false;
} else {
$ret = true;
}
}
if ($smd_access_error || $smd_access_errcode) {
trace_add('[smd_access_key error state: ' . $smd_access_errcode . '|' . $smd_access_error . ']');
if ($thing === null) {
txp_die(gTxt($smd_access_error), $smd_access_errcode);
}
}
// If we reach this point it's because we're using a container.
return parse($thing, $ret);
} else {
trigger_error(gTxt('smd_akey_tbl_not_installed'), E_USER_NOTICE);
}
}
/**
* Display access error information.
*
* @param array $atts (req) Tag attribute list
* @param array $thing (opt) Tag container content
* @return HTML
*/
function smd_access_error($atts, $thing = null)
{
global $smd_access_error, $smd_access_errcode;
extract(lAtts(array(
'item' => 'message',
'message' => '',
'wraptag' => '',
'class' => '',
'html_id' => '',
'break' => '',
'breakclass' => '',
), $atts));
$out = array();
$items = do_list($item);
if ($smd_access_errcode && in_array('code', $items)) {
$out[] = $smd_access_errcode;
}
if ($smd_access_error && in_array('message', $items)) {
$out[] = ($message) ? $message : gTxt($smd_access_error);
}
if ($out) {
return doWrap($out, $wraptag, $break, $class, $breakclass, '', '', $html_id);
}
return '';
}
/**
* Conditional tag for checking error status from smd_access_protect.
*
* @param array $atts (req) Tag attribute list
* @param array $thing (opt) Tag container content
* @return HTML
*/
function smd_if_access_error($atts, $thing = null)
{
global $smd_access_error, $smd_access_errcode;
extract(lAtts(array(
'type' => '',
'code' => '',
), $atts));
$err = array();
$codes = do_list($code);
$types = do_list($type);
if ($smd_access_error) {
if ($code && $type) {
$err['code'] = (in_array($smd_access_errcode, $codes)) ? true : false;
$err['msg'] = (in_array($smd_access_error, $types)) ? true : false;
} elseif ($code) {
$err['code'] = (in_array($smd_access_errcode, $codes)) ? true : false;
} elseif ($type) {
$err['msg'] = (in_array($smd_access_error, $types)) ? true : false;
} else {
$err['msg'] = true;
}
}
$out = in_array(false, $err) ? false : true; // AND logic
return parse($thing, $out);
}
}
// Register these all the time, since they're used on the admin side too.
if (class_exists('\Textpattern\Tag\Registry')) {
Txp::get('\Textpattern\Tag\Registry')
->register('smd_access_info')
->register('smd_access_key');
}
if (!defined('SMD_AKEYS')) {
define("SMD_AKEYS", 'smd_akeys');
}
register_callback('smd_access_protect_download', 'file_download');
/**
* ADMIN SIDE INTERFACE
* ====================
*
* Jump off point for event/steps.
*
* @param string $evt (req) Textpattern event
* @param string $stp (req) Textpattern step
*/
function smd_akey_dispatcher($evt, $stp)
{
if (!$stp or !in_array($stp, array(
'smd_akey_table_install',
'smd_akey_table_remove',
'smd_akey_create',
'smd_akey_multi_edit',
'smd_akey_change_pageby',
))) {
smd_akey('');
} else $stp();
}
/**
* Bootstrap when plugin installed/deleted.
*
* @param string $evt (req) Textpattern event
* @param string $stp (req) Textpattern step
* @return string Notification message
*/
function smd_akey_welcome($evt, $stp)
{
$msg = '';
switch ($stp) {
case 'installed':
smd_akey_table_install(0);
$msg = 'Restrict your Textpattern world :-)';
break;
case 'deleted':
smd_akey_table_remove(0);
break;
}
return $msg;
}
/**
* Main admin interface
*
* @param string $msg (opt) Flash status message to display
* @return HTML Page content
*/
function smd_akey($msg = '')
{
global $smd_akey_event, $logging, $event;
$smd_akey_prefs = smd_akey_get_prefs();
pagetop(gTxt('smd_akey'), $msg);
if (smd_akey_table_exist(1)) {
extract(gpsa(array('page', 'sort', 'dir', 'crit', 'search_method')));
if ($sort === '') {
$sort = get_pref('smd_akey_sort_column', 'time');
} else {
if (!in_array($sort, array('page', 'triggah', 'time', 'expires', 'maximum', 'accesses', 'ip'))) {
$sort = 'time';
}
set_pref('smd_akey_sort_column', $sort, 'smd_akey', PREF_HIDDEN, '', 0, PREF_PRIVATE);
}
if ($dir === '') {
$dir = get_pref('smd_akey_sort_dir', 'desc');
} else {
$dir = ($dir == 'asc') ? "asc" : "desc";
set_pref('smd_akey_sort_dir', $dir, 'smd_akey', PREF_HIDDEN, '', 0, PREF_PRIVATE);
}
switch ($sort) {
case 'page':
$sort_sql = 'page '.$dir.', time desc';
break;
case 'triggah':
$sort_sql = 'triggah '.$dir.', time desc';
break;
case 'maximum':
$sort_sql = 'maximum '.$dir.', time desc';
break;
case 'accesses':
$sort_sql = 'accesses '.$dir.', time desc';
break;
case 'ip':
$sort_sql = 'ip '.$dir.', time desc';
break;
default:
$sort = 'time';
$sort_sql = 'time '.$dir;
break;
}
$switch_dir = ($dir == 'desc') ? 'asc' : 'desc';
$showip = get_pref('smd_akey_log_ip', $smd_akey_prefs['smd_akey_log_ip']['default'], 1);
$searchCols = array(
'page' => array(
'column' => SMD_AKEYS.'.page',
'label' => gTxt('page'),
),
'triggah' => array(
'column' => SMD_AKEYS.'.triggah',
'label' => gTxt('smd_akey_trigger'),
),
'time' => array(
'column' => SMD_AKEYS.'.time',
'label' => gTxt('smd_akey_time'),
'options' => array('case_sensitive' => true),
),
'maximum' => array(
'column' => SMD_AKEYS.'.maximum',
'label' => gTxt('smd_akey_max'),
'type' => 'numeric',
),
'accesses' => array(
'column' => SMD_AKEYS.'.accesses',
'label' => gTxt('smd_akey_accesses'),
'type' => 'numeric',
),
);
if ($showip) {
$searchCols['ip'] = array(
'column' => SMD_AKEYS.'.ip',
'label' => 'IP',
);
}
$search = new Filter($event, $searchCols);
list($criteria, $crit, $search_method) = $search->getFilter();
$search_render_options = array('placeholder' => 'smd_akey_search');
$total = safe_count(SMD_AKEYS, $criteria);
$searchBlock =
n.tag(
$search->renderForm('smd_akey', $search_render_options),
'div', array(
'class' => 'txp-layout-4col-3span',
'id' => $event.'_control',
)
);
// Set up the buttons.
$newbtn = '<a class="navlink smd_akey_btn_new" href="#">'.gTxt('smd_akey_btn_new').'</a>';
$prefbtn = '<a class="navlink" href="'.prefs_link().'">'.gTxt('smd_akey_btn_pref').'</a>';
$createBlock =
n.tag(
$newbtn.$prefbtn,
'div', array('class' => 'txp-control-panel')
);
$contentBlock = '';
$paginator = new \Textpattern\Admin\Paginator($event, 'smd_akey');
$limit = $paginator->getLimit();
list($page, $offset, $numPages) = pager($total, $limit, $page);
$contentBlock .= script_js(<<<EOC
jQuery(function() {
jQuery('#smd_akey_container').on('click', '.smd_akey_btn_new', function(ev) {
ev.preventDefault();
var box = jQuery("#smd_akey_create");
box.toggleClass('ui-helper-hidden');
jQuery("input.smd_focus").focus();
});
jQuery("#smd_akey_add").on('click', function(ev) {
ev.preventDefault();
step = '';
jQuery("[name=step]").val('smd_akey_create');
jQuery("#smd_akey_form").submit();
});
});
EOC
);
// Access key list.
$headers = array(
'page' => 'page',
'triggah' => 'smd_akey_trigger',
'time' => 'smd_akey_time',
'expires' => 'expires',
'maximum' => 'smd_akey_max',
'accesses' => 'smd_akey_accesses',
);
if ($showip) {
$headers['ip'] = 'IP';
}
$dates = array('time', 'expires');
$head_row = hCell(
fInput('checkbox', 'select_all', 0, '', '', '', '', '', 'select_all'),
'', 'class="txp-list-col-multi-edit" scope="col" title="'.gTxt('toggle_all_selected').'"'
);
foreach ($headers as $header => $column_head) {
if ($header == 'expires') {
$head_row .= hcell(gTxt($column_head), $header, ' class="date time" data-col="expires"');
} else {
$head_row .= column_head(array(
'options' => array(
'class' => trim('txp-list-col-'.$header.($header == $sort ? " $dir" : '').(in_array($header, $dates) ? ' date' : ''))),
'value' => $column_head,
'sort' => $header,
'event' => 'smd_akey',
'step' => 'smd_akey',
'is_link' => true,
'dir' => $switch_dir,
'crit' => $crit,
'method' => $search_method,
));
}
}
$contentBlock .= n.tag_start('form', array(
'class' => 'multi_edit_form',
'id' => 'smd_akey_form',
'name' => 'longform',
'method' => 'post',
'action' => 'index.php',
)).
n.tag_start('div', array('class' => 'txp-listtables')).
n.tag_start('table', array('class' => 'txp-list')).
n.tag_start('thead').
tr($head_row).
n.tag_end('thead');
$contentBlock .= n.tag_start('tbody');
// New access key row.
$contentBlock .= '<tr id="smd_akey_create" class="ui-helper-hidden">';
$contentBlock .= td(fInput('submit', 'smd_akey_add', gTxt('add'), 'smallerbox', '', '', '', '', 'smd_akey_add'))
.td(fInput('text', 'smd_akey_newpage', '', 'smd_focus', '', '', '50'))
.td(fInput('text', 'smd_akey_triggah', ''))
.td(fInput('text', 'smd_akey_time', safe_strftime('%Y-%m-%d %H:%M:%S'), '', '', '', '25'))
.td(fInput('text', 'smd_akey_expires', '', '', '', '', '25'))
.td(fInput('text', 'smd_akey_maximum', '', '', '', '', '5'))
.td(' ')
. (($showip) ? td(' ') : '');
$contentBlock .= '</tr>';
if ($total < 1 && $criteria != 1) {
$contentBlock .= tr(tdcs(
span(null, array('class' => 'ui-icon ui-icon-info')).' '.
gTxt('no_results_found')
, 7)
, array('class' => 'alert-block information')
).n.tag_end('tbody').
n.tag_end('table').
n.tag_end('div'). // End of .txp-listtables
tInput().eInput($smd_akey_event).sInput('').
n.tag_end('form');
} else {
// Retrieve the secret keyring table entries.
$secring = safe_rows('*', SMD_AKEYS, "$criteria order by $sort_sql limit $offset, $limit");
// Remaining access keys.
foreach ($secring as $secidx => $data) {
if ($showip) {
$ips = do_list($data['ip'], ' ');
$iplist = array();
foreach ($ips as $ip) {
$iplist[] = ($logging == 'none') ? $ip : eLink('log', 'log_list', 'search_method', 'ip', $ip, 'crit', $ip);
}
}
$dkey = $data['page'].'|'.$data['t_hex'];
$timeparts = do_list($data['t_hex'], '-');
$expiry = (isset($timeparts[1])) ? hexdec($timeparts[1]) : '';
$contentBlock .= tr(
td(fInput('checkbox', 'selected[]', $dkey, 'checkbox'), '', 'txp-list-col-multi-edit')
. td('<a href="'.$data['page'].'">'.$data['page'].'</a>', '', 'page')
. td($data['triggah'])
. td(safe_strftime('%Y-%m-%d %H:%M:%S', $data['time']), 85, 'date time')
. td( (($expiry) ? safe_strftime('%Y-%m-%d %H:%M:%S', $expiry) : '-'), 85, 'date time')
. td($data['maximum'])
. td($data['accesses'])
. ( ($showip) ? td( trim(join(' ', $iplist)), 20, 'ip' ) : '' )
);
}
$multiOpts = array('smd_akey_delete' => gTxt('delete'));
$contentBlock .= n.tag_end('tbody').
n.tag_end('table').
n.tag_end('div'). // End of .txp-listtables.
multi_edit($multiOpts, 'smd_akey', 'smd_akey_multi_edit', $page, $sort, $dir, $crit, $search_method).
tInput().eInput($smd_akey_event).
n.tag_end('form');
}
$pageBlock = $paginator->render().
nav_form('smd_akey', $page, $numPages, $sort, $dir, $crit, $search_method, $total, $limit);
$table = new \Textpattern\Admin\Table($event);
// No Ajax updates or it breaks the 'New key' button after an Ajax call.
$html_id = '';
$heading = $event;
echo $table->render(compact('heading', 'total', 'crit', 'html_id'), $searchBlock, $createBlock, $contentBlock, $pageBlock);
} else {
// Table not installed.
$out = n.'<div class="txp-layout">'.
n.tag(
hed(gTxt('smd_akey'), 1, array('class' => 'txp-heading')),
'div', array('class' => 'txp-layout-4col-alt')
);
$out .= tag_start('div', array(
'class' => 'txp-layout-1col',
'id' => $event.'_container',
));
$btnInstall = '<form method="post" action="?event='.$smd_akey_event.a.'step=smd_akey_table_install">'.fInput('submit', 'submit', gTxt('smd_akey_tbl_install_lbl'), 'smallerbox').'</form>';
$out .= graf(strong(gTxt('smd_akey_prefs_some_tbl')))
.graf(gTxt('smd_akey_prefs_some_explain'))
.graf(gTxt('smd_akey_prefs_some_opts'));
$out .= $btnInstall;
$out .= '</div>'
.'</div>';
echo $out;
}
}
/**
* Change and store qty-per-page value.
*/
function smd_akey_change_pageby()
{
event_change_pageby('smd_akey');
smd_akey();
}
/**
* Create a key from the admin side's 'New key' button.
*/
function smd_akey_create()
{
extract(gpsa(array('smd_akey_newpage', 'smd_akey_triggah', 'smd_akey_time', 'smd_akey_expires', 'smd_akey_maximum')));
if ($smd_akey_newpage) {
// Just call the public tag with the relevant options.
$key = smd_access_key(
array(
'url' => $smd_akey_newpage,
'trigger' => $smd_akey_triggah,
'start' => $smd_akey_time,
'expires' => $smd_akey_expires,
'max' => $smd_akey_maximum,
)
);
$msg = gTxt('smd_akey_generated', array('{key}' => $key));
} else {
$msg = array(gTxt('smd_akey_need_page'), E_ERROR);
}
smd_akey($msg);
}
/**
* Handle submission of the multi-edit dropdown options.
*/
function smd_akey_multi_edit()
{
$selected = gps('selected');
$operation = gps('edit_method');
$del = 0;
$msg = '';
switch ($operation) {
case 'smd_akey_delete':
if ($selected) {
foreach ($selected as $sel) {
$parts = explode('|', $sel);
$ret = safe_delete(SMD_AKEYS, "page = '" . $parts[0] . "' AND t_hex = '" . $parts[1] . "'");
$del = ($ret) ? $del+1 : $del;
}
$msg = gTxt('smd_akey_deleted', array('{deleted}' => $del));
}
break;
}
smd_akey($msg);
}
/**
* Fetch the admin-side prefs panel link.
*/
function prefs_link()
{
return '?event=prefs#prefs_group_smd_akey';
}
/**
* Jump to the prefs panel from the Plugin options link.
*
* @return HTML Page sub-content.
*/
function smd_akey_options()