-
Notifications
You must be signed in to change notification settings - Fork 6
/
image-metadata-cruncher.php
executable file
·1598 lines (1413 loc) · 51.6 KB
/
image-metadata-cruncher.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 Name: Image Metadata Cruncher
Description: Gives you ultimate controll over which image metadata (EXIF or IPTC) WordPress extracts from an uploaded image and where and in what form it then goes. You can even specify unlimited custom post meta tags as the target of the extracted image metadata.
Version: 1.8
Author: Peter Hudec
Author URI: http://peterhudec.com
Plugin URI: http://peterhudec.com/programming/2012/11/13/image-metadata-cruncher-wp-plugin/
License: GPL2
*/
/**
* Main plugin class
*/
class Image_Metadata_Cruncher {
// stores metadata between wp_handle_upload_prefilter and add_attachment hooks
private $metadata;
private $keyword;
private $keywords;
private $pattern;
public $plugin_name = 'Image Metadata Cruncher';
private $version = 1.5;
private $after_update = FALSE;
private $settings_slug = 'image_metadata_cruncher-options';
private $donate_url = 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RJYHYJJD2VKAN';
/**
* Constructor
*/
function __construct() {
$options = get_option( $this->plugin_name );
$this->after_update = intval( $options['version'] ) < intval( $this->version );
// the EXIF and IPTC mapping arrays are quite long, so they deserve to be in separate files
require_once 'includes/exif-mapping.php';
require_once 'includes/iptc-mapping.php';
// create regex patterns
$this->patterns();
/////////////////////////////////////////////////////////////////////////////////////
// WordPress Hooks
/////////////////////////////////////////////////////////////////////////////////////
// plugin settings hooks
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_action_links' ), 10, 2 );
add_filter( 'plugin_row_meta', array( $this, 'plugin_row_meta' ), 10, 2 );
register_activation_hook( __FILE__, array( $this, 'defaults' ) );
add_action('admin_init', array( $this, 'init' ) );
add_action('admin_menu', array( $this, 'options' ) );
// plugin functionality hooks
add_action( 'wp_handle_upload_prefilter', array( $this, 'wp_handle_upload_prefilter' ) );
add_action( 'add_attachment', array( $this, 'add_attachment' ) );
}
/////////////////////////////////////////////////////////////////////////////////////
// Functionality
/////////////////////////////////////////////////////////////////////////////////////
private function insert_next_to_key( &$array, $key, $value, $insert_before = FALSE ) {
// get position of the index in the array
$offset = array_search( $key, array_keys( $array ) );
if ( ! $insert_before ) {
$offset++;
}
$left = array_slice( $array, 0, $offset );
$right = array_slice( $array, $offset );
$array = array_merge( $left, $value, $right );
}
/**
* The wp_handle_upload_prefilter hook gets triggered before
* wordpress erases all the image metadata
*
* @return untouched file
*/
public function wp_handle_upload_prefilter( $file ) {
// get meta
$this->metadata = $this->get_meta_by_path( $file['name'], $file['tmp_name'] );
// return untouched file
return $file;
}
/**
* The add_attachment hook gets triggered when the attachment post is created.
* In Wordpress media uploads are handled as posts.
*/
public function add_attachment( $post_ID, $template = array() ) {
// get plugin options
$options = get_option( $this->prefix );
// uploaded image is handled as post by WordPress
$post = get_post( $post_ID );
// Try to get template from $template array then from $options.
$title = isset( $template['title'] ) ? $template['title'] : $options['title'];
$caption = isset( $template['caption'] ) ? $template['caption'] : $options['caption'];
$description = isset( $template['description'] ) ? $template['description'] : $options['description'];
$alt = isset( $template['alt'] ) ? $template['alt'] : $options['alt'];
if ( isset( $template['custom_meta'] ) ) {
$meta = $template['custom_meta'];
} elseif ( isset( $options['custom_meta'] ) ) {
$meta = $options['custom_meta'];
} else {
$meta = array();
}
// Apply new values to post properties:
// title
$post->post_title = $this->render_template( $title );
// caption
$post->post_excerpt = $this->render_template( $caption );
// description
$post->post_content = $this->render_template( $description );
// alt is meta attribute
update_post_meta( $post_ID, '_wp_attachment_image_alt', $this->render_template( $alt ) );
// add custom post meta if any
foreach ( $meta as $key => $value ) {
// get value
$value = $this->render_template( $value );
// update or create the post meta
add_post_meta( $post_ID, $key, $value, true ) or update_post_meta( $post_ID, $key, $value );
}
// finally sanitize and update post
// sanitize_post( $post );
wp_update_post( $post );
}
/**
* Extracts image metadata from the image specified by its path.
*
* @return structured array with all available metadata
*/
public function get_meta_by_path( $name, $tmp_name = NULL ) {
if ( !$tmp_name ) {
$tmp_name = $name;
}
$this->metadata = array();
// extract metadata from file
// the $meta variable will be populated with it
$size = getimagesize( $tmp_name, $meta );
// extract pathinfo and merge with size
$this->metadata['Image'] = array_merge( $size, pathinfo( $name ) );
// remove index 'dirname'
unset($this->metadata['Image']['dirname']);
// parse iptc
// IPTC is stored in the APP13 key of the extracted metadata
$iptc = null;
if ( isset( $meta['APP13'] ) ) {
$iptc = iptcparse( $meta['APP13'] );
}
if ( $iptc ) {
// symplify array structure
foreach ( $iptc as &$i ) {
// if the array has only one item
if ( count( $i ) <= 1 ) {
$i = $i[0];
}
}
// add named copies to all found IPTC items
foreach ( $iptc as $key => $value ) {
if ( isset( $this->IPTC_MAPPING[ $key ] ) ) {
$name = $this->IPTC_MAPPING[ $key ];
// add "Caption" alias to "Caption-Caption-Abstract"
if ( $key == '2#120' ) {
$this->insert_next_to_key( $iptc, $key, array( 'Caption' => $value ) );
}
$this->insert_next_to_key( $iptc, $key, array( $name => $value ) );
}
}
}
if ( $iptc ) {
$this->metadata['IPTC'] = $iptc;
}
// parse exif
$exif = NULL;
// the exif_read_data() function throws a warning if it is passed an unsupported file format.
// This warning is impossible to catch so we have to check the file mime type manually
$safe_file_formats = array(
'image/jpg',
'image/jpeg',
'image/tif',
'image/tiff',
);
if ( in_array( $size['mime'], $safe_file_formats ) ) {
$exif = exif_read_data( $tmp_name );
if ( is_array( $exif ) ) {
// add named copies of UndefinedTag:0x0000 items to $exif array
foreach ( $exif as $key => $value ) {
// check case insensitively if key begins with "UndefinedTag:"
if ( strtolower( substr( $key, 0, 13 ) ) == 'undefinedtag:' ) {
// get EXIF tag name by ID and convert it to base 16 integer
$id = intval( substr( $key, 13 ), 16 );
if ( isset( $this->EXIF_MAPPING[ $id ] ) ) {
// create copy with EXIF tag name as key
$name = $this->EXIF_MAPPING[ $id ];
//$exif[ $name ] = $value;
$this->insert_next_to_key( $exif, $key, array( $name => $value ) );
}
}
}
}
}
if ( $exif ) {
$this->metadata['EXIF'] = $exif;
}
// no need for return but good for testing
return $this->metadata;
}
/**
* Extracts image metadata from the image specified by the attachment post ID.
*
* @return structured array with all available metadata
*/
public function get_meta_by_id( $ID ) {
$post = get_post( $ID );
return $this->get_meta_by_path( $post->guid );
}
/**
* Extracts metadata from the image file belonging to the attachment post
* specified by the $ID and updates the post according to supplied $template array.
* The $template array should have following structure:
*
* $template = array(
* 'title' => 'Title template',
* 'caption' => 'Caption template',
* 'description' => 'Description template',
* 'alt' => 'Alt template',
* 'custom_meta' => array(
* 'meta-name' => 'Meta template',
* 'another-meta-name' => 'Another meta template',
* ),
* )
*
* Settings templates will be used for missing indexes in the array.
*/
public function crunch( $ID, $template = array() ) {
# Get the attachment post.
$post = get_post( $ID );
# Extract metadata.
$this->get_meta_by_id( $ID );
# Update attachment.
$this->add_attachment( $ID, $template );
}
/**
* Replaces template tags in template string.
*
* @return Sanitized template string with processed template tags.
*/
private function render_template( $template ){
// restore escaped characters
$template = str_replace(
array(
'<',
'>',
''',
'"'
),
array(
'<',
'>',
"'",
'"'
),
$template
);
// replace each found tag with parse_tag method return value
$result = preg_replace_callback( $this->pattern, array( $this, 'parse_tag' ), $template );
if ( $result === NULL ) {
$result = $template;
}
// handle escaped curly brackets
$result = str_replace(array('\{', '\}'), array('{', '}'), $result);
return sanitize_text_field( $result );
}
/**
* Converts array keys recursively
*
* @return recursive copy of an array with lowercase keys
*/
private function array_keys_to_lower_recursive( $array ) {
$array = array_change_key_case( $array, CASE_LOWER );
foreach ( $array as $key => $value ) {
if ( is_array( $value ) ) {
// if value is array call this function recursively with the value as argument
$array[ $key ] = $this->array_keys_to_lower_recursive( $value );
}
}
return $array;
}
/**
* Searches for metadata case insensitively by category and value
*
* @return found value
*/
private function get_metadata( $metadata, $category, $key ) {
// convert to lowercase to allow for case insensitive search
$category = strtolower( $category );
$key = strtolower( $key );
if ( isset( $metadata[ $category ][ $key ] ) ) {
return $metadata[ $category ][ $key ];
}
}
/**
* Analyses template keyword and searches for its value in $this->metadata
*
* @return found value
*/
private function get_meta_by_key( $key, $delimiter = NULL ){
// convert metadata keys to lowercase to allow for case insensitive keys
$metadata = $this->array_keys_to_lower_recursive( $this->metadata );
if ( ! $delimiter ) {
// if no delimiter specified in the tag, coma and space will be used as default
$delimiter = ', ';
}
// separate key prefix and suffix on the first occurence of a colon
$pieces = explode( ':', $key, 2 );
// get case insensitive prefix
$category = strtolower( $pieces[0] );
if ( count( $pieces ) > 1 ) {
// parse path pieces separated by ">" greater than character
$path = explode( '>', $pieces[1] );
} else {
// tag is not valid without anything after colon e.g. "EXIF:"
return; // exit and return nothing
}
// start search
$value = $key = NULL;
if ( $category == 'all' ) {
// get nested level specified by path
$value = $this->explore_path( $this->metadata, $path );
switch ( strtolower( $path[0] ) ) {
case 'php':
// return found value as human readable PHP array
return print_r( $value, TRUE );
break;
case 'json':
// return found value as JSON
return json_encode( $value );
break;
case 'jsonpp':
// return found value as pretty printed JSON
// JSON_PRETTY_PRINT constant is available since PHP 5.4.0
$JSON_PRETTY_PRINT = defined( 'JSON_PRETTY_PRINT' ) ? JSON_PRETTY_PRINT : NULL ;
return json_encode( $value, $JSON_PRETTY_PRINT );
break;
case 'xml':
// not implemented yet
break;
default:
break;
}
} elseif ( $category == 'exif' ) {
// key is the first part of the path
$key = $path[0];
// try to find value directly in the keys returned by exif_read_data() function
// e.g. {EXIF:Model}
$value = $this->get_metadata( $metadata, $category, $key );
if ( ! $value ) {
// some EXIF tags are returned by the exif_read_data() functions like "UndefinedTag:0x####"
// so if nothing found try looking up for "UndefinedTag:0x####"
// since we need an uppercase hex number e.g. 0xA432 but with lowercase 0x part
// we convert the key to base 16 integer and then back to uppercase string
$key = strtoupper( dechex( intval( $key, 16 ) ) );
// construct the "UndefinedTag:0x####" key and search for it in the extracted metadata
$key = "UndefinedTag:0x$key";
$value = $this->get_metadata( $metadata, $category, $key );
}
} else {
// try to find anything that is provided (handles IPTC too)
$key = $path[0];
$value = $this->get_metadata( $metadata, $category, $key );
}
// get the level of the value specified in the path
$value = $this->explore_path( $value, $path );
if ( is_array( $value ) ) {
// if value is array convert it to string
$value = implode( $delimiter, $value );
}
// some IPTC metadata contain the End Of Transmission character, which strips everythig after it
$value = str_replace("", '', $value);
return $value;
}
/**
* Traverses value according to path
*
* @return value found at the level specified in the path
*/
private function explore_path( $value, $path, $index = 0 ) {
// if value is array
if ( is_array( $value ) ) {
$index++;
if ( isset( $path[ $index ] ) ) {
// if index set in the path, get its value
// temporarily convert value and path to lowercase to allow for key insensitive lookup
$value_lower = array_change_key_case( $value, CASE_LOWER );
$path_lower = strtolower( $path[ $index ] );
$value = $value_lower[ $path_lower ];
// before returning check if there is not another part of the path
return $this->explore_path( $value, $path, $index );
} else {
return $value;
}
} else {
// if value is not an aray return it
return $value;
}
}
/**
* Processes the match of a regular expression which matches the template tag and
* captures keywords group and success, default and delimiter options
*
* @return tag replacement or empty string
*/
private function parse_tag( $match ) {
$keywords = isset( $match['keywords'] ) ? explode( '|', $match['keywords'] ) : array();
$success = isset( $match['success'] ) ? $match['success'] : FALSE;
$default = isset( $match['default'] ) ? $match['default'] : FALSE;
$delimiter = isset( $match['delimiter'] ) ? $match['delimiter'] : FALSE;
if ( $keywords ) {
foreach ( $keywords as $keyword ) {
// search for key in metadata extracted from the image
//TODO: Sanitize?
$meta = $this->get_meta_by_key( trim( $keyword ), $delimiter );
if ( $meta ) {
// return first found meta
if ( $success ) {
// if success option specified
// return success string with $ dolar sign replaced by found meta
// and handle escaped characters
return str_replace(
array(
'\$', // replace escaped dolar sign with some unusual unicode character
'$', // replace dolar signs for meta value
'\"', // replace escaped doublequote for doublequote
'\u2328' // replace \u2328 with dolar sign
),
array(
'\u2328',
$meta,
'"',
'$'
),
$success
);
} else {
return $meta;
}
}
}
}
// if flow gets here nothing was found so...
if ( $default ){
// ...return default if specified or...
return $default;
} else {
// ...empty string
return '';
}
}
/**
* Declares all regex patterns used inside the class
*/
private function patterns() {
// matches key in form of: abc:def(>ijk)*
$this->keyword = '
[\w]+ # category prefix
: # colon
[\w.:#-]+ # keyword first part
(?: # zero or more keyword parts
> # part delimiter
[\w.:#-]+ # part
)*
';
// matches keys in form of: key( | key)*
$this->keywords = '
'.$this->keyword.' # at least one key
(?: # zero or more additional keys
\s* # space
\| # colon delimiter
\s* # space
'.$this->keyword.' # key
)*
';
// matches tag in form of: { keys @ "success" % "default" # "identifier" }
$this->pattern = '/
{
\s*
(?P<keywords>'.$this->keywords.')
\s*
(?: # success
@ # identifier
\s* # space
" # opening quote
(?P<success> # capture value
(?: # must contain
\\\\" # either escaped doublequote \"
| # or
[^"] # any non doublequote character
)* # zero or more times
)
" # closing quote
)?
\s*
(?: # default
% # identifier
\s* # space
" # opening quote
(?P<default> # capture value
(?: # must contain
\\\\" # either escaped doublequote \"
| # or
[^"] # any non doublequote character
)* # zero or more times
)
" # closing quote
)?
\s*
(?: # delimiter
\# # identifier
\s* # space
" # opening quote
(?P<delimiter> # capture value
(?: # must contain
\\\\" # either escaped doublequote \"
| # or
[^"] # any non doublequote character
)* # zero or more times
)
" # closing quote
)?
\s*
}
/x';
}
/////////////////////////////////////////////////////////////////////////////////////
// Settings
/////////////////////////////////////////////////////////////////////////////////////
public $prefix = 'image_metadata_cruncher';
/**
* Adds action links to the plugin
*
* @return updated plugin links
*/
public function plugin_action_links( $links, $file ) {
static $this_plugin;
if ( ! $this_plugin ) {
$this_plugin = plugin_basename( __FILE__ );
}
if ( $file == $this_plugin ) {
$url = esc_url( admin_url( "admin.php?page={$this->settings_slug}" ) );
$settings_link = "<a href=\"$url\">Settings</a>";
array_unshift( $links, $settings_link );
}
return $links;
}
/**
* Adds action links to the plugin row
*
* @return updated plugin links
*/
public function plugin_row_meta( $links, $file ) {
if ( $file == plugin_basename( __FILE__ ) ) {
$url = esc_url( admin_url( "admin.php?page={$this->settings_slug}" ) );
$links[] = "<a href=\"$url\">Settings</a>";
$links[] = "<a href=\"$this->donate_url\">Donate</a>";
}
return $links;
}
/////////////////////////////////////////////////////////////////////////////////////
// JavaScript and CSS
/////////////////////////////////////////////////////////////////////////////////////
function js_rangy_core() { wp_enqueue_script( "{$this->prefix}_rangy_core" ); }
function js_rangy_selectionsaverestore() { wp_enqueue_script( "{$this->prefix}_rangy_selectionsaverestore" ); }
function js() { wp_enqueue_script( "{$this->prefix}_script" ); }
function css() { wp_enqueue_style( "{$this->prefix}_style" ); }
/**
* Default plugin options
*/
public function defaults() {
add_option( $this->prefix, array(
'version' => $this->version,
'title' => '{ IPTC:Headline }',
'alt' => '',
'caption' => '',
'enable_highlighting' => 'enable',
'description' => '{ IPTC:Caption | EXIF:ImageDescription }',
'custom_meta' => array()
) );
}
/**
* Adds a section to the plugin admin page
*/
private function section( $id, $title ) {
add_settings_section(
"{$this->prefix}_section_{$id}", // section id
$title, // title
array( $this, "section_{$id}" ), // callback
"{$this->prefix}-section-{$id}" // page
);
}
/**
* Plugin initialization
*/
public function init() {
// register stylesheets and scripts for admin
wp_register_script( "{$this->prefix}_rangy_core", plugins_url( 'js/ext/rangy-core.js', __FILE__ ) );
wp_register_script( "{$this->prefix}_rangy_selectionsaverestore", plugins_url( 'js/ext/rangy-selectionsaverestore.js', __FILE__ ) );
wp_register_script( "{$this->prefix}_script", plugins_url( 'js/script.js', __FILE__ ) );
wp_register_style( "{$this->prefix}_style", plugins_url( 'style.css', __FILE__ ) );
///////////////////////////////////
// Sections
///////////////////////////////////
$this->section( 0, 'Tag Syntax Highlighting:' );
$this->section( 1, 'Media form fields:' );
$this->section( 2, 'Custom image meta tags:' );
$this->section( 3, 'Available metadata keywords:' );
$this->section( 4, 'How to Use Template Tags' );
$this->section( 5, 'About Image Metadata Cruncher:' );
///////////////////////////////////
// Options
///////////////////////////////////
// Title
// register a new setting...
register_setting(
"{$this->prefix}_title", // option group
$this->prefix, // option name
array( $this, 'sanitizer' ) // sanitizer
);
// ...and add it to a section
add_settings_field(
"{$this->prefix}_title", // field id
'Title:', // title
array( $this, 'title_cb' ), // callback
"{$this->prefix}-section-1", // section page
"{$this->prefix}_section_1" // section id
);
// Alternate text
register_setting(
"{$this->prefix}_alt", // option group
$this->prefix, // option name
array( $this, 'sanitizer' ) // sanitizer
);
add_settings_field(
"{$this->prefix}_alt", // field id
'Alternate text:', // title
array( $this, 'alt_cb' ), // callback
"{$this->prefix}-section-1", // section page
"{$this->prefix}_section_1" // section id
);
// Caption
register_setting(
"{$this->prefix}_caption", // option group
$this->prefix, // option name
array( $this, 'sanitizer') // sanitizer
);
add_settings_field(
"{$this->prefix}_caption", // field id
'Caption:', // title
array( $this, 'caption_cb' ), // callback
"{$this->prefix}-section-1", // section page
"{$this->prefix}_section_1" // section id
);
// Description
register_setting(
"{$this->prefix}_description", // option group
$this->prefix, // option name
array( $this, 'sanitizer' ) // sanitizer
);
add_settings_field(
"{$this->prefix}_description", // field id
'Description:', // title
array( $this, 'description_cb' ), // callback
"{$this->prefix}-section-1", // section page
"{$this->prefix}_section_1" // section id
);
}
/**
* Plugin options callback
*/
public function options() {
$page = add_plugins_page(
'Image Metadata Cruncher',
'Image Metadata Cruncher',
'manage_options',
"{$this->prefix}-options",
array( $this, 'options_cb' )
);
add_action( 'admin_print_scripts-' . $page, array( $this, 'js_rangy_core' ) );
add_action( 'admin_print_scripts-' . $page, array( $this, 'js_rangy_selectionsaverestore' ) );
add_action( 'admin_print_scripts-' . $page, array( $this, 'js' ) );
add_action( 'admin_print_styles-' . $page, array( $this, 'css' ) );
}
/**
* Options page callback
*/
public function options_cb() { ?>
<div id="metadata-cruncher" class="wrap metadata-cruncher">
<h2>Image Metadata Cruncher Options</h2>
<?php settings_errors(); ?>
<h2 class="nav-tab-wrapper">
<?php
if ( isset( $_GET['tab'] ) ) {
$active_tab = $_GET['tab'];
} else {
$active_tab = 'settings';
}
function active_tab( $value, $at ) {
if ( $at == $value ) {
echo 'nav-tab-active';
}
}
?>
<a href="?page=image_metadata_cruncher-options&tab=settings" class="nav-tab <?php active_tab( 'settings', $active_tab ); ?>">Settings</a>
<a href="?page=image_metadata_cruncher-options&tab=metadata" class="nav-tab <?php active_tab( 'metadata', $active_tab ); ?>">Available Metadata</a>
<a href="?page=image_metadata_cruncher-options&tab=usage" class="nav-tab <?php active_tab( 'usage', $active_tab ); ?>"><?php _e( 'How to Use Template Tags' ) ?></a>
<a href="?page=image_metadata_cruncher-options&tab=about" class="nav-tab <?php active_tab( 'about', $active_tab ); ?>">About</a>
</h2>
<?php if ( $active_tab == 'settings' ): ?>
<form action="options.php" method="post">
<?php
settings_fields( "{$this->prefix}_title" ); // renders hidden input fields
settings_fields( "{$this->prefix}_alt" ); // renders hidden input fields
do_settings_sections( "{$this->prefix}-section-0" );
do_settings_sections( "{$this->prefix}-section-1" );
do_settings_sections( "{$this->prefix}-section-2" );
submit_button();
?>
</form>
<?php elseif ( $active_tab == 'metadata' ): ?>
<?php do_settings_sections( "{$this->prefix}-section-3" ); ?>
<?php elseif ( $active_tab == 'usage' ): ?>
<?php do_settings_sections( "{$this->prefix}-section-4" ); ?>
<?php elseif ( $active_tab == 'about' ): ?>
<?php do_settings_sections( "{$this->prefix}-section-5" ); ?>
<?php endif ?>
</div>
<?php }
///////////////////////////////////
// Section callbacks
///////////////////////////////////
public function section_0() {
$options = get_option( $this->prefix );
if ( isset( $options['version'] ) && intval( $options['version'] ) > 1.0 ) {
//TODO: Move to defaults
// if the plugin has been updated from version 1.0 enable highlighting by default
$options['enable_highlighting'] = 'enable';
$options['version'] = $this->version;
update_option( $this->prefix, $options );
}
?>
<p>
The fancy syntax highlighting of template tags may in some cases cause strange caret/cursor behaviour.
If you encounter any of such problems, you can disable this feature here.
</p>
<input type="checkbox" value="enable" <?php checked( 'enable', $options['enable_highlighting'] ); ?> name="<?php echo $this->prefix; ?>[enable_highlighting]" id="enable-highlighting" />
<label for="highlighting">Enable highlighting</label>
<?php }
// media form fields
public function section_1() { ?>
<p>
Specify text templates with which should the media upload form be prepopulated with.
Use template tags like this <code>{ IPTC:Headline }</code> to place found metadata into the templates.
Template tags can be as simple as <code>{ EXIF:Model }</code> or more complex like
<code>{ EXIF:LensInfo>2 | EXIF:LensModel @ "Lens info is $" % "Lens info not found" # "; " }</code>.
</p>
<p>
Tags with invalid syntax will be ignored by the plugin and will apear
unchanged in the <em>Upload Media Form</em> fields.
For your better orientation valid template tags get highlighted as you type.
</p>
<p>
To find out more about the template tag syntax read the
<a href="?page=image_metadata_cruncher-options&tab=usage">How to Use Template Tags</a> section.
</p>
<?php }
// custom post metadata
public function section_2() { ?>
<?php $options = get_option( $this->prefix ); ?>
<p>Here you can specify your own meta fields that will be saved to the database with the uploaded image.</p>
<table id="custom-meta-list" class="widefat">
<colgroup>
<col class="col-name" />
<col class="col-template" />
<col class="col-delete" />
</colgroup>
<thead>
<th>Name</th>
<th>Template</th>
<th>Delete</th>
</thead>
<?php if ( isset( $options['custom_meta'] ) ) : ?>
<?php if ( is_array( $options['custom_meta'] ) ): ?>
<?php foreach ( $options['custom_meta'] as $key => $value ): ?>
<?php
$key = sanitize_text_field($key);
$value = sanitize_text_field($value);
?>
<tr>
<td><input type="text" class="name" value="<?php echo $key ?>" /></td>
<td>
<div class="highlighted ce" contenteditable="true"><?php echo $value ?></div>
<?php // used textarea because hidden input caused bugs when whitespace got converted to ?>
<textarea class="hidden-input template" name="<?php echo $this->prefix; ?>[custom_meta][<?php echo $key ?>]" ><?php echo $value ?></textarea>
</td>
<td><button class="button">Remove</button></td>
</tr>
<?php endforeach; ?>
<?php endif ?>
<?php endif ?>
</table>
<div>
<button id="add-custom-meta" class="button">Add New Field</button>
</div>
<?php }
// list of available metadata tags
public function section_3() { ?>
<p>
The <strong>Image Metadata Cruncher</strong> template tags are <strong>case insensitive</strong> and so are the metadata keywords.
Thus <code>EXIF:ImageHeight</code> is the same as <code>exif:imageheight</code> and <code>EXIF:IMAGEHEIGHT</code>.
</p>
<h2>SPECIAL:</h2>
<p>
The <code>ALL:php</code>, <code>ALL:json</code> and <code>ALL:jsonpp</code> keywords
return all the available information structured as nested arrays,
formatted according to the suffix after the colon <code>:</code>.
You can access the nested values using the <code>></code> greater than notation.
For example
<code>{ALL:php>iptc}</code>,
<code>{ALL:json>exif}</code>,
<code>{ALL:jsonpp>iptc>caption-abstract}</code>,
<code>{ALL:php>exif>computed}</code>,
<code>{ALL:json>exif>computed>ApertureFNumber}</code>,
<code>{ALL:jsonpp>exif>0xA432>3}</code> and so forth.
</p>
<div>
<table>
<tr>
<td class="tag-list special">
<span class="tag">
<span class="first">
<span class="prefix">ALL</span><span class="colon">:</span><span class="part">php</span>
</span>
</span>
</td>
<td>
Prints out all found metadata formated as PHP array.
</td>
</tr>
<tr>
<td class="tag-list special">
<span class="tag">
<span class="first">
<span class="prefix">ALL</span><span class="colon">:</span><span class="part">json</span>
</span>
</span>
</td>
<td>
Prints out all found metadata formated as JSON.
</td>
</tr>
<tr>
<td class="tag-list special">
<span class="tag">
<span class="first">
<span class="prefix">ALL</span><span class="colon">:</span><span class="part">jsonpp</span>
</span>
</span>