-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathais_url_alias.php
More file actions
1219 lines (1033 loc) · 36.8 KB
/
ais_url_alias.php
File metadata and controls
1219 lines (1033 loc) · 36.8 KB
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
/**
* ais_url_alias - URL aliases for Textpattern
*
* Copyright (C) 2025 Ashley Butcher (Alien Internet Services)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @author Ashley Butcher (Alien Internet Services)
* @copyright Copyright (C) 2025 Ashley Butcher (Alien Internet Services)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License version 3
* @version 0.4
* @link https://github.com/alieninternet/ais_url_alias/
*/
// Test mode of operation
switch (txpinterface) {
case 'admin':
ais_url_alias::newAdmin();
break;
case 'public':
/**
* Callback handler
*
* @param string $event
* @param string $step
*/
function ais_url_alias_handler($event, $step) {
ais_url_alias::handlePublicEvent($event);
}
// Register callback(s)
register_callback('ais_url_alias_handler', 'pretext_end', '', 1);
break;
}
/**
* Regex validation constraint (not provided by Textpattern API before version 4.9.0)
*
* This will be obsolete in Textpattern 4.9.0 (replaced with \Textpattern\Validator\PatternConstraint)
*/
class ais_url_alias_RegexConstraint extends \Textpattern\Validator\Constraint
{
/**
* Constructor.
*
* @param mixed $value The value to validate
* @param array $options Key/value pair containing options - 'regex' for the regular expression to include, 'message' for a custom error message
*/
public function __construct($value, $options = [])
{
// Merge options provided with local defaults
$options = lAtts(['message' => '',
'regex' => ''],
$options,
false);
parent::__construct($value, $options);
}
/**
* Validate a given value against this constraint.
*
* @return bool When true, the
*/
public function validate()
{
return preg_match($this->options['regex'], $this->value) >= 1;
}
}
/**
* Support class
*/
class ais_url_alias
{
/**
* Preference defaults
*/
const PREF_DEFAULT_CUSTOM_FIELDS = '';
const PREF_DEFAULT_REDIRECT_PERMANENT = '0';
const PREF_DEFAULT_SHOW_ARTICLE_CUSTOM_FIELD_VALIDITY = '1';
/**
* Preference names
*/
const PREF_NAME_ALIASES_SORT_COL = 'ais_url_alias_aliases_sort_col';
const PREF_NAME_ALIASES_SORT_DIR = 'ais_url_alias_aliases_sort_dir';
const PREF_NAME_CUSTOM_FIELDS = 'ais_url_alias_custom_fields';
const PREF_NAME_REDIRECT_PERMANENT = 'ais_url_alias_redirect_permanent';
const PREF_NAME_SHOW_ARTICLE_CUSTOM_FIELD_VALIDITY = 'ais_url_alias_show_article_custom_field_validity';
/**
* Diagnostic message constants
*/
const DIAG_ERROR = 'e';
const DIAG_INFO = 'i';
const DIAG_SUCCESS = 's';
const DIAG_WARNING = 'w';
/**
* HTTP status codes and texts
*/
const HTTP_FOUND = 302;
const HTTP_FOUND_TEXT = 'Found';
const HTTP_MOVED_PERMANENTLY = 301;
const HTTP_MOVED_PERMANENTLY_TEXT = 'Moved permanently';
/**
* Regular expressions (validation)
*/
// This pattern follows RFC3986, avoiding a '/' prefix, and forbidding invalid %nn escapes and disallowing #
const REGEX_URL_ALIAS_PATH = '^(?:[a-zA-Z0-9._~!$&\'\\(\\)*+,;=:@%\\-](?:[a-zA-Z0-9._~!$&\'\\(\\)*+,;=:@\\/\\-]|%[0-9a-fA-F]{2})*)?$';
/**
* Other constants
*/
const MAX_CUSTOM_FIELD_NUM = 10;
/**
* The plugin's event as registered in Textpattern
*/
protected string $event = __CLASS__;
/**
* Preferences
*/
private ?array $customFields = null;
private ?bool $redirectPermanent = null;
private ?bool $showArticleCustomFieldValidity = null;
/**
* Constructor
*/
private function __constructor()
{
}
/**
* Bounce to a new URL
*
* @param string $newURL The new URL (location) to bounce to
*/
private function bounce($newURL) : void
{
global $production_status;
if (isset($newURL) &&
(strlen($newURL) > 0)) {
// In debug mode, output the bounce link as debug information rather than automatically bounce
if ($production_status === 'debug') {
echo '<div style="display:block;background:#f00;width:100%;font-family:monospace;color:#000;padding:1em;">[Plugin ais_url_alias] Redirect to <a href="' . $newURL . '" style="color:#000;">' . $newURL . '</a></div>';
} else {
$statusCode = self::HTTP_FOUND;
$statusText = self::HTTP_FOUND_TEXT;
$this->getPrefs();
// If we're live, and if configured for permanent redirection, we can return a 301 instead of a 302
if ($production_status === 'live') {
$this->getPrefs();
if ($this->redirectPermanent) {
$statusCode = self::HTTP_MOVED_PERMANENTLY;
$statusText = self::HTTP_MOVED_PERMANENTLY_TEXT;
}
}
// Set the location header and response code and die gracefully
txp_die($statusText, $statusCode, $newURL);
}
}
}
/**
* Check if CTE support is available in the database engine
*
* @return bool True if CTE support is available, otherwise false
*/
private function canCTE()
{
global $DB;
// CTE support was added in MySQL 8.0 (part of SQL:1999)
return (explode('.', $DB->version)[0] >= 8);
}
/**
* Event handler for article validation on save/publish
*
* @param string $event Textpattern event
* @param string $step Textpattern step (action)
* @param mixed $data Callback payload data
* @param mixed $options Callback payload options -> validation constraints
*/
public function eventArticleValidate($event, $step, &$data, &$options) : void
{
assert(($event === 'article_ui') &&
(($step === 'validate_publish') ||
($step === 'validate_safe')));
// Ensure preferences are loaded
$this->getPrefs();
// PHP regular expressions need to be wrapped up in a delimiter
$regex = ('[' . self::REGEX_URL_ALIAS_PATH . ']');
// Loop through configured custom fields
foreach ($this->customFields as $customField) {
if (is_numeric($customField)) {
$customFieldName = ('custom_' . $customField);
// If we are running on Textpattern 4.9.0 we can use standard functionality
if (version_compare(txp_version, '4.9.0', '>=')) {
$options[$customFieldName] =
new \Textpattern\Validator\PatternConstraint($data[$customFieldName],
['message' => 'ais_url_alias_error_invalid_alias_format',
'pattern' => $regex]);
} else {
// Use a built-in validator
$options[$customFieldName] =
new ais_url_alias_RegexConstraint($data[$customFieldName],
['message' => 'ais_url_alias_error_invalid_alias_format',
'regex' => $regex]);
}
}
}
}
/**
* Event handler for installation diagnostics
*
* @param string $event Textpattern event
* @param string $step Textpattern step (action)
*/
public function eventDiag($event, $step) : void
{
assert($event === 'diag');
// Ensure we have the right event/step
if ($step !== 'steps') {
$output = [];
$this->getPrefs();
// Check if custom fields have been configured
if (empty($this->customFields)) {
$output[] = [self::DIAG_ERROR,
($this->t('error_no_custom_fields') . ' ' .
sLink(('plugin_prefs.' . $this->event), 'edit', $this->t('see_plugin_configuration')))];
} else {
// These checks requires CTE support in the database engine
if ($this->canCTE()) {
// Build a CTE to help flatten the article IDs and URL alias fields - we'll use it a few times
$cteName = rtrim(base64_encode(md5(microtime())), "=");
$sqlCTE = $this->sqlCTE($cteName);
// Ensure we have a CTE - we should, since custom fields should be configured
if (!empty($sqlCTE)) {
// Check for aliases used by other articles
$resultSet = safe_query($sqlCTE . 'SELECT DISTINCT A.ID AS ID, A.C AS C FROM ' . $cteName .
' AS A INNER JOIN ' . $cteName . ' AS B ON (A.C = B.C) AND (A.ID <> B.ID) ORDER BY A.ID ASC;');
if ($resultSet &&
(numRows($resultSet) > 0)) {
while ($row = nextRow($resultSet)) {
$output[] = [self::DIAG_ERROR,
$this->t('diag_error_duplicate_alias',
['{article}' => eLink('article', 'edit', 'ID', $row['ID'], $row['ID']),
'{alias}' => htmlspecialchars($row['C'])],
false)];
}
} else {
$output[] = [self::DIAG_SUCCESS, $this->t('diag_no_duplicate_aliases')];
}
// Check for invalid values
$resultSet = safe_query($sqlCTE . 'SELECT DISTINCT ID, C FROM ' . $cteName .
' WHERE (C NOT REGEXP \'' . safe_escape(self::REGEX_URL_ALIAS_PATH) . '\') ORDER BY ID ASC;');
if ($resultSet &&
(numRows($resultSet) > 0)) {
while ($row = nextRow($resultSet)) {
$output[] = [self::DIAG_ERROR,
$this->t('diag_error_invalid_alias_format',
['{article}' => eLink('article', 'edit', 'ID', $row['ID'], $row['ID']),
'{alias}' => htmlspecialchars($row['C'])],
false)];
}
} else {
$output[] = [self::DIAG_SUCCESS, $this->t('diag_no_invalid_alias_format')];
}
}
}
}
// Collate diagnostics results if something was created
if (!empty($output)) {
$content = '';
foreach ($output as $out) {
$cssClass = '';
switch ($out[0])
{
case self::DIAG_ERROR:
$cssClass = 'error';
break;
case self::DIAG_WARNING:
$cssClass = 'warning';
break;
case self::DIAG_SUCCESS:
$cssClass = 'success';
break;
case self::DIAG_INFO:
default:
$cssClass = 'information';
}
$content .= tag(tag($out[1],
'span',
['class' => $cssClass]),
'li');
}
// Output diagnostic results HTML snippet
if (!empty($content)) {
echo tag(tag((hed($this->t('diag_title'), 2) .
tag($content,
'ul')),
'div',
['class' => 'txp-layout-1col']),
'div',
['class' => ('txp-layout ' . $this->event)]);
}
}
}
}
/**
* Event handler for CSS/JS header injection
*
* @param string $event Textpattern event
* @param string $step Textpattern step (action)
* @return string Success/failure message
*/
public function eventHead($event, $step) : void
{
assert(($event === 'admin_side') &&
($step === 'head_end'));
global $event;
$css = [];
$js = [];
$eventTokens = explode('.', $event);
switch ($eventTokens[0]) {
// Add javascript for the article page to dynamically modify the custom fields with validation for URNs
case 'article':
$this->getPrefs();
if (!empty($this->customFields)) {
// Escape regex - it needs to be inside javascript, and inside HTML. What a mess.
$regex = str_replace('\\', '\\\\', self::REGEX_URL_ALIAS_PATH);
$js[] = ('function ais_url_alias_(){if(jQuery){var r="' . $regex . '";');
$cssInput = [];
$cssInputInvalid = [];
$cssInputAfter = [];
$cssInputAfterInvalid = [];
$cssInputAfterValid = [];
foreach ($this->customFields as $customField) {
if (is_numeric($customField)) {
// Add pattern to configured custom field for client-side input validation
$js[] = ('$("#custom-' . $customField . '").attr("pattern",r);');
// Add a class to the custom field for styling (if configured)
if ($this->showArticleCustomFieldValidity) {
$js[] = ('$("#custom-' . $customField . '").addClass("' . $this->event . '");');
}
}
}
// Finish JS - trigger on document load and DOM change
$js[] = ('}};' .
'$(document).ready(ais_url_alias_);' .
'new (window.MutationObserver||window.WebKitMutationObserver)(ais_url_alias_).observe(document,{subtree:true,childList:true});');
// Build CSS if validity should be shown
if ($this->showArticleCustomFieldValidity) {
$cssElement = ('input.' . $this->event);
$css[] = ($cssElement . '{padding-right:1.75em;background-repeat:no-repeat;background-position:right center;background-size:1.75em;background-origin:border-box;}' .
$cssElement . ':invalid{text-decoration:#f00 wavy underline !important;background-image:url("data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22 fill=%22red%22%3E%3Cpath d=%22M12 10.59L5.41 4 4 5.41 10.59 12 4 18.59 5.41 20 12 13.41l6.59 6.59L20 18.59 13.41 12 20 5.41 18.59 4z%22/%3E%3C/svg%3E");}' .
$cssElement . ':valid{background-image:url("data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22 fill=%22green%22%3E%3Cpath d=%22M9 16.2l-4.2-4.2 1.4-1.4L9 13.4l8.8-8.8 1.4 1.4L9 16.2z%22/%3E%3C/svg%3E");}}');
}
}
break;
// Adjust the custom fields in the preferences to show they are used for URL aliases
case 'prefs':
$this->getPrefs();
foreach ($this->customFields as $customField) {
if (is_numeric($customField)) {
$css[] = ('div#prefs-custom_' . $customField . '_set label:after{display:block;font-size:x-small;font-style:italic;content:"' . $this->t('prefs_used_field') . '";}');
}
}
break;
}
if (!empty($css)) {
echo tag(implode($css),
'style',
['type' => 'text/css']);
}
if (!empty($js)) {
echo tag(implode($js),
'script',
['type' => 'text/javascript']);
}
}
/**
* Lifecycle event handler
*
* @param string $event Textpattern event
* @param string $step Textpattern step (action)
* @return string Success/failure message
*/
public function eventLifecycle($event, $step) : string
{
assert($event === ('plugin_lifecycle.' . $this->event));
$result = '';
switch ($step) {
case 'installed':
$result = $this->t('installed');
break;
case 'deleted':
// Wipe preferences for this module to clean up the database
remove_pref(null, $this->event);
break;
case 'disabled':
case 'downgraded':
case 'enabled':
case 'upgraded':
default:
}
return $result;
}
/**
* Plugin aliases panel event handler
*
* @param string $event Textpattern event
* @param string $step Textpattern step (action)
*/
public function eventPanelAliases($event, $step) : void
{
assert($event === $this->event);
$availableSteps = [
'list' => false,
'multiedit' => true,
'ais_url_alias_change_pageby' => true
];
switch (bouncer($step, $availableSteps) ? $step : null) {
case 'ais_url_alias_change_pageby':
$this->panelAliasesListPageby();
break;
case 'multiedit':
$this->multieditAliases();
break;
case 'list':
default:
$this->panelAliasesList();
}
}
/**
* Plugin options panel event handler
*
* @param string $event Textpattern event
* @param string $step Textpattern step (action)
*/
public function eventPanelPrefs($event, $step) : void
{
assert($event === ('plugin_prefs.' . $this->event));
$availableSteps = [
'list' => false,
'save' => true
];
switch (bouncer($step, $availableSteps) ? $step : null) {
case 'save':
$this->panelPrefsSave();
break;
case 'list':
default:
$this->panelPrefsList();
}
}
/**
* Get plugin preferences
*/
private function getPrefs() : void
{
if (!isset($this->customFields)) {
$customFields = get_pref(self::PREF_NAME_CUSTOM_FIELDS, self::PREF_DEFAULT_CUSTOM_FIELDS);
if ($customFields != '') {
$this->customFields = explode(',', $customFields);
} else {
$this->customFields = array();
}
}
if (!isset($this->redirectPermanent)) {
$redirectPermanent = get_pref(self::PREF_NAME_REDIRECT_PERMANENT, self::PREF_DEFAULT_REDIRECT_PERMANENT);
$this->redirectPermanent = ((is_numeric($redirectPermanent) && ($redirectPermanent == 1)) ? true : false);
}
if (!isset($this->showArticleCustomFieldValidity)) {
$showArticleCustomFieldValidity = get_pref(self::PREF_NAME_SHOW_ARTICLE_CUSTOM_FIELD_VALIDITY, self::PREF_DEFAULT_SHOW_ARTICLE_CUSTOM_FIELD_VALIDITY);
$this->showArticleCustomFieldValidity = ((is_numeric($showArticleCustomFieldValidity) && ($showArticleCustomFieldValidity == 1)) ? true : false);
}
}
/**
* Handle a public side event/callback
*
* @param string $event
*/
static public function handlePublicEvent($event) : void
{
// Sanity check: We only handle the "textpattern" (= rendering) callback.
if ($event == 'pretext_end') {
$handler = new ais_url_alias();
$handler->handleRender();
}
}
/**
* Handle a public side rendering event ("textpattern" callback)
*/
private function handleRender() : void
{
global $pretext;
$requestURI = $pretext['request_uri'];
$queryString = $pretext['qs'];
// Sanity check - we should have the request URI at this point
if (isset($requestURI) &&
($requestURI != '')) {
// Clean the request URI
$requestURI = ltrim(explode('?', $requestURI)[0], '/');
// Build the where clause
$where = $this->sqlWhere($requestURI);
// If there's no where clause, that means the plugin is probably not configured yet (nothing to do)
if ($where != '') {
// We only want exactly one live article
$where .= ' AND (status = ' . STATUS_LIVE . ') LIMIT 1';
// Try to find an article ID with this alternative URI
$id = safe_field('ID', 'textpattern', $where);
if (isset($id)) {
// Fetch the official permlink for that article ID
$newURL = permlinkurl_id($id);
// If we have a URL, let's bounce.
if (isset($newURL) &&
(strlen($newURL) > 0)) {
if (strlen($queryString) > 0) {
$this->bounce($newURL . '?' . $queryString);
} else {
$this->bounce($newURL);
}
}
}
}
}
}
/**
* Initialise for admin
*/
private function initAdmin() : void
{
// Prepare privileges
add_privs(('plugin_prefs.' . $this->event), '1,2'); // Plugin preferences -> Publishers / Managing editors only
add_privs($this->event, '1,2,3,4'); // URL aliases panel -> Publishers / Managing editors / Copy editor / Staff writer
// Register panels
if ($this->canCTE()) {
register_tab('content', $this->event, $this->t('url_aliases'));
}
// Register callbacks
register_callback(array($this, 'eventArticleValidate'), 'article_ui', 'validate_publish');
register_callback(array($this, 'eventArticleValidate'), 'article_ui', 'validate_save');
register_callback(array($this, 'eventDiag'), 'diag');
register_callback(array($this, 'eventHead'), 'admin_side', 'head_end');
register_callback(array($this, 'eventLifecycle'), ('plugin_lifecycle.' . $this->event));
register_callback(array($this, 'eventPanelAliases'), $this->event);
register_callback(array($this, 'eventPanelPrefs'), ('plugin_prefs.' . $this->event));
}
/**
* Perform a multi-edit action on the aliases list
*/
function multieditAliases()
{
$ok = true;
$message = '';
$selected = ps('selected');
if (!$selected || !is_array($selected)) {
$this->panelAliasesList();
return;
}
// Clean-up selection - should be a list of key/value pairs (article ID + custom field number)
$selected = array_map(fn($v) => array_map('assert_int', explode('_', $v)),
$selected);
$selected = array_filter($selected);
// Fetch valid article IDs
if (!empty($selected)) {
// Fetch the multiedit method
$method = ps('edit_method');
switch ($method) {
// Remove alias URLs
case 'delete':
// Determine what custom fields are impacted
$customFields = array_unique(array_column($selected, 1));
$updateCount = 0;
// Wipe custom field values for selected articles, per custom field
$sql = '';
foreach ($customFields as $customField) {
// Find out which article IDs are marked for this custom field
$articleIDs = array_unique(array_column(array_filter($selected, fn($v) => ($v[1] === $customField)), 0));
$ok = (safe_update('textpattern',
('custom_' . $customField . ' = \'\''),
('(ID in (' . join(',', $articleIDs) . '))')) &&
$ok);
if ($ok) {
$updateCount += count($articleIDs);
}
}
$message = $this->t(($ok ? 'bulk_remove_success' : 'bulk_remove_failed'),
['{count}' => $updateCount]);
break;
default:
}
}
// Reload the list
$this->panelAliasesList($message);
}
/**
* Generate the multiedit form for the URL aliases list page
*
* @param int $page Page number
* @param string $sort Column sorted by
* @param string $dir Sorting direction
* @param string $crit Search criterion
* @param string $search_method Search method
* @return string The generated multiedit HTML
*/
function multieditAliasesForm(int $page, string $sort, string $dir, string $crit, string $searchMethod) : string
{
$methods = [];
$methods['delete'] = $this->t('bulk_remove_alias');
return tag(multi_edit($methods, $this->event, 'multiedit', $page, $sort, $dir, $crit, $searchMethod),
'div');
}
/**
* Create a new instance for admin mode
*/
static public function newAdmin() : void
{
$handler = new ais_url_alias();
$handler->initAdmin();
}
/**
* URL aliases panel - list mode
*
* @param $message Message to output
*/
private function panelAliasesList($message = '') : void
{
$heading = $this->t('url_aliases');
pagetop($heading, $message);
// Table fields
$tableFields = ['ID', 'Title', 'C'];
// Get page query values
extract(gpsa(['page', 'sort', 'dir', 'crit', 'search_method']));
// Prepare the CTE we'll be using to collapse all configured custom fields together
$cteName = rtrim(base64_encode(md5(microtime())), "=");
$sqlCTE = $this->sqlCTE($cteName);
// Sort field as defined, by preference, or default
if (empty($sort)) {
$sort = get_pref(self::PREF_NAME_ALIASES_SORT_COL, 'C');
} else {
if (!in_array($sort, $tableFields)) {
$sort = self::PREF_DEFAULT_ALIASES_SORT_COL;
}
set_pref(self::PREF_NAME_ALIASES_SORT_COL, $sort, $this->event, PREF_HIDDEN, '', 0, PREF_PRIVATE);
}
// Sort direction by preference or by default
if (empty($dir)) {
$dir = get_pref(self::PREF_NAME_ALIASES_SORT_DIR, 'DESC');
} else {
$dir = ($dir === 'DESC' ? 'DESC' : 'ASC');
set_pref(self::PREF_NAME_ALIASES_SORT_DIR, $dir, $this->event, PREF_HIDDEN, '', 0, PREF_PRIVATE);
}
// Toggle direction is the opposite of the current direction :)
$toggleDir = (($dir === 'DESC') ? 'ASC' : 'DESC');
// Build SQL sort string
switch ($sort) {
// Article ID from CTE
case 'ID':
$sqlSort = "A.ID $dir";
break;
// Alias from CTE
case 'C':
$sqlSort = "A.$sort $dir, A.ID DESC";
break;
// Fields from article table
case 'Title':
default:
$sqlSort = "B.$sort $dir, A.ID DESC";
}
// Build filtering
$search = new \Textpattern\Search\Filter($this->event, [
'ID' => [
'column' => 'A.ID',
'label' => gTxt('article'),
'type' => 'integer'
],
'Title' => [
'column' => 'B.Title',
'label' => gTxt('title')
],
'C' => [
'column' => 'A.C',
'label' => $this->t('url_alias')
]
]);
list($sqlCriteria, $crit, $searchMethod) = $search->getFilter(['ID' => ['can_list' => true]]);
// Build SQL 'from' chunk
$sqlFrom = ("$cteName AS A INNER JOIN " . safe_pfx_j('textpattern') . ' AS B ON (A.ID = B.ID)');
// Calculate total
if ($crit) {
// Include the full join since the criteria may include fields from any table
$total = getThing("$sqlCTE SELECT COUNT(*) FROM $sqlFrom" .
(empty($crit) ? '' : " WHERE $sqlCriteria"));
} else {
// Simpler version if there's no criteria, without the join or the criteria
$total = getThing("$sqlCTE SELECT COUNT(*) FROM $cteName");
}
// Build the search block
$searchRenderOptions = ['placeholder' => 'ais_url_alias_search_aliases'];
$searchBlock = n.tag($search->renderForm('list',
$searchRenderOptions),
'div',
['class' => 'txp-layout-4col-3span',
'id' => ($this->event . '_control')]);
// Build the paginator
$paginator = new \Textpattern\Admin\Paginator($this->event);
$limit = $paginator->getLimit();
list($page, $offset, $numPages) = pager($total, $limit, $page);
// Build the content block
$contentBlock = '';
if ($total <= 0) {
$contentBlock .= graf((span(null, ['class' => 'ui-icon ui-icon-info']) .
' ' .
(empty($crit) ? $this->t('no_aliases_configured') : gTxt('no_results_found'))),
['class' => 'alert-block information']);
} else {
// Fetch the rows to display
$resultSet = safe_query("$sqlCTE SELECT A.*, B.Title FROM $sqlFrom WHERE $sqlCriteria ORDER BY $sqlSort LIMIT $offset, $limit");
// Ensure we got something back
if ($resultSet &&
(numRows($resultSet) > 0)) {
// Start the multiedit form and the table header
$contentBlock .= (n.tag_start('form', ['class' => 'multi_edit_form',
'id' => 'ais_url_alias_aliases_form',
'name' => 'longform',
'method' => 'post',
'action' => 'index.php']) .
n.tag_start('div', ['class' => 'txp-listtables',
'tabindex' => 0,
'aria-label' => gTxt('list')]) .
n.tag_start('table', ['class' => 'txp-list']) .
n.tag_start('thead') .
tr(hCell(fInput('checkbox', 'select_all', 0, '', '', '', '', '', 'select_all'),
'',
(' class="txp-list-col-multi-edit" scope="col" title="' . gTxt('toggle_all_selected') . '"')) .
column_head('article', 'ID', $this->event, true, $toggleDir, $crit, $searchMethod,
((($sort === 'ID') ? "$dir " : '') . 'txp-list-col-id')) .
column_head('title', 'Title', $this->event, true, $toggleDir, $crit, $searchMethod,
((($sort === 'Title') ? "$dir " : '') . 'txp-list-col-title')) .
column_head('ais_url_alias_url_alias', 'C', $this->event, true, $toggleDir, $crit, $searchMethod,
((($sort === 'C') ? $dir : '')))) .
n.tag_end('thead') .
n.tag_start('tbody'));
// Loop through row
while ($row = nextRow($resultSet)) {
// Edit URL links back to the article where the URL alias can be edited
$urlEditArticle = ['event' => 'article', 'step' => 'edit', 'ID' => $row['ID']];
// Add this row to a content block
$contentBlock .= (tr(td(fInput('checkbox', 'selected[]', ($row['ID'] . '_' . $row['N']),
'',
'txp-list-col-multi-edit') .
hCell(href($row['ID'], $urlEditArticle, (' title="' . gTxt('edit') . '"')),
'',
' class="txp-list-col-id" scope="row"') .
td(href(txpspecialchars($row['Title']), $urlEditArticle, (' title="' . gTxt('edit') . '"')),
'',
'txp-list-col-title') .
td($row['C']))));
}
// Finish the table and the content block
$contentBlock .= (n.tag_end('tbody') .
n.tag_end('table') .
n.tag_end('div') .
$this->multieditAliasesForm($page, $sort, $dir, $crit, $searchMethod) .
tInput() .
n.tag_end('form'));
}
}
// Build the pagination block
$pageBlock = ($paginator->render() .
nav_form($this->event, $page, $numPages, $sort, $dir, $crit, $searchMethod, $total, $limit));
// Render out the table
$table = new \Textpattern\Admin\Table($this->event);
echo $table->render(compact('heading', 'total', 'crit'), $searchBlock, null, $contentBlock, $pageBlock);
}
/**
* Change URL aliases pagination
*
* @param $message Message to output
*/
private function panelAliasesListPageby() : void
{
\Txp::get('\Textpattern\Admin\Paginator')->change();
$this->panelAliasesList();
}
/**
* Plugin preferences panel - list mode
*
* @param $message Message to output
*/
private function panelPrefsList($message = '') : void
{
$heading = $this->t('prefs_title');
pagetop($heading, $message);
$pageContent = '';
// Build the page title
$titleContent =
tag(hed($heading, 1, ['class' => 'txp-heading']),
'div',
['class' => 'txp-layout-1col']);
// Fetch/default preferences
$this->getPrefs();
// Behaviour fields
$formContentBehaviour =
(inputLabel(self::PREF_NAME_REDIRECT_PERMANENT,
selectInput(self::PREF_NAME_REDIRECT_PERMANENT,
['0' => $this->t('pref_redirect_type_temporary'),
'1' => $this->t('pref_redirect_type_permanent')],
($this->redirectPermanent ? '1' : '0')),
'ais_url_alias_pref_redirect_type',
'ais_url_alias_help_pref_redirect_type') .
inputLabel(self::PREF_NAME_SHOW_ARTICLE_CUSTOM_FIELD_VALIDITY,
onoffRadio(self::PREF_NAME_SHOW_ARTICLE_CUSTOM_FIELD_VALIDITY,
($this->showArticleCustomFieldValidity ? '1' : '0')),
'ais_url_alias_pref_show_article_custom_field_validity',
'ais_url_alias_help_pref_show_article_custom_field_validity'));
// Custom field checkbox fields
$formContentCustom = '';
for ($i = 1; $i <= self::MAX_CUSTOM_FIELD_NUM; ++$i) {
$fieldName = (self::PREF_NAME_CUSTOM_FIELDS . '_' . $i);
$formContentCustom .=
inputLabel($fieldName,
checkbox($fieldName, 1, in_array($i, $this->customFields)),
('ais_url_alias_pref_custom_' . $i));
}
// Build behaviour group
$formTitleBehaviour = $this->t('prefs_title_behaviour');
$formIDBehaviour = 'ais_url_alias_pref_group_behaviour';
$formTabBehaviour =
tag(href($formTitleBehaviour,
('#' . $formIDBehaviour),
['data-txp-pane' => $formIDBehaviour,
'data-txp-token' => md5($formIDBehaviour . form_token() . get_pref('blog_uid'))]),
'li');
$formGroupBehaviour =
tag((hed($formTitleBehaviour, 2, ['id' => 'ais_url_alias_pref_group_behaviour-label']) .
$formContentBehaviour),
'section',
['class' => 'txp-tabs-vertical-group',
'id' => $formIDBehaviour,
'aria-labelledby' => 'ais_url_alias_pref_group_behaviour-label']);
// Build custom fields group
$formTitleCustom = $this->t('prefs_title_custom');
$formIDCustom = 'ais_url_alias_pref_group_custom';