-
Notifications
You must be signed in to change notification settings - Fork 8
/
tru_tags.php
1402 lines (1171 loc) · 47.5 KB
/
tru_tags.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
$plugin['allow_html_help'] = 0;
$plugin['version'] = 'X.X';
$plugin['author'] = 'Nathan Arthur';
$plugin['author_uri'] = 'http://www.rainskit.com/';
$plugin['description'] = 'Article tagging';
// Plugin types:
// 0 = regular plugin; loaded on the public web side only
// 1 = admin plugin; loaded on both the public and admin side
// 2 = library; loaded only when include_plugin() or require_plugin() is called
$plugin['type'] = 1;
if (!defined('txpinterface'))
@include_once('zem_tpl.php');
if (0) {
?>
# --- BEGIN PLUGIN HELP ---
To learn more about tru_tags, check out the "introductory article":http://www.rainskit.com/blog/493/trutags-a-tagging-plugin-for-textpattern, "releases page":http://www.rainskit.com/reference/537/tru_tags-releases, "feature list":http://www.rainskit.com/reference/495/trutags-feature-list, "roadmap":http://www.rainskit.com/reference/554/tru_tags-roadmap, and "usage instructions":http://www.rainskit.com/reference/497/trutags-usage-instructions.
You can also find the source code at "github.com/truist/tru-tags":https://github.com/truist/tru-tags.
I've taken the detailed help out of the plugin; my apologies. It was too big and too difficult to keep maintaining on my site and in the plugin. If, my site is ever down, however, the source HTML of the usage instructions is available from the "github repo":https://github.com/truist/tru-tags/blob/master/tru_tags-docs.html
# --- END PLUGIN HELP ---
<?php
}
# --- BEGIN PLUGIN CODE ---
# Copyright 2017 Nathan Arthur
# Released under the GNU Public License, see http://www.opensource.org/licenses/gpl-license.php for details
#
# This work was originally inspired by ran_tags by Ran Aroussi, originally found at http://aroussi.com/article/45/tagging-textpattern
# Javascript bug fixes were provided by the_ghost - http://victorus.net
# Javascript code for the tag auto-complete feature was provided by Jim Biancolo - http://www.biancolo.com/
# Fixes for Textpattern 4.6 provided by:
# - Rimas Kudelis; https://github.com/rimas-kudelis
# - jools-r; https://github.com/jools-r
# - Simon Finch; https://github.com/spiffin
### CONFIGURATION ###
#####################
# TURN BACK! Configuration is no longer handled by editing the plugin.
# Check out the 'Extensions' tab in the Textpattern admin :)
# Changing these won't do any good. They're just here as a convenience for development.
define('TRU_TAGS_FIELD', 'Keywords');
define('ENCODING', 'utf-8');
define('CLEAN_URLS', 'clean_urls');
define('TAG_SECTION', 'tag_section');
define('PARM_NAME', 'parm');
define('TAGS_IN_FEED_CATEGORIES', 'tags_in_feed_categories');
define('TAGS_IN_FEED_BODY', 'tags_in_feed_body');
define('TAGS_IN_WRITE_TAB', 'tags_in_write_tab');
define('AUTOCOMPLETE_IN_WRITE_TAB', 'autocomplete_in_write_tab');
define('UTF_8_CASE', 'utf_8_case');
global $tru_tags_prefs;
global $tru_tags_query_cache;
$tru_tags_prefs = tru_tags_load_prefs();
$tru_tags_query_cache = array();
### TAG REGISTRATION ###
########################
Txp::get('\Textpattern\Tag\Registry')
->register('tru_tags_handler')
->register('tru_tags_if_has_tags')
->register('tru_tags_from_article')
->register('tru_tags_cloud')
->register('tru_tags_list')
->register('tru_tags_if_tag_search')
->register('tru_tags_tag_parameter')
->register('tru_tags_search_result_excerpt')
->register('tru_tags_search_parameter')
->register('tru_tags_related_tags_from_search')
->register('tru_tags_archive')
->register('tru_tags_current_archive_tag');
### PRIMARY TAG FUNCTIONS ###
#############################
function tru_tags_handler($atts) {
$tag_parameter = tru_tags_tag_parameter(array(), false);
if (!empty($tag_parameter)) {
if (tru_tags_redirect_if_needed($tag_parameter)) {
return '';
}
$clean_atts = tru_tags_fixup_query_atts($atts, $tag_parameter);
$result = doArticles($clean_atts, true); #function in TXP code
if (trim($result) == '') {
if (isset($atts['noarticles'])) {
tru_tags_redirect($atts['noarticles'], true);
} else if (isset($atts['404redirect']) && !$atts['404redirect']) {
return $result;
} else {
txp_die(gTxt('404_not_found'), '404');
}
} else {
return $result;
}
} else {
return tru_tags_cloud($atts);
}
}
function tru_tags_archive($atts) {
global $tru_tags_current_archive_tag;
$tags = array_unique(tru_tags_cloud_query(tru_tags_get_standard_cloud_atts($atts, false, false)));
natcasesort($tags);
foreach ($tags as $tag) {
$tru_tags_current_archive_tag = $tag;
$clean_atts = tru_tags_fixup_query_atts($atts, $tag);
$results[] = doArticles($clean_atts, true); #function in TXP code
}
return join(' ', $results);
}
function tru_tags_current_archive_tag($atts) {
global $tru_tags_current_archive_tag;
extract(lAtts(array('link' => '0'), $atts, 0));
if ($link) {
return '<a href="' . tru_tags_linkify_tag($tru_tags_current_archive_tag) . '">' . $tru_tags_current_archive_tag . '</a>';
} else {
return $tru_tags_current_archive_tag;
}
}
function tru_tags_cloud($atts) {
return tru_tags_list(tru_tags_get_standard_cloud_atts($atts, false, false));
}
function tru_tags_list($atts) {
$atts = tru_tags_get_standard_cloud_atts($atts, true, false);
$all_tags = tru_tags_cloud_query($atts);
return tru_tags_render_cloud($atts, $all_tags, $all_tags);
}
function tru_tags_from_article($atts) {
global $thisarticle;
extract($thisarticle);
$all_tags = tru_tags_get_tags_for_article($thisid);
$atts = tru_tags_get_standard_cloud_atts($atts, false, true);
$all_tags_for_weight = $all_tags;
if ($atts['useoverallcounts']) {
$all_tags_for_weight = tru_tags_cloud_query($atts);
}
return tru_tags_render_cloud($atts, $all_tags, $all_tags_for_weight);
}
function tru_tags_if_has_tags($atts, $thing) {
global $thisarticle;
extract($thisarticle);
$tags_field = TRU_TAGS_FIELD;
$rs = safe_row($tags_field, "textpattern", "ID='$thisid' AND $tags_field <> ''");
return parse(EvalElse($thing, $rs));
}
function tru_tags_if_tag_search($atts, $thing) {
extract(lAtts(array('tag' => ''), $atts, 0));
$tag_parameter = tru_tags_tag_parameter(array('striphyphens' => 1), false);
$condition = (!empty($tag_parameter)) ? true : false;
if ($condition && !empty($tag)) {
$condition = ($tag_parameter == $tag);
}
return parse(EvalElse($thing, $condition));
}
function tru_tags_tag_parameter($atts, $safehtml = true) {
global $tru_tags_prefs;
extract(lAtts(array('striphyphens' => '0', 'urlencode' => 0), $atts, 0));
$parm = urldecode(strip_tags(gps($tru_tags_prefs[PARM_NAME]->value)));
if ('lookup' == $striphyphens) {
$atts = tru_tags_get_standard_cloud_atts(array(), false, false);
$tag_list = array_unique(tru_tags_cloud_query($atts));
foreach ($tag_list as $cloud_tag) {
if ($parm == str_replace(' ', '-', $cloud_tag)) {
$parm = $cloud_tag;
break;
}
}
} else if ($striphyphens) {
$parm = str_replace('-', ' ', $parm);
}
if ($urlencode) {
$parm = urlencode($parm);
} else if ($safehtml) {
$parm = htmlspecialchars($parm);
}
return $parm;
}
function tru_tags_search_result_excerpt($atts) {
global $pretext;
$tag_parameter = tru_tags_tag_parameter(array(), false);
if (trim($tag_parameter) != '') {
$q = $pretext['q'];
$pretext['q'] = $tag_parameter;
$result = search_result_excerpt($atts);
$pretext['q'] = $q;
} else {
$result = search_result_excerpt($atts);
}
return $result;
}
function tru_tags_search_parameter() {
trigger_error(gTxt('deprecated_tag'), E_USER_NOTICE);
return strip_tags(gps('q'));
}
function tru_tags_related_tags_from_search($atts) {
$tag_parameter = tru_tags_tag_parameter(array(), false);
extract(lAtts(array('tag_parameter' => $tag_parameter), $atts, 0));
if (!empty($tag_parameter)) {
$tags_field = TRU_TAGS_FIELD;
$all_tags = array();
$query_atts = tru_tags_fixup_query_atts($atts, $tag_parameter);
$rs = tru_tags_redo_article_search($query_atts);
if ($rs) {
while ($a = nextRow($rs)) {
$article_tags = array();
if (isset($a[$tags_field])) {
$article_tags = explode(",", trim(tru_tags_strtolower($a[$tags_field])));
}
# faster implementation of array_merge(), thanks to whocarez
# (http://forum.textpattern.com/viewtopic.php?pid=238373#p238373)
foreach(tru_tags_trim_tags($article_tags) as $i) {$all_tags[] = $i;}
}
}
$alt_tag_parameter = str_replace('-', ' ', $tag_parameter);
foreach ($all_tags as $key => $tag) {
if ($tag == $tag_parameter || $tag == $alt_tag_parameter) {
unset($all_tags[$key]);
}
}
$cloud_atts = tru_tags_get_standard_cloud_atts($atts, false, false);
$all_tags_for_weight = $all_tags;
if ($cloud_atts['useoverallcounts']) {
$all_tags_for_weight = tru_tags_cloud_query($cloud_atts);
}
return tru_tags_render_cloud($cloud_atts, $all_tags, $all_tags_for_weight);
} else {
return '';
}
}
### CLOUD SUPPORT FUNCTIONS ###
###############################
function tru_tags_get_standard_cloud_atts($atts, $isList, $isArticle, $showAll=false) {
return lAtts(array('wraptag' => ($isList ? 'ul' : ''),
'break' => ($isList ? 'li' : ', '),
'class' => '',
'breakclass' => '',
'section' => '',
'minpercent' => '100',
'maxpercent' => ($isList || $isArticle ? '100' : '200'),
'showcounts' => '',
'countwrapchars' => '[]',
'usereltag' => ($isArticle ? '1' : ''),
'generatelinks' => '1',
'mintagcount' => '0',
'maxtagcount' => '1000',
'setsizes' => ($isArticle ? '0' : '1'),
'usenofollow' => '',
'sort' => 'alpha',
'useoverallcounts' => '',
'setclasses' => ($isArticle ? '0' : '1'),
'title' => '',
'listlimit' => '',
'keep' => 'largest',
'cutoff' => 'chunk',
'texttransform' => 'none',
'linkpath' => '',
'linkpathtail' => '',
'filtersearch' => ($showAll ? 0 : '1'),
'excludesection'=> '',
'activeclass' => 'tagActive',
'time' => ($showAll ? 'any' : 'past')
),$atts, 0);
}
function tru_tags_cloud_query($atts) {
global $tru_tags_query_cache;
extract($atts);
$section_clause = '';
if ($section <> '') {
$keys = explode(',', $section);
foreach ($keys as $key) {
$keyparts[] = " Section = '" . trim($key) . "'";
}
$section_clause = " AND (" . join(' or ', $keyparts) . ")";
}
$tags_field = TRU_TAGS_FIELD;
include_once txpath.'/publish/search.php';
$filter = tru_tags_filter_sections($excludesection);
$filter .= ($filtersearch ? filterSearch() : '');
// Using SQL caching capabilities. Txp 4.6+
if (function_exists('now')) {
$where_posted = now('posted');
$where_expired = " AND (".now('expires')." <= Expires OR Expires IS NULL)";
} else {
$where_posted = "now()";
$where_expired = " AND (now() <= Expires OR Expires = ".NULLDATETIME.")";
}
switch ($time) {
case 'any':
$time = ""; break;
case 'future':
$time = " AND Posted > ".$where_posted; break;
default:
$time = " AND Posted <= ".$where_posted;
}
global $prefs;
extract($prefs);
if (!$publish_expired_articles) {
$time .= $where_expired;
}
$all_tags = array();
$query_where = "$tags_field <> ''" . $section_clause . $filter . " and Status >= '4'" . $time;
if (array_key_exists($query_where, $tru_tags_query_cache)) {
$rs = $tru_tags_query_cache[$query_where];
} else {
$rs = safe_rows("$tags_field", "textpattern", $query_where);
$tru_tags_query_cache[$query_where] = $rs;
}
foreach ($rs as $row) {
$temp_array = array();
if (isset($row[$tags_field])) {
$temp_array = explode(",", trim(tru_tags_strtolower($row[$tags_field])));
}
# faster implementation of array_merge(), thanks to whocarez
# (http://forum.textpattern.com/viewtopic.php?pid=238373#p238373)
foreach(tru_tags_trim_tags($temp_array) as $i) {$all_tags[] = $i;}
}
return $all_tags;
}
function tru_tags_filter_sections($excludesection) {
$sections = explode(',', $excludesection);
$filters = array();
foreach ($sections as $section) {
$filters[] = "and Section != '".doSlash($section)."'";
}
return join(' ', $filters);
}
function tru_tags_render_cloud($atts, $all_tags, $all_tags_for_weight) {
global $tru_tags_prefs;
extract($atts);
$tags_weight = array_count_values($all_tags_for_weight);
foreach ($tags_weight as $tag => $weight) {
if (!in_array($tag, $all_tags)
|| $tags_weight[$tag] < $mintagcount
|| $tags_weight[$tag] > $maxtagcount) {
unset($tags_weight[$tag]);
}
}
$sort_by_count = (strpos($sort, 'count') !== false);
$sort_ascending = (strpos($sort, 'asc') !== false);
$tags_weight = tru_tags_sort_tags($tags_weight, $sort_by_count, $sort_ascending);
if ($listlimit > 0 && $listlimit < count($tags_weight)) {
$resorted_tags = array();
if ($keep == 'largest') {
$resorted_tags = array_keys(tru_tags_sort_tags($tags_weight, true, false));
} else {
if ($keep == 'random') {
foreach ($tags_weight as $tag => $weight) {
$resorted_tags[$tag] = rand(0, $weight);
}
$resorted_tags = array_keys(tru_tags_sort_tags($resorted_tags, true, false));
} else if ($keep == 'alpha') {
$resorted_tags = array_keys($tags_weight);
natcasesort($resorted_tags);
}
$cutoff = 'exact';
}
$last_good_index = $listlimit - 1;
if ($cutoff == 'chunk') { //alternative is 'exact'
$last_weight = -1;
for ($i = 0; $i < $listlimit + 1; $i++) {
$new_weight = $tags_weight[$resorted_tags[$i]];
if ($new_weight != $last_weight) {
$last_good_index = $i - 1;
$last_weight = $new_weight;
}
}
if ($last_good_index < 0) {
$last_good_index = $listlimit - 1;
}
}
$resorted_tags = array_chunk($resorted_tags, $last_good_index + 1);
$resorted_tags = $resorted_tags[0];
foreach ($tags_weight as $tag => $weight) {
if (!in_array($tag, $resorted_tags)) {
unset($tags_weight[$tag]);
}
}
}
if ($generatelinks) {
if ($linkpath) {
$urlprefix = $linkpath;
$urlsuffix = $linkpathtail;
} else {
if (tru_tags_clean_urls()) {
$urlprefix = hu . $tru_tags_prefs[TAG_SECTION]->value . '/';
} else {
$urlprefix = hu . '?s=' . $tru_tags_prefs[TAG_SECTION]->value . '&' . $tru_tags_prefs[PARM_NAME]->value . '=';
}
$urlsuffix = (tru_tags_clean_urls() ? '/' : '');
}
if ($usereltag) {
if ($usenofollow) {
$urlsuffix .= '" rel="tag nofollow';
} else {
$urlsuffix .= '" rel="tag';
}
} else if ($usenofollow) {
$urlsuffix .= '" rel="nofollow';
}
}
if (count($tags_weight) > 0) {
$max = max($tags_weight);
$min = min($tags_weight);
} else {
$max = $min = 0;
}
$stepvalue = ($max == $min) ? 0 : ($maxpercent - $minpercent) / ($max - $min);
$tags_html = array();
$tag_search_tag = tru_tags_tag_parameter(array('striphyphens' => 'lookup'));
$tag_search_tag = function_exists("htmlspecialchars_decode") ? htmlspecialchars_decode($tag_search_tag) : html_entity_decode($tag_search_tag);
foreach ($tags_weight as $tag => $weight) {
$tag_weight = floor($minpercent + ($weight - $min) * $stepvalue);
$style = '';
if ($setsizes)
$style = ' style="font-size: ' . $tag_weight . '%;"';
$tag_class = '';
if ($setclasses) {
$tag_class = ' class="';
if ($weight == $min) {
$tag_class .= "tagSizeSmallest";
} else if ($weight == $max) {
$tag_class .= "tagSizeLargest";
} else {
$tag_class .= "tagSizeMedium";
}
$tag_class .= ' tagSize' . ($weight + 1 - $min);
if ($tag == $tag_search_tag) {
$tag_class .= ' ' . $activeclass;
}
$tag_class .= '"';
}
//adapted from code by gdtroiano, see http://forum.textpattern.com/viewtopic.php?pid=102875#p102875
$titlecount = '';
if ($title)
$titlecount = ' title="' . $title . '"';
$displaycount= '';
$count = $countwrapchars[0] . $weight . $countwrapchars[1];
if ($showcounts == 'title' || $showcounts == 'both')
$titlecount = ' title="' . $title . $count . '"';
if ($showcounts && $showcounts != 'title')
$displaycount = ' ' . $count;
if ($texttransform == 'capitalize') {
$tag = tru_tags_ucwords($tag);
} else if ($texttransform == 'uppercase') {
$tag = tru_tags_strtoupper($tag);
} else if ($texttransform == 'lowercase') {
$tag = tru_tags_strtolower($tag);
} else if ($texttransform == 'capfirst') {
$tag = tru_tags_ucfirst($tag);
}
if ($generatelinks) {
$wholeurl = '"' . $urlprefix . urlencode($tag) . $urlsuffix . '"';
$tags_html[] = '<a href=' . $wholeurl . $tag_class . $style . $titlecount . '>' . htmlspecialchars($tag) . '</a>' . $displaycount;
} else if ($tag_class || $style || $titlecount) {
$tags_html[] = '<span' . $tag_class . $style . $titlecount . '>' . htmlspecialchars($tag) . '</span>' . $displaycount;
} else {
$tags_html[] = htmlspecialchars($tag) . $displaycount;
}
}
return tru_tags_do_wrap($tags_html, $wraptag, $break, $class, $breakclass);
}
### CLEAN URL FUNCTIONS ###
###########################
if (tru_tags_clean_urls()) {
register_callback('tru_tags_clean_url_handler', 'pretext');
}
function tru_tags_clean_url_handler($event, $step) {
global $tru_tags_prefs;
$subpath = preg_replace("/https?:\/\/.*(\/.*)/Ui","$1",hu);
$regsafesubpath = preg_quote($subpath, '/');
$req = preg_replace("/^$regsafesubpath/i",'/',$_SERVER['REQUEST_URI']);
$qs = strpos($req, '?');
$qatts = ($qs ? '&'.substr($req, $qs + 1) : '');
if ($qs) $req = substr($req, 0, $qs);
$parts = array_values(array_filter(explode('/', $req)));
if (count($parts) == 2 && $parts[0] == $tru_tags_prefs[TAG_SECTION]->value) {
$tag = $parts[1];
$_SERVER['QUERY_STRING'] = $tru_tags_prefs[PARM_NAME]->value . '=' . $tag . $qatts;
$_SERVER['REQUEST_URI'] = $subpath . $tru_tags_prefs[TAG_SECTION]->value . '/?' . $_SERVER['QUERY_STRING'];
if (count($_POST) > 0) {
$_POST['section'] = $tru_tags_prefs[TAG_SECTION]->value;
$_POST[$tru_tags_prefs[PARM_NAME]->value] = $tag;
} else {
$_GET['section'] = $tru_tags_prefs[TAG_SECTION]->value;
$_GET[$tru_tags_prefs[PARM_NAME]->value] = $tag;
}
}
}
function tru_tags_clean_urls() {
global $tru_tags_prefs;
return ('clean' == $tru_tags_prefs[CLEAN_URLS]->value);
}
### ADMIN SIDE FUNCTIONS ###
############################
if (@txpinterface == 'admin') {
add_privs('tru_tags', '1,2');
register_tab('extensions', 'tru_tags', 'tru_tags');
register_callback('tru_tags_admin_tab', 'tru_tags');
if ($tru_tags_prefs[TAGS_IN_WRITE_TAB]->value || $tru_tags_prefs[AUTOCOMPLETE_IN_WRITE_TAB]->value) {
register_callback('tru_tags_admin_write_tab_handler', 'article_ui', 'keywords');
}
}
function tru_tags_admin_tab($event, $step) {
require_privs('tru_tags');
$results = tru_tags_admin_tab_handle_input();
$atts = tru_tags_get_standard_cloud_atts(array(), false, false, true);
$all_tags = tru_tags_cloud_query($atts);
$cloud = tru_tags_render_cloud($atts, $all_tags, $all_tags);
$redirects = tru_tags_load_redirects();
tru_tags_admin_tab_render_page($results, $cloud, $redirects);
}
function tru_tags_admin_tab_render_page($results, $cloud, $redirects) {
global $event;
pagetop('tru_tags', '');
include_once(txpath . '/include/txp_prefs.php');
global $tru_tags_prefs;
echo startTable('layout', '', '', '10px').'<tr><td style="border-right:2px solid gray">'. # I know, I know...
startTable('layout', '', '', '', '10px').'<tr><td style="border-bottom:2px solid gray">'.
startTable('list', '', '', '', '300px').
tr(hCell(gTxt('Current tags'))).
tr(td($cloud)).
endTable().
'</td></tr><tr><td>'.
startTable('list', '', '', '', '300px').
tr(hCell(gTxt('tru_tags Reference'))).
tr(td('<a href="http://www.rainskit.com/reference/497/trutags-usage-instructions">Usage instructions</a>'.
'<br><a href="http://forum.textpattern.com/viewtopic.php?id=15084">Forum pages</a>'.
'<br><a href="http://www.rainskit.com/reference/537/tru_tags-releases">Releases page</a>'.
'<br><a href="http://www.rainskit.com/reference/554/tru_tags-roadmap">Release roadmap</a>'.
'<br><a href="http://www.rainskit.com/reference/495/trutags-feature-list">Feature list</a>'.
'<br><br><a href="https://github.com/truist/tru-tags/blob/master/tru_tags.php">tru_tags source code</a>'.
'<br><a href="https://github.com/truist/tru-tags/blob/master/tru_tags-docs.html">Source HTML for the usage instructions</a>'.
'<br><br><a href="http://www.rainskit.com/blog/493/trutags-a-tagging-plugin-for-textpattern">tru_tags</a>, by <a href="http://www.rainskit.com/">Nathan Arthur</a>'.
'<br><br>'.
'<div id="paypal"><form action="https://www.paypal.com/cgi-bin/webscr" method="post"><input type="hidden" name="cmd" value="_s-xclick" /><input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but04.gif" name="submit" alt="Make a donation to Nathan Arthur" /><img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /><input type="hidden" name="encrypted" value="-----BEGIN PKCS7-----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-----END PKCS7-----"></form></div>'
)).
endTable().
'</td></tr>'.endTable().
'</td><td>'.
startTable('layout', '', '', '10px').'<tr><td style="border-bottom:2px solid gray;width:400px">';
if ($results) {
echo startTable('list', '', '', '', '100%').
tr(hCell(gTxt('Results'))).
tr(tda($results), ' style="color:red"').
endTable();
echo '</td></tr><tr><td style="border-bottom:2px solid gray">';
}
echo startTable('list', '', '', '', '100%').
tr(tag(gTxt('Article Tag Maintenance').' ('.gTxt('Case Sensitive').'!)', 'th', ' colspan="5"')).
tr(
form(
tda(gTxt('Rename').': ', ' style="vertical-align:middle"').
td(text_input('matchtag', '', '15')).
tda(gTxt('to').':', ' style="vertical-align:middle"').
td(text_input('replacetag', '', '15')).
td(fInput('submit', 'replace', gTxt('Run'), 'publish').eInput('tru_tags')),
'', ' verify(\'' . gTxt('are_you_sure') . '\')"'
)
).
tr(
form(
tda(gTxt('Delete').': ', ' style="vertical-align:middle"').
td(text_input('deletetag', '', '15')).
tdcs('', 2).
td(fInput('submit', 'delete', gTxt('Run'), 'publish').eInput('tru_tags')),
'', ' verify(\'' . gTxt('are_you_sure') . '\')"'
)
).
endTable();
echo '</td></tr><tr><td style="border-bottom:2px solid gray">';
echo startTable('list', '', '', '', '100%').
tr(tag(gTxt('Redirections'), 'th', ' colspan="4"'));
foreach ($redirects as $lefttag => $righttag) {
echo tr(
tda(href($lefttag, tru_tags_linkify_tag($lefttag)), ' style="text-align: center"').
tda(htmlspecialchars('=>'), ' style="text-align: center"').
tda(href($righttag, tru_tags_linkify_tag($righttag)), ' style="text-align: center"').
td('<a href="index.php?event=tru_tags&delete_redirect='.urlencode($lefttag).'" onclick="return verify(\''.gTxt('are_you_sure').'\')">Delete</a>')
);
}
echo tr(
'<form name="redirect" id="redirect" method="post" action="index.php?event=tru_tags" onsubmit="return verify(\''.gTxt('are_you_sure').'\')">'.
tda(text_input('lefttag', '', '15'), ' style="text-align:center"').
tda(htmlspecialchars('=>'), ' style="vertical-align:middle;text-align:center"').
tda(text_input('righttag', '', '15'), ' style="text-align:center"').
tda('<a href="#" onclick="if (verify(\''.gTxt('are_you_sure').'\')) document.getElementById(\'redirect\').submit(); return false;">Add new</a>', ' style="vertical-align:middle"').
fInput('hidden', 'redirect', '1').
'</form>'
).
endTable();
echo '</td></tr><tr><td>';
echo startTable('list').
tr(tag(gTxt('Preferences'), 'th', ' colspan="2"')).
form(
tr(
tda(gTxt('Use clean URLs').' ('.gTxt('site default is').' '.$tru_tags_prefs[CLEAN_URLS]->default_value.'): ', ' style="vertical-align:middle"').
td(radio_list(CLEAN_URLS,
array('clean'=>gTxt('clean'), 'messy'=>gTxt('messy')),
$tru_tags_prefs[CLEAN_URLS]->value))
).
tr(
tda(gTxt('Tag section name').' (default is "'.$tru_tags_prefs[TAG_SECTION]->default_value.'"): ', ' style="vertical-align:middle"').
td(text_input(TAG_SECTION, $tru_tags_prefs[TAG_SECTION]->value, '15'))
).
tr(
tda(gTxt('URL parameter for tag search').' (default is "'.$tru_tags_prefs[PARM_NAME]->default_value.'"): '.
'<br><em>(you shouldn\'t change this unless you really know what you are doing)</em>', ' style="vertical-align:middle"').
td(text_input(PARM_NAME, $tru_tags_prefs[PARM_NAME]->value, '15'))
).
tr(
tda(gTxt('Put tags into RSS/Atom feeds, in "Category" elements').
': <br><em>(you probably want this)</em>', ' style="vertical-align:middle"').
td(yesnoRadio(TAGS_IN_FEED_CATEGORIES, $tru_tags_prefs[TAGS_IN_FEED_CATEGORIES]->value))
).
tr(
tda('Append the tag list to the body of RSS/Atom feeds, '.
'with links, and with rel="tag":'.
'<br><em>(if this is turned on,'.
'you can define a "misc" form named tru_tags_feed_tags '.
'that will be used to render the tags in the feed)</em>',
' style="vertical-align:middle"').
td(yesnoRadio(TAGS_IN_FEED_BODY, $tru_tags_prefs[TAGS_IN_FEED_BODY]->value))
).
tr(
tda(gTxt('Show a clickable list of tags on the "Write" page').': ',
' style="vertical-align:middle"').
td(yesnoRadio(TAGS_IN_WRITE_TAB, $tru_tags_prefs[TAGS_IN_WRITE_TAB]->value))
).
tr(
tda(gTxt('Autocomplete tags on the "Write" page').': <br>'.
'<em>(you can adjust the appearance via <code>css/jquery-ui.css</code>)</em>',
' style="vertical-align:middle"').
td(yesnoRadio(AUTOCOMPLETE_IN_WRITE_TAB, $tru_tags_prefs[AUTOCOMPLETE_IN_WRITE_TAB]->value))
).
tr(
tda(gTxt('Convert tags to lowercase by default').': <br>'.
'<em>(you probably want this, unless you are having problems with utf-8 characters)</em>',
' style="vertical-align:middle"').
td(yesnoRadio(UTF_8_CASE, $tru_tags_prefs[UTF_8_CASE]->value))
).
tr(
td('').
tda(fInput('submit', 'prefs', gTxt('Save'), 'publish').eInput('tru_tags'), ' style="text-align:right"')
),
'', ' verify(\'' . gTxt('are_you_sure') . '\')"'
).
endTable().'</td></tr>'.
endTable();
echo '</td></tr>'.endTable();
}
function tru_tags_admin_tab_handle_input() {
if (gps('prefs')) {
return tru_tags_admin_update_prefs();
} else if (gps('delete')) {
return tru_tags_admin_delete_tag(gps('deletetag'));
} else if (gps('replace')) {
$result = tru_tags_admin_replace_tag(gps('matchtag'), gps('replacetag'), false);
return $result . '<br>' . tru_tags_admin_redirect_tag(gps('matchtag'), gps('replacetag'));
} else if (gps('redirect')) {
return tru_tags_admin_redirect_tag(gps('lefttag'), gps('righttag'));
} else if (gps('delete_redirect')) {
return tru_tags_admin_delete_redirect(gps('delete_redirect'));
} else {
return '';
}
}
function tru_tags_admin_update_prefs() {
global $tru_tags_prefs;
$results = array();
foreach ($tru_tags_prefs as $pref) {
$valid_value = $pref->validate_value(gps($pref->name));
if ($valid_value && $valid_value <> gps($pref->name)) {
return $valid_value; ### this is a sneaky way to handle validation - sorry ;)
}
if ($valid_value <> $pref->value) {
if ($valid_value == $pref->default_value) {
$result = tru_tags_delete_pref($pref->name);
} else {
$result = tru_tags_upsert_pref($pref->name, $valid_value);
}
if ($result) {
$results[] = 'Updated ' . $pref->name;
$pref->value = $valid_value;
} else {
$results[] = 'Error updating ' . $pref->name;
}
}
}
if (count($results) == 0) {
return 'No records need updating';
} else {
return join('<br>', $results);
}
}
function tru_tags_upsert_pref($name, $value) {
return safe_upsert('tru_tags_prefs', 'value="'.$value.'"', 'name="'.$name.'"');
}
function tru_tags_delete_pref($name) {
if (safe_delete('tru_tags_prefs', 'name="'.$name.'"')) {
if (safe_count('tru_tags_prefs', '1') == 0 && !safe_query('drop table ' . safe_pfx('tru_tags_prefs'))) {
return false;
}
return true;
} else {
return false;
}
}
function tru_tags_admin_delete_tag($deletetag) {
if (trim($deletetag)) {
return tru_tags_admin_replace_tag($deletetag, '', true);
} else {
return 'Please enter a value';
}
}
function tru_tags_admin_replace_tag($matchtag, $replacetag, $allow_blank_replacetag) {
$matchtag = trim($matchtag);
$replacetag = trim($replacetag);
if ($matchtag && ($allow_blank_replacetag || $replacetag)) {
if (safe_update('textpattern', TRU_TAGS_FIELD.'=trim(both \',\' from replace(concat(",", '.TRU_TAGS_FIELD.', ","), concat(",", \''.addslashes($matchtag).'\', ","), \','.addslashes($replacetag).',\'))', '1')) {
return 'Updated '.mysqli_affected_rows().' rows ("'.htmlspecialchars($matchtag).'"=>"'.htmlspecialchars($replacetag).'")';
} else {
return 'Error: ' . mysqli_error();
}
} else {
return 'Please enter a value in both fields';
}
}
function tru_tags_admin_redirect_tag($lefttag, $righttag) {
$lefttag = addslashes(tru_tags_strtolower(trim($lefttag)));
$righttag = addslashes(tru_tags_strtolower(trim($righttag)));
if (!$lefttag || !$righttag) {
return 'Please enter a value in both fields';
}
if (safe_insert('tru_tags_redirects', 'lefttag="'.$lefttag.'",righttag="'.$righttag.'"')) {
return 'Redirect added ("'.htmlspecialchars($lefttag).'"=>"'.htmlspecialchars($righttag).'") - please test it!';
} else {
return 'Error adding record - does it already exist?';
}
}
function tru_tags_admin_delete_redirect($lefttag) {
if (safe_delete('tru_tags_redirects', 'lefttag="'.addslashes($lefttag).'"')) {
if (safe_count('tru_tags_redirects', '1') == 0 && !safe_query('drop table ' . safe_pfx('tru_tags_redirects'))) {
return 'Redirect deleted, but unable to drop table ' . safe_pfx('tru_tags_redirects');
}
return 'Redirect deleted ("'.htmlspecialchars($lefttag).'")';
} else {
return 'Error deleting redirect';
}
}
function tru_tags_admin_write_tab_handler($event, $step, $data) {
global $tru_tags_prefs;
$atts = tru_tags_get_standard_cloud_atts(array(), true, true, true);
$cloud = array_unique(tru_tags_cloud_query($atts));
natcasesort($cloud);
$id = (empty($GLOBALS['ID']) ? gps('ID') : $GLOBALS['ID']);
$article_tags = (empty($id) ? array() : tru_tags_get_tags_for_article($id));
$links = array();
$raw_cloud = '';
foreach ($cloud as $tag) {
$style = (in_array($tag, $article_tags) ? ' class="tag_chosen"' : '');
$links[] = '<a href="#advanced"'.$style.' onclick="toggleClass(this, toggleTag(\\\''.addslashes(addslashes(htmlspecialchars($tag))).'\\\')); return false;">' . addslashes(htmlspecialchars($tag)) . '<\/a>';
$raw_cloud .= '"' . addSlashes($tag) . '",';
}
$raw_cloud = substr($raw_cloud, 0, strlen($raw_cloud) - 1);
$to_insert = join(', ', $links);
if ($tru_tags_prefs[TAGS_IN_WRITE_TAB]->value) {
$js = <<<EOF
var keywordsField = document.getElementById('keywords');
keywordsField.parentNode.appendChild(document.createElement('br'));
var cloud = document.createElement('span');
keywordsField.parentNode.appendChild(cloud);
cloud.setAttribute('class', 'tru_tags_admin_tags');
cloud.innerHTML = '{$to_insert}';
var styleElement = document.createElement('style');
styleElement.setAttribute("type", "text/css");
var styleText = 'a.tag_chosen{background-color: #FEB; color: black;}';
if (styleElement.styleSheet) { //IE
styleElement.styleSheet.cssText = styleText;
} else {
var textNode = document.createTextNode(styleText);
styleElement.appendChild(textNode);
}
var headElement = document.getElementsByTagName('head')[0];
headElement.appendChild(styleElement);
function toggleTag(tagName) {
var regexTag = tagName.replace(/([\\\\\^\\$*+[\\]?{}.=!:(|)])/g,"\\\\$1");
var tagRegex = new RegExp("((^|,)\\\s*)" + regexTag + "\\\s*(,\\\s*|$)");
var textarea = document.getElementById('keywords');
var curval = textarea.value.replace(/,?\s+$/, '');
if ('' == curval) {
textarea.value = tagName;
} else if (curval.match(tagRegex)) {
textarea.value = curval.replace(tagRegex, '$1').replace(/,?\s+$/, '');
return '';
} else if (',' == curval.charAt(curval.length - 1)) {
textarea.value += ' ' + tagName;
} else {
textarea.value += ', ' + tagName;
}
return 'tag_chosen';
}
function toggleClass(element, className) {
element.setAttribute('class', className);
element.setAttribute('className', className); /* for IE */
}
EOF;
return $data . script_js($js);
}
if ($tru_tags_prefs[AUTOCOMPLETE_IN_WRITE_TAB]->value) {
$output='<link rel="stylesheet" type="text/css" href="../css/jquery-ui.css" media="projection, screen" />
<script language="JavaScript" type="text/javascript"><!--
$(document).ready(function(){
var availableTags = ['.$raw_cloud.'];
function split( val ) { return val.split( /,\s*/ ); }
function extractLast( term ) { return split( term ).pop(); }
$("#keywords").autocomplete({ minLength: 3, delay: 500,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}});
});
//--></script>';
echo n.$output.n;
}
}
### ATOM/RSS FEED FUNCTIONS ###
###############################
register_callback('tru_tags_atom_handler', 'atom_entry');
function tru_tags_atom_handler($event, $step) { return tru_tags_feed_handler(true); }
register_callback('tru_tags_rss_handler', 'rss_entry');
function tru_tags_rss_handler($event, $step) { return tru_tags_feed_handler(false); }
function tru_tags_feed_handler($atom) {
global $thisarticle, $tru_tags_prefs;
extract($thisarticle);
$tags = tru_tags_get_tags_for_article($thisid);