-
Notifications
You must be signed in to change notification settings - Fork 4
/
smd_thumbnail.php
2334 lines (1962 loc) · 94.7 KB
/
smd_thumbnail.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_thumbnail';
// Allow raw HTML help, as opposed to Textile.
// 0 = Plugin help is in Textile format, no raw HTML allowed (default).
// 1 = Plugin help is in raw HTML. Not recommended.
# $plugin['allow_html_help'] = 1;
$plugin['version'] = '0.7.0';
$plugin['author'] = 'Stef Dawson';
$plugin['author_uri'] = 'https://stefdawson.com/';
$plugin['description'] = 'Multiple image thumbnails of arbitrary dimensions';
// 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'] = '5';
// Plugin "flags" signal the presence of optional capabilities to the core plugin loader.
// Use an appropriately OR-ed combination of these flags.
// The four high-order bits 0xf000 are available for this plugin's private use
if (!defined('PLUGIN_HAS_PREFS')) define('PLUGIN_HAS_PREFS', 0x0001); // This plugin wants to receive "plugin_prefs.{$plugin['name']}" events
if (!defined('PLUGIN_LIFECYCLE_NOTIFY')) define('PLUGIN_LIFECYCLE_NOTIFY', 0x0002); // This plugin wants to receive "plugin_lifecycle.{$plugin['name']}" events
$plugin['flags'] = '2';
// Plugin 'textpack' is optional. It provides i18n strings to be used in conjunction with gTxt().
// Syntax:
// ## arbitrary comment
// #@event
// #@language ISO-LANGUAGE-CODE
// abc_string_name => Localized String
$plugin['textpack'] = <<<EOT
#@owner smd_thumb
#@image
#@language en, en-gb, en-us
smd_thumb_actions => Actions
smd_thumb_all_sizes => All sizes
smd_thumb_all_thumbs => Create
smd_thumb_batch_preamble => (Re)create thumbnails for all active profiles, based on:
smd_thumb_btn_pnl => Profiles
smd_thumb_btn_tools => Tools
smd_thumb_btn_tools_prefs => Setup
smd_thumb_byall => All images
smd_thumb_bysel => Selected images
smd_thumb_create => Creation
smd_thumb_create_group_confirm => Really create thumbnails for ALL active profiles? Any existing thumbs will be overwritten.
smd_thumb_delete => Deletion
smd_thumb_delete_confirm => Really delete profile {name}? It will delete ALL thumbnails of this type.
smd_thumb_image => Image =
smd_thumb_new => New profile
smd_thumb_profile => Profile =
smd_thumb_profile_deleted => Profile <strong>{name}</strong> deleted
smd_thumb_profile_exists => Profile <strong>{name}</strong> already exists
smd_thumb_profile_heading => Thumbnail profiles
smd_thumb_profile_preftool_heading => Thumbnail setup
smd_thumb_profile_tool_heading => Thumbnail tools
smd_thumb_quality => Quality (%)
smd_thumb_sharpen => Sharpen
smd_thumb_tables_not_installed => Tables not installed: try reinstalling the plugin
smd_thumb_txp_auto_replace => Recreate thumbnails on re-upload of main image:
smd_thumb_txp_create_from => Create thumbnails from:
smd_thumb_txp_create_from_full => Full size image
smd_thumb_txp_create_from_thumb => Thumbnail
smd_thumb_txp_default_sync => Keep thumbnails in sync with default profile on:
smd_thumb_upload => Replace selected thumbnail
#@language fr
smd_thumb_actions => Actions
smd_thumb_all_sizes => Toutes les tailles
smd_thumb_all_thumbs => Créer
smd_thumb_batch_preamble => (Re)créer des vignettes pour les profils actifs :
smd_thumb_btn_pnl => Profils
smd_thumb_btn_tools => Outils
smd_thumb_btn_tools_prefs => Configuration
smd_thumb_byall => Tous images
smd_thumb_bysel => Sélectionnées
smd_thumb_create => Création
smd_thumb_create_group_confirm => Créer les vignettes pour TOUS les profils existant ? Les précédentes vignettes seront écrasées.
smd_thumb_delete => Suppression
smd_thumb_delete_confirm => Voulez-vous vraiment supprimer le profil {name} ? Les vignettes de ce type seront TOUTES supprimées.
smd_thumb_image => Image =
smd_thumb_new => Nouveau profil
smd_thumb_profile => Profil =
smd_thumb_profile_deleted => Le profil <strong>{name}</strong> a été supprimé.
smd_thumb_profile_exists => Le profil <strong>{name}</strong> existe déjà.
smd_thumb_profile_heading => Profils de vignettes
smd_thumb_profile_preftool_heading => Configuration du vignettage
smd_thumb_profile_tool_heading => Outils de vignettage
smd_thumb_quality => Qualité (%)
smd_thumb_sharpen => Rendre net
smd_thumb_tables_not_installed => Tables non installées : essayez de réinstaller le plugin.
smd_thumb_txp_auto_replace => Recréer les vignettes au téléchargement des images :
smd_thumb_txp_create_from => Créer les vignettes à partir de :
smd_thumb_txp_create_from_full => l’image originale
smd_thumb_txp_create_from_thumb => la vignette
smd_thumb_txp_delete => Supprimer
smd_thumb_txp_default_sync => Gardez les vignettes en synchronisation avec le profil par défaut sur :
smd_thumb_upload => Remplacer les vignettes sélectionnées
#@language de
smd_thumb_actions => Aktionen
smd_thumb_all_sizes => Alle Größen
smd_thumb_all_thumbs => Erstellen
smd_thumb_batch_preamble => (Neu-)Erstellung ALLER Thumbnails für alle aktiven Profile, basierend auf:
smd_thumb_btn_pnl => Profile
smd_thumb_btn_tools => Werkzeuge
smd_thumb_btn_tools_prefs => Einstellungen
smd_thumb_byall => Alle Bilder
smd_thumb_bysel => Ausgewählte Bilder
smd_thumb_create => beim Erstellen
smd_thumb_create_group_confirm => Wirklich thumbnails für ALLE aktiven Profile erstellen? Alle existierenden Thumbs werden überschrieben.
smd_thumb_delete => beim Löschen
smd_thumb_delete_confirm => Profil {name} wirklich löschen? Es werden ALLE Thumbs diesen Types gelöscht.
smd_thumb_image => Bild =
smd_thumb_new => Neues Profil
smd_thumb_profile => Profile =
smd_thumb_profile_deleted => Profil <strong>{name}</strong> gelöscht
smd_thumb_profile_exists => Profil <strong>{name}</strong> existiert bereits
smd_thumb_profile_heading => Thumbnail Profile
smd_thumb_profile_preftool_heading => Thumbnail Setup
smd_thumb_profile_tool_heading => Thumbnail Werkzeuge
smd_thumb_quality => Qualität (%)
smd_thumb_sharpen => schärfen
smd_thumb_tables_not_installed => Tabellen wurden nicht installiert: versuche das Plugin neu zu installieren
smd_thumb_txp_auto_replace => Neugenerierung der Thumbnails bei Upload des Hauptbildes:
smd_thumb_txp_create_from => Erstelle Thumbnails vom:
smd_thumb_txp_create_from_full => Hauptbild
smd_thumb_txp_create_from_thumb => Thumbnail
smd_thumb_txp_default_sync => Thumbnails synchron halten mit Standard-Profil:
smd_thumb_upload => Ersetze ausgewählte Thumbnails
EOT;
if (!defined('txpinterface'))
@include_once('zem_tpl.php');
# --- BEGIN PLUGIN CODE ---
/**
* smd_thumbnail
*
* A Textpattern CMS plugin for managing multiple image thumbnails:
* -> Create unlimited thumbnail profiles of differing sizes for various site uses
* -> Thumbnail files are created in your image directory -- no realtime scaling
* -> Batch create / alter thumbnails
* -> Choose to sync the thumbnails with Textpattern's own thumbs
*
* @author Stef Dawson
* @link https://stefdawson.com/
* TODO: Make Selections (lines 912-916) optional via prefs or something
* TODO: Simplify AJAX response packets to speed things up
*/
if (!defined('SMD_THUMB')) {
define("SMD_THUMB", 'smd_thumbnail');
}
if (!defined('SMD_THUMB_ACTIVE')) {
define("SMD_THUMB_ACTIVE", 1);
}
if (!defined('SMD_THUMB_CROP')) {
define("SMD_THUMB_CROP", 2);
}
if (!defined('SMD_THUMB_SHARP')) {
define("SMD_THUMB_SHARP", 4);
}
if (txpinterface === 'admin') {
global $smd_thumb_event, $smd_thumb_prevs;
$smd_thumb_event = 'smd_thumbnail';
$smd_thumb_privs = '1,2,3'; // Plugin privs
$smd_thumb_prevs = array('1'); // Privs for prefs
add_privs($smd_thumb_event, $smd_thumb_privs);
add_privs('smd_thumb_profiles', $smd_thumb_privs);
register_callback('smd_thumb_welcome', 'plugin_lifecycle.'.$smd_thumb_event);
register_callback('smd_thumb_profiles', 'image_ui', 'extend_controls');
register_callback('smd_thumbs', 'image_ui', 'thumbnail');
register_callback('smd_thumb_edit', 'image_ui', 'thumbnail_edit');
register_callback('smd_thumb_empty', 'image_ui', 'thumbnail_image');
register_callback('smd_thumb_empty', 'image_ui', 'thumbnail_create');
register_callback('smd_thumb_generate', 'image_uploaded', 'image');
register_callback('smd_thumb_generate', 'image_uploaded', 'article');
register_callback('smd_thumb_generate', 'image_uploaded', 'moderate');
register_callback('smd_thumb_delete', 'image_deleted', 'image');
register_callback('smd_thumb_create_one', 'image', 'smd_thumb_create_one');
register_callback('smd_thumb_switch_active', 'image', 'smd_thumb_switch_active');
register_callback('smd_thumb_switch_pref', 'image', 'smd_thumb_switch_pref');
register_callback('smd_thumb_insert', 'image', 'smd_thumbnail_insert', 1);
register_callback('smd_thumb_inject_css', 'admin_side', 'head_end');
} elseif (txpinterface === 'public') {
smd_thumb_set_impath();
}
if (class_exists('\Textpattern\Tag\Registry')) {
Txp::get('\Textpattern\Tag\Registry')
->register('smd_thumbnail')
->register('smd_if_thumbnail')
->register('smd_thumbnail_info');
}
/**
* CSS definitions: hopefully kind to themers.
*/
function smd_thumb_get_style_rules()
{
$smd_thumb_styles = array(
'smd_thumb' =>'
.smd_selected { border-color: #0066ff; }
.smd_hidden { display: none; }
.smd_inactive td { opacity: 0.33; }
input.smd_thumbnail-create { margin: 0; }
.smd_thumbnail_links { position:relative; flex-grow:1; margin:1em 0; text-align:right }
#smd_thumbs img { display: block; margin: 1em 0; cursor: pointer; }
.smd_thumb_heading_active { cursor:pointer; }
/* Legacy 4.6.x support */
#smd_thumb_profiles { clear: both; }
.txp-list--no-options { width: 100%; }
.txp-details .txp-listtables { margin: 1em 0;}
'
);
return $smd_thumb_styles;
}
/**
* Inject the stylesheet rules into the matching panel.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
function smd_thumb_inject_css($evt, $stp)
{
global $event;
if ($event === 'image') {
$smd_thumb_styles = smd_thumb_get_style_rules();
$content = $smd_thumb_styles['smd_thumb'];
if (class_exists('\Textpattern\UI\Style')) {
echo Txp::get('\Textpattern\UI\Style')->setContent($content);
} else {
echo '<style>' . $content . '</style>';
}
}
return;
}
/**
* Kickstart the plugin after installation/activation/deletion.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
function smd_thumb_welcome($evt, $stp)
{
switch ($stp) {
case 'installed':
smd_thumb_table_install();
// Remove per-user prefs on upgrade from v0.1x to v0.20.
safe_delete ('txp_prefs', "name IN ('smd_thumb_txp_create', 'smd_thumb_txp_delete', 'smd_thumb_auto_replace') AND user_name != ''");
break;
case 'deleted':
smd_thumb_table_remove();
break;
}
return;
}
/**
* Display the designated default thumbnail on the list page.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
* @param string $dflt Default markup ready to render
* @param array $currimg Current image information
*/
function smd_thumbs($evt, $stp, $dflt, $currimg)
{
extract(gpsa(array('page', 'sort', 'dir', 'crit', 'search_method')));
$search_method = (is_array($search_method)) ? implode(',', $search_method) : $search_method;
if (smd_thumb_table_exist()) {
$default = get_pref('smd_thumb_default_profile', '', 1);
if ($default) {
$row = safe_row('*', SMD_THUMB, "name='".sanitizeForUrl($default)."'");
if ($row) {
$edit_url = '?event=image'.a.'step=image_edit'.a.'id='.$currimg['id'].a.'sort='.$sort.
a.'dir='.$dir.a.'page='.$page.a.'search_method='.$search_method.a.'crit='.$crit;
$out = smd_thumb_img($row, $currimg, array('class' => 'content-image '.$default));
return ($out) ? href($out, $edit_url) : gTxt('no');
} else {
return gTxt('no');
}
} else {
return gTxt('no');
}
}
}
/**
* Don't want the 'create' controls or thumbnail image as they're both handled in the edit portion of the screen.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
* @param string $dflt Default markup ready to render
* @param array $currimg Current image information
*/
function smd_thumb_empty($evt, $stp, $dflt, $currimg)
{
return ' ';
}
/**
* Create a bunch of thumbnails en masse.
*
* With a lot of images in the database, doing it all in one hit would time out.
* Thus it's done via ajax; one request per image.
*
* @param string $type Flavour of thumbnail creation: by (usr), by (cat), by (sel)ection, or (all)
* @param string $lst List of images to operate upon
* @return [type] [description]
*/
function smd_thumb_create_group($type, $lst = '')
{
switch ($type) {
case 'all':
$where = '1=1';
break;
case 'sel':
$where = ($lst) ? 'id IN ('.doSlash($lst).')' : '1=0';
break;
case 'cat':
$where = "category in ('".doSlash($lst)."')";
break;
case 'usr':
$where = "author in ('".doSlash($lst)."')";
break;
}
$images = safe_column('id', 'txp_image', $where);
$count = count($images);
$scriptout = <<<EOJS
var bctr = 0; var btot = {$count};
jQuery(function() {
jQuery("#smd_thumb_btot").text("/{$count}");
EOJS;
foreach ($images as $img) {
$scriptout .= <<<EOJS
sendAsyncEvent(
{
event: textpattern.event,
step: 'smd_thumb_create_one',
smd_thumb_imgid: {$img}
}, smd_create_group_feedback);
EOJS;
}
$scriptout .= <<<EOJS
});
function smd_create_group_feedback() {
bctr++;
jQuery('#smd_thumb_bcurr').text(bctr);
}
EOJS;
echo script_js($scriptout);
}
/**
* AJAX method to create one thumbnail for each active profile, from the passed ID.
*/
function smd_thumb_create_one()
{
$currimg = gps('smd_thumb_imgid');
assert_int($currimg);
$rs = safe_rows('*', SMD_THUMB, '1=1 AND flags & ' . SMD_THUMB_ACTIVE);
$curr = safe_row('*', 'txp_image', "id=" . doSlash($currimg));
if ($rs) {
$ret = smd_thumb_make($rs, $curr, 1);
if (is_array($ret) && in_array($ret[1], array(E_ERROR, E_NOTICE))) {
$rcode = '415 Unsupported Media Type';
} elseif (!$ret) {
$rcode = '406 Not Acceptable';
} else {
$rcode = '200 OK';
}
send_xml_response(array('http-status' => $rcode, 'msg' => $ret));
}
}
/**
* AJAX method to set the active thumbnail profile.
*
* Requires GET/POST params:
* -> smd_thumb_profile TName of the profile to set as active
*/
function smd_thumb_switch_active()
{
$name = doSlash(gps('smd_thumb_profile'));
if ($name) {
safe_update(SMD_THUMB, 'flags = flags ^ ' . SMD_THUMB_ACTIVE, "name='$name'");
send_xml_response(array('smd_thumb_profile' => $name));
}
}
/**
* AJAX method to toggle the given preference name to the given state.
*
* Requires GET/POST params:
* -> smd_thumb_txptype Preference name (without plugin prefix)
* -> smd_thumb_state Preference value to store
*/
function smd_thumb_switch_pref()
{
$name = doSlash(gps('smd_thumb_txptype'));
$state = doSlash(gps('smd_thumb_state'));
if ($name) {
set_pref('smd_thumb_'.$name, $state, 'smd_thumb', PREF_HIDDEN, 'text_input');
send_xml_response();
}
}
/**
* Wrapper to create thumbnail for active profiles from uploaded image.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
* @param string $id New image identifier. If omitted, will try GET/POST, then Textpattern's GLOBALS['ID']
*/
function smd_thumb_generate($evt, $stp, $id = '')
{
// Catch situations where the plugin is installed without lifecycle on a
// new install where no images exist. Thus the first time the plugin is
// invoked is here when the first image is uploaded.
if (!smd_thumb_table_exist()) {
smd_thumb_table_install();
}
$id = ($id) ? $id : gps('id');
$id = ($id) ? $id : $GLOBALS['ID'];
$rs = safe_rows('*', SMD_THUMB, '1=1 AND flags & ' . SMD_THUMB_ACTIVE);
smd_thumb_make($rs, $id);
}
/**
* Wrapper to delete a bunch of selected thumbnails.
*
* Uses GET/POST parameters:
* -> selected Comma-separated list of selected image identifiers
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
*/
function smd_thumb_delete($evt, $stp)
{
$ids = gps('selected');
$rs = safe_rows('*', SMD_THUMB, '1=1');
$images = safe_rows('*', 'txp_image', 'id IN (' . join(',',quote_list($ids)) . ')');
foreach ($images as $img) {
smd_thumb_unmake($rs, $img);
}
}
/**
* Create a thumbnail.
*
* @param array $rs Record set containing image meta data
* @param int $currimg Identifier for the current image being operated upon
* @param bool $force Whether to always create the thumbnail, even if it exists
* @return string Feedback message
*/
function smd_thumb_make($rs, $currimg, $force = 0)
{
// Wrapper for wet_thumb to allow multiple thumbnails.
$msg = '';
smd_thumb_set_impath();
if (!class_exists('smd_thumb')) {
class smd_thumb extends wet_thumb
{
var $m_ext;
var $m_id;
var $m_dir;
var $m_dflt;
var $width;
var $height;
var $force;
/**
* Constructor.
*
* @param int $id Unique image identifier
* @param string $dir Subdirectory in which to store the image
* @param array $img_row Image meta data to store
* @param boolean $is_default Whether the thumbnail is to become the default
* @param string $pro_w Thumbnail width
* @param string $pro_h Thumbnail height
* @param boolean $force Whether to overwrite any previous thumbnail
*/
public function __construct ($id, $dir, $img_row, $is_default = false, $pro_w = '', $pro_h = '', $force = 0)
{
$id = assert_int($id);
if ($img_row) {
extract($img_row);
$this->m_id = $id;
$this->m_ext = $ext;
$this->m_dir = $dir;
$this->force = $force;
$this->width = $pro_w;
$this->height = $pro_h;
$this->m_dflt = $is_default;
}
parent::__construct();
}
/**
* Store the thumbnail image on disk.
*
* @return bool
*/
public function write_image()
{
if (!isset($this->m_ext)) {
return false;
}
$autorep = get_pref('smd_thumb_auto_replace', '0');
$recfrom = get_pref('smd_thumb_create_from', 'full');
$src_sz = ($recfrom === 'full') ? '' : 't';
$infile = IMPATH . $this->m_id . $src_sz . $this->m_ext;
$outfile = IMPATH . $this->m_dir . DS . $this->m_id . $this->m_ext;
// If we're trying to create from Txp thumbnail but it doesn't exist,
// fall back to creating from full image.
if (!file_exists($infile) && $src_sz === 't') {
$infile = IMPATH . $this->m_id . $this->m_ext;
}
if (!file_exists($outfile) || $autorep || $this->force) {
// If this is the default profile and the pref indicates, write a Textpattern thumb too.
if (($this->m_dflt === true) && (get_pref('smd_thumb_txp_create', '0'))) {
$txp_thumb = IMPATH . $this->m_id . 't' . $this->m_ext;
if (parent::write($infile, $txp_thumb)) {
safe_update('txp_image', "thumbnail = 1, thumb_w = $this->width, thumb_h = $this->height", 'id = ' . $this->m_id);
@chmod($outfile, 0644);
}
}
if (parent::write ($infile, $outfile)) {
@chmod($outfile, 0644);
return true;
}
}
return false;
}
}
}
// If passed only an ID, look up the rest of the image data.
if (!is_array($currimg)) {
assert_int($currimg);
$currimg = safe_row('*', 'txp_image', 'id=' . $currimg);
}
// Create each thumbnail.
$pro_dflt = get_pref('smd_thumb_default_profile', '');
foreach ($rs as $row) {
// Sanitize a little.
$width = (int) $row['width'];
$height = (int) $row['height'];
if ($width === 0) {
$width = '';
}
if ($height === 0) {
$height = '';
}
if ($width === '' && $height === '') {
continue;
}
$crop = ($row['flags'] & SMD_THUMB_CROP) ? 1 : 0;
$sharpen = ($row['flags'] & SMD_THUMB_SHARP) ? 1 : 0;
$id = $currimg['id'];
$is_dflt = ($row['name'] === $pro_dflt) ? true : false;
$t = new smd_thumb($id, sanitizeForUrl($row['name']), $currimg, $is_dflt, $width, $height, $force);
$t->extrapolate = true; // Allow bigger thumbs than original image.
$t->crop = ($crop === 1);
$t->sharpen = ($sharpen === 1);
$t->hint = '0';
$t->width = $width;
$t->height = $height;
$t->quality = $row['quality'];
if ($t->write_image()) {
$msg = gTxt('thumbnail_saved', array('{id}' => $id));
} else {
$msg = array(gTxt('thumbnail_not_saved', array('{id}' => $id)), E_ERROR);
}
}
return $msg;
}
/**
* Delete the passed set of thumbnails.
*
* @param array $rs Sert of image identifiers to delete
* @param int $currimg Current image being operated upon
*/
function smd_thumb_unmake($rs, $currimg)
{
$id = $currimg['id'];
$ext = $currimg['ext'];
$pro_dflt = get_pref('smd_thumb_default_profile', '');
$txp_del = get_pref('smd_thumb_txp_delete', '0');
smd_thumb_set_impath();
foreach ($rs as $row) {
$path = IMPATH . sanitizeForUrl($row['name']) . DS . $id . $ext;
if (file_exists($path)) {
unlink($path);
}
// Also remove Txp's built-in thumb?
if (($row['name'] === $pro_dflt) && ($txp_del == '1')) {
$path = IMPATH . $id . 't' . $ext;
if (file_exists($path)) {
safe_update('txp_image', "thumbnail = 0, thumb_w = 0, thumb_h = 0", 'id = ' . $id);
unlink($path);
}
}
}
return '';
}
/**
* Insert a thumbnail when a new file is uploaded.
*/
function smd_thumb_insert()
{
global $txpcfg, $txp_user, $page, $sort, $dir, $crit, $search_method;
smd_thumb_set_impath();
extract(gpsa(array('page', 'sort', 'dir', 'crit', 'search_method')));
$search_method = (is_array($search_method)) ? implode(',', $search_method) : $search_method;
include_once txpath.'/lib/txplib_misc.php';
extract($txpcfg);
$id = assert_int(gps('id'));
$profile = gps('smd_thumb_profile');
$thumb_ext = gps('smd_thumb_ext');
$author = fetch('author', 'txp_image', 'id', $id);
if (!has_privs('image.edit') && !($author == $txp_user && has_privs('image.edit.own'))) {
return;
}
$file = $_FILES['thefile']['tmp_name'];
$name = $_FILES['thefile']['name'];
$file = get_uploaded_file($file);
if (empty($file)) {
return;
}
list($w, $h, $extension) = getimagesize($file);
$valid_exts = array(
'.gif' => IMAGETYPE_GIF,
'.jpg' => IMAGETYPE_JPEG,
'.jpeg' => IMAGETYPE_JPEG,
'.png' => IMAGETYPE_PNG,
);
$gd_info = gd_info();
if (!empty($gd_info['WebP Support'])) {
$valid_exts['.webp'] = IMAGETYPE_WEBP;
}
if (!empty($gd_info['AVIF Support'])) {
$valid_exts['.avif'] = IMAGETYPE_AVIF;
}
$ext = (string) array_search($extension, $valid_exts);
if (($file !== false) && $profile && $ext) {
$newpath = IMPATH . sanitizeForUrl($profile) . DS . $id . $ext;
if (shift_uploaded_file($file, $newpath) === false) {
// Failed: do nothing.
} else {
@chmod($newpath, 0644);
// If the pref indicates, duplicate as a Textpattern thumb too.
if (get_pref('smd_thumb_txp_create', '0') == 1) {
$txp_thumb = IMPATH . $id . 't' . $ext;
if (copy($newpath, $txp_thumb)) {
safe_update('txp_image', "thumbnail = 1, thumb_w = $w, thumb_h = $h", 'id = ' . $id);
@chmod($txp_thumb, 0644);
}
}
// $message = gTxt('image_uploaded', array('{name}' => $name));
}
}
// Since the headers have been sent, resort to JavaScript to refresh the page.
$urlPieces = array(
'event' => 'image',
'step' => 'image_edit',
'id' => $id,
'sort' => $sort,
'dir' => $dir,
'page' => $page,
'search_method' => $search_method,
'crit' => $crit,
);
$url = html_entity_decode(join_qs($urlPieces));
$scriptout = 'window.location.href="{' . $url . '}";';
$noscriptout = '<meta http-equiv="refresh" content="0;url={' . $url . '}" />';
if (class_exists('\Textpattern\UI\Script')) {
echo Txp::get('\Textpattern\UI\Script')->setContent($scriptout)
->setNoscript($noscriptout);
} else {
echo '<script>' . $scriptout . '</script>'.
n.'<noscript>' . $noscriptout . '</noscript>';
}
exit;
}
/**
* pluggable_ui callback to render the additions to the image edit panel.
*
* @param string $evt Textpattern event (panel)
* @param string $stp Textpattern step (action)
* @param string $dflt Default markup ready to render
* @param array $currimg Current image information
*/
function smd_thumb_edit($evt, $stp, $dflt, $currimg)
{
global $step, $file_max_upload_size, $txp_user;
extract(gpsa(array(
'id',
'page',
'sort',
'dir',
'crit',
'search_method',
'smd_thumbnail_size',
'smd_thumbnail_chosen_size',
'smd_thumbnail_delete',
'smd_step'
)));
$id = ($id) ? $id : $GLOBALS['ID'];
$search_method = (is_array($search_method)) ? implode(',', $search_method) : $search_method;
// Toggle profile panel.
if ($step === 'save_pane_state') {
smd_thumbnail_save_pane_state();
return;
}
// Create/delete the selected thumbs depending on the button pressed.
if ($smd_step === 'smd_thumbnail_manage') {
// Validate user.
$author = fetch('author', 'txp_image', 'id', $id);
if (!has_privs('image.edit') && !($author == $txp_user && has_privs('image.edit.own'))) {
image_list(gTxt('restricted_area'));
return;
}
// Grab the thumbnails to work on.
$where = ($smd_thumbnail_size === 'all') ? '1=1 AND flags & ' . SMD_THUMB_ACTIVE : "name='" . doSlash($smd_thumbnail_chosen_size) . "'";
$rs = safe_rows('*', SMD_THUMB, $where);
// Do it.
if ($smd_thumbnail_delete) {
$msg = smd_thumb_unmake($rs, $currimg);
} else {
$msg = smd_thumb_make($rs, $currimg, 1);
}
}
$ext = $currimg['ext'];
echo script_js(<<<EOC
function smd_thumb_selector(sel) {
var idx = 0;
jQuery("#smd_thumbs img").each(function() {
if (jQuery(this).hasClass(sel)) {
jQuery(this).toggleClass('smd_selected active');
if (jQuery(this).hasClass('smd_selected')) {
jQuery("#smd_upload_thumbnail").attr('disabled', false);
jQuery(".smd_thumbnail-upload input[type=submit]").attr('disabled', false);
jQuery("#smd_thumb_profile").val(sel);
idx = jQuery("#smd_thumbnail_size option[value='"+sel+"']").index();
jQuery("#smd_thumbnail_chosen_size").val(sel);
} else {
jQuery("#smd_upload_thumbnail").attr('disabled', true);
jQuery(".smd_thumbnail-upload input[type=submit]").attr('disabled', true);
jQuery("#smd_thumb_profile").val('');
jQuery("#smd_thumbnail_chosen_size").val('');
}
} else {
jQuery(this).removeClass('smd_selected active');
}
});
jQuery("#smd_thumbnail_size").prop("selectedIndex", idx);
}
function smd_thumb_select_changed() {
obj = jQuery("#smd_thumbnail_size");
if (obj.attr("selectedIndex") == 0) {
jQuery("#smd_upload_thumbnail").attr('disabled', true);
jQuery(".smd_thumbnail-upload input[type=submit]").attr('disabled', true);
jQuery("#smd_thumb_profile").val('');
jQuery("#smd_thumbnail_chosen_size").val('');
} else {
jQuery("#smd_upload_thumbnail").attr('disabled', false);
jQuery(".smd_thumbnail-upload input[type=submit]").attr('disabled', false);
jQuery("#smd_thumb_profile").val(obj.val());
jQuery("#smd_thumbnail_chosen_size").val(obj.val());
}
jQuery("#smd_thumbs img").each(function() {
if (jQuery(this).hasClass(obj.val())) {
jQuery(this).addClass('smd_selected active');
} else {
jQuery(this).removeClass('smd_selected active');
}
});
}
jQuery(function() {
jQuery("#smd_thumbs img").each(function() {
var prf = jQuery(this).data('profile');
jQuery(this).click(function() {
smd_thumb_selector(prf);
});
});
jQuery("#smd_upload_thumbnail").attr('disabled', true);
jQuery(".smd_thumbnail-upload input[type=submit]").attr('disabled', true);
jQuery(".smd_thumbnail-upload").prepend('<input type="hidden" name="smd_thumb_imgid" value="{$id}" /><input type="hidden" id="smd_thumb_profile" name="smd_thumb_profile" value="" /><input type="hidden" id="smd_thumb_ext" name="smd_thumb_ext" value="{$ext}" />');
});
EOC
);
// Add thumbnails and creation controls.
if (smd_thumb_table_exist()) {
$rs = safe_rows('*', SMD_THUMB, '1=1 ORDER BY name');
if ($rs) {
$profiles = array('all' => gTxt('smd_thumb_all_sizes'));
$thumbs[] = '<div id="smd_thumbs">';
foreach ($rs as $row) {
if ($row['flags'] & SMD_THUMB_ACTIVE) {
$profiles[$row['name']] = $row['name'];
}
$thumbs[] = smd_thumb_img($row, $currimg, array(
'class' => 'content-image ' . $row['name'],
'data-profile' => $row['name'],
));
}
$thumbs[] = '</div>';
$qs = array(
"event" => 'image',
"step" => 'image_edit',
"id" => $id,
"page" => $page,
"sort" => $sort,
"dir" => $dir,
"crit" => $crit,
"search_method" => $search_method,
);
$out[] = upload_form(gTxt('smd_thumb_upload'), '', 'smd_thumbnail_insert', 'image', $id, $file_max_upload_size, 'smd_upload_thumbnail', 'smd_thumbnail-upload');
$out[] = '<form name="smd_thumbnail_create" method="post" action="'.join_qs($qs).'">'.n.'<p>';
$out[] = fInput('hidden', 'smd_step', 'smd_thumbnail_manage');
$out[] = fInput('hidden', 'smd_thumbnail_chosen_size', '', '', '', '', '', '', 'smd_thumbnail_chosen_size');
$out[] = selectInput('smd_thumbnail_size', $profiles, '', '', ' onchange="return smd_thumb_select_changed()";', 'smd_thumbnail_size');
$out[] = fInput('submit', '', gTxt('create'), 'smd_thumbnail-create');
$out[] = fInput('submit', 'smd_thumbnail_delete', gTxt('delete'), 'smd_thumbnail-delete');
$out[] = join('', $thumbs);
$out[] = '</p>'.n.'</form>';
return join(n, $out);
}
}
return ' ';
}
/**
* Create an <img> tag to a thumbnail.
*
* @param array $row Thumbnail information
* @param array $currimg Corresponding image information
* @param array $meta Thumbnail meta info
* @param string $dsp Textpattern Form that contains rendering information
* @return string
*/
function smd_thumb_img($row, $currimg, $meta = array(), $dsp = '')
{
global $img_dir, $smd_thumb_data;
static $mimetypes;
if (!isset($mimetypes)) {
$mimetypes = get_safe_image_types();
}
smd_thumb_set_impath();
$dir = sanitizeForUrl($row['name']);
$id = $currimg['id'];
$ext = $currimg['ext'];
$alt = $currimg['alt'];
// alt is a mandatory attribute so make sure it exists (even if it's "").
if (!isset($meta['alt'])) {
$meta['alt'] = $currimg['alt'];
}
$path = IMPATH . $dir . DS . $id . $ext;
if (file_exists($path)) {
$extras = '';
if (isset($meta['forcew']) || isset($meta['forceh'])) {
$dims = getimagesize($path);
if (isset($meta['forcew']) && !$row['width']) {
$row['width'] = $dims[0];
}
if (isset($meta['forceh']) && !$row['height']) {