-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcore.php
1432 lines (1202 loc) · 48.2 KB
/
core.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
if( $_SERVER['SCRIPT_FILENAME'] == __FILE__ )
die( 'Access denied.' );
if( !class_exists( 'BasicGoogleMapsPlacemarks' ) )
{
/**
* A Wordpress plugin that adds a custom post type for placemarks and builds a Google Map with them
* @package BasicGoogleMapsPlacemarks
* @author Ian Dunn <[email protected]>
* @link http://wordpress.org/extend/plugins/basic-google-maps-placemarks/
*/
class BasicGoogleMapsPlacemarks
{
// Declare variables and constants
protected $settings, $options, $updatedOptions, $userMessageCount, $mapShortcodeCalled, $mapShortcodeCategories;
const VERSION = '1.10';
const PREFIX = 'bgmp_';
const POST_TYPE = 'bgmp';
const TAXONOMY = 'bgmp-category';
const ZOOM_MIN = 0;
const ZOOM_MAX = 21;
const DEBUG_MODE = false;
/**
* Constructor
* @author Ian Dunn <[email protected]>
*/
public function __construct()
{
add_action( 'init', array( $this, 'init' ), 8 ); // lower priority so that variables defined here will be available to BGMPSettings class and other init callbacks
add_action( 'init', array( $this, 'upgrade' ) );
add_action( 'init', array( $this, 'createPostType' ) );
add_action( 'init', array( $this, 'createCategoryTaxonomy' ) );
add_action( 'after_setup_theme', array( $this, 'addFeaturedImageSupport' ), 11 ); // @todo add note explaining why higher priority
add_action( 'admin_init', array( $this, 'addMetaBoxes' ) );
add_action( 'wp', array( $this, 'loadResources' ), 11 ); // @todo - should be wp_enqueue_scripts instead? // @todo add note explaining why higher priority
add_action( 'admin_enqueue_scripts', array( $this, 'loadResources' ), 11 );
add_action( 'wp_head', array( $this, 'outputHead' ) );
add_action( 'admin_notices', array( $this, 'printMessages' ) );
add_action( 'save_post', array( $this, 'saveCustomFields' ) );
add_action( 'wpmu_new_blog', array( $this, 'activateNewSite' ) );
add_action( 'shutdown', array( $this, 'shutdown' ) );
add_filter( 'parse_query', array( $this, 'sortAdminView' ) );
add_shortcode( 'bgmp-map', array( $this, 'mapShortcode') );
add_shortcode( 'bgmp-list', array( $this, 'listShortcode') );
register_activation_hook( dirname(__FILE__) . '/basic-google-maps-placemarks.php', array( $this, 'networkActivate') );
require_once( dirname(__FILE__) . '/settings.php' );
$this->settings = new BGMPSettings();
}
/**
* Performs various initialization functions
* @author Ian Dunn <[email protected]>
*/
public function init()
{
if( did_action( 'init' ) !== 1 )
return;
$defaultOptions = array( 'updates' => array(), 'errors' => array(), 'dbVersion' => '0' );
$this->options = array_merge( $defaultOptions, get_option( self::PREFIX . 'options', array() ) );
if( !is_array( $this->options ) )
$this->options = $defaultOptions;
if( !is_array( $this->options[ 'updates' ] ) )
$this->options[ 'updates' ] = array();
if( !is_array( $this->options[ 'errors' ] ) )
$this->options[ 'errors' ] = array();
$this->userMessageCount = array( 'updates' => count( $this->options[ 'updates' ] ), 'errors' => count( $this->options[ 'errors' ] ) );
$this->updatedOptions = false;
$this->mapShortcodeCalled = false;
$this->mapShortcodeCategories = null;
}
/**
* Getter method for instance of the BGMPSettings class, used for unit testing
* @author Ian Dunn <[email protected]>
*/
public function &getSettings()
{
return $this->settings;
}
/**
* Handles extra activation tasks for MultiSite installations
* @author Ian Dunn <[email protected]>
* @param bool $networkWide True if the activation was network-wide
*/
public function networkActivate( $networkWide )
{
global $wpdb, $wp_version;
if( function_exists( 'is_multisite' ) && is_multisite() )
{
// Enable image uploads so the 'Set Featured Image' meta box will be available
$mediaButtons = get_site_option( 'mu_media_buttons' );
if( version_compare( $wp_version, '3.3', "<=" ) && ( !array_key_exists( 'image', $mediaButtons ) || !$mediaButtons[ 'image' ] ) )
{
$mediaButtons[ 'image' ] = 1;
update_site_option( 'mu_media_buttons', $mediaButtons );
/*
@todo enqueueMessage() needs $this->options to be set, but as of v1.8 that doesn't happen until the init hook, which is after activation. It doesn't really matter anymore, though, because mu_media_buttons was removed in 3.3. http://core.trac.wordpress.org/ticket/17578
$this->enqueueMessage( sprintf(
__( '%s has enabled uploading images network-wide so that placemark icons can be set.', 'bgmp' ), // @todo - give more specific message, test. enqueue for network admin but not regular admins
BGMP_NAME
) );
*/
}
// Activate the plugin across the network if requested
if( $networkWide )
{
$blogs = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
foreach( $blogs as $b )
{
switch_to_blog( $b );
$this->singleActivate();
}
restore_current_blog();
}
else
$this->singleActivate();
}
else
$this->singleActivate();
}
/**
* Prepares a single blog to use the plugin
* @author Ian Dunn <[email protected]>
*/
protected function singleActivate()
{
// Save default settings
if( !get_option( self::PREFIX . 'map-width' ) )
add_option( self::PREFIX . 'map-width', 600 );
if( !get_option( self::PREFIX . 'map-height' ) )
add_option( self::PREFIX . 'map-height', 400 );
if( !get_option( self::PREFIX . 'map-address' ) )
add_option( self::PREFIX . 'map-address', __( 'Seattle', 'bgmp' ) );
if( !get_option( self::PREFIX . 'map-latitude' ) )
add_option( self::PREFIX . 'map-latitude', 47.6062095 );
if( !get_option( self::PREFIX . 'map-longitude' ) )
add_option( self::PREFIX . 'map-longitude', -122.3320708 );
if( !get_option( self::PREFIX . 'map-zoom' ) )
add_option( self::PREFIX . 'map-zoom', 7 );
if( !get_option( self::PREFIX . 'map-type' ) )
add_option( self::PREFIX . 'map-type', 'ROADMAP' );
if( !get_option( self::PREFIX . 'map-type-control' ) )
add_option( self::PREFIX . 'map-type-control', 'off' );
if( !get_option( self::PREFIX . 'map-navigation-control' ) )
add_option( self::PREFIX . 'map-navigation-control', 'DEFAULT' );
if( !get_option( self::PREFIX . 'map-info-window-width' ) )
add_option( self::PREFIX . 'map-info-window-width', 500 );
if( !get_option( self::PREFIX . 'marker-clustering' ) )
add_option( self::PREFIX . 'marker-clustering', '' );
if( !get_option( self::PREFIX . 'cluster-max-zoom' ) )
add_option( self::PREFIX . 'cluster-max-zoom', '7' );
if( !get_option( self::PREFIX . 'cluster-grid-size' ) )
add_option( self::PREFIX . 'cluster-grid-size', '40' );
if( !get_option( self::PREFIX . 'cluster-style' ) )
add_option( self::PREFIX . 'cluster-style', 'default' );
// @todo - this isn't DRY, same values in BGMPSettings::__construct() and upgrade()
}
/**
* Runs activation code on a new WPMS site when it's created
* @author Ian Dunn <[email protected]>
* @param int $blogID
*/
public function activateNewSite( $blogID )
{
if( did_action( 'wpmu_new_blog' ) !== 1 )
return;
switch_to_blog( $blogID );
$this->singleActivate();
restore_current_blog();
}
/**
* Checks if the plugin was recently updated and upgrades if necessary
* @author Ian Dunn <[email protected]>
*/
public function upgrade()
{
if( did_action( 'init' ) !== 1 )
return;
if( version_compare( $this->options[ 'dbVersion' ], self::VERSION, '==' ) )
return;
if( version_compare( $this->options[ 'dbVersion' ], '1.1', '<' ) )
{
// Populate new Address field from existing coordinate fields
$posts = get_posts( array( 'numberposts' => -1, 'post_type' => self::POST_TYPE ) );
if( $posts )
{
foreach( $posts as $p )
{
$address = get_post_meta( $p->ID, self::PREFIX . 'address', true );
$latitude = get_post_meta( $p->ID, self::PREFIX . 'latitude', true );
$longitude = get_post_meta( $p->ID, self::PREFIX . 'longitude', true );
if( empty($address) && !empty($latitude) && !empty($longitude) )
{
$address = $this->reverseGeocode( $latitude, $longitude );
if( $address )
update_post_meta( $p->ID, self::PREFIX . 'address', $address );
}
}
}
}
if( version_compare( $this->options[ 'dbVersion' ], '1.6', '<' ) )
{
// Add new options
add_option( self::PREFIX . 'map-type', 'ROADMAP' );
add_option( self::PREFIX . 'map-type-control', 'off' );
add_option( self::PREFIX . 'map-navigation-control', 'DEFAULT' );
// @todo - this isn't DRY, those default values appear in activate and settings->construct. should have single array to hold them all
}
if( version_compare( $this->options[ 'dbVersion' ], '1.9', '<' ) )
{
// Add new options
add_option( self::PREFIX . 'marker-clustering', '' );
add_option( self::PREFIX . 'cluster-max-zoom', '7' );
add_option( self::PREFIX . 'cluster-grid-size', '40' );
add_option( self::PREFIX . 'cluster-style', 'default' );
// @todo - this isn't DRY, those default values appear in activate and settings->construct. should have single array to hold them all
}
$this->options[ 'dbVersion'] = self::VERSION;
$this->updatedOptions = true;
// Clear WP Super Cache and W3 Total Cache
if( function_exists( 'wp_cache_clear_cache' ) )
wp_cache_clear_cache();
if( class_exists( 'W3_Plugin_TotalCacheAdmin' ) )
{
$w3TotalCache =& w3_instance('W3_Plugin_TotalCacheAdmin');
if( method_exists( $w3TotalCache, 'flush_all' ) )
$w3TotalCache->flush_all();
}
}
/**
* Adds featured image support
* @author Ian Dunn <[email protected]>
*/
public function addFeaturedImageSupport()
{
global $wp_version;
if( did_action( 'after_setup_theme' ) !== 1 )
return;
// We enabled image media buttons for MultiSite on activation, but the admin may have turned it back off
if( version_compare( $wp_version, '3.3', "<=" ) && is_admin() && function_exists( 'is_multisite' ) && is_multisite() )
{
// @todo this isn't DRY, similar code in networkActivate()
$mediaButtons = get_site_option( 'mu_media_buttons' );
if( !array_key_exists( 'image', $mediaButtons ) || !$mediaButtons[ 'image' ] )
{
$this->enqueueMessage( sprintf(
__( "%s requires the Images media button setting to be enabled in order to use custom icons on markers, but it's currently turned off. If you'd like to use custom icons you can enable it on the <a href=\"%s\">Network Settings</a> page, in the Upload Settings section.", 'bgmp' ),
BGMP_NAME,
network_admin_url() . 'settings.php'
), 'error' );
}
}
$supportedTypes = get_theme_support( 'post-thumbnails' );
if( $supportedTypes === false )
add_theme_support( 'post-thumbnails', array( self::POST_TYPE ) );
elseif( is_array( $supportedTypes ) )
{
$supportedTypes[0][] = self::POST_TYPE;
add_theme_support( 'post-thumbnails', $supportedTypes[0] );
}
}
/**
* Gets all of the shortcodes in the current post
* @author Ian Dunn <[email protected]>
* @param string $content
* @return mixed false | array
*/
protected function getShortcodes( $content )
{
$matches = array();
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches );
if( !is_array( $matches ) || !array_key_exists( 2, $matches ) )
return false;
return $matches;
}
/**
* Validates and cleans the map shortcode arguments
* @author Ian Dunn <[email protected]>
* @param array
* @return array
*/
protected function cleanMapShortcodeArguments( $arguments )
{
// @todo - not doing this in settings yet, but should. want to make sure it's DRY when you do.
// @todo - Any errors generated in there would stack up until admin loads page, then they'll all be displayed, include ones from geocode() etc. that's not great solution, but is there better way?
// maybe add a check to enqueuemessage() to make sure that messages doesn't already exist. that way there'd only be 1 of them. if do that, make sure to fix the bug where they're getting adding twice before, b/c this would mask that
// maybe call getMapShortcodeArguments() when saving post so they get immediate feedback about any errors in shortcode
// do something similar for list shortcode arguments?
global $post;
if( !is_array( $arguments ) )
return array();
// Placemark
if( isset( $arguments[ 'placemark' ] ) )
{
$pass = true;
$originalID = $arguments[ 'placemark' ];
// Check for valid placemark ID
if( !is_numeric( $arguments[ 'placemark' ] ) )
$pass = false;
$arguments[ 'placemark' ] = (int) $arguments[ 'placemark' ];
if( $arguments[ 'placemark' ] <= 0 )
$pass = false;
$placemark = get_post( $arguments[ 'placemark' ] );
if( !$placemark )
$pass = false;
if( !$pass )
{
$error = sprintf(
__( '%s shortcode error: %s is not a valid placemark ID.', 'bgmp' ),
BGMP_NAME,
is_scalar( $originalID ) ? (string) $originalID : gettype( $originalID )
);
}
// Check for valid coordinates
if( $pass )
{
$latitude = get_post_meta( $arguments[ 'placemark' ], self::PREFIX . 'latitude', true );
$longitude = get_post_meta( $arguments[ 'placemark' ], self::PREFIX . 'longitude', true );
$coordinates = $this->validateCoordinates( $latitude .','. $longitude );
if( $coordinates === false )
{
$pass = false;
$error = sprintf(
__( '%s shortcode error: %s does not have a valid address.', 'bgmp' ),
BGMP_NAME,
(string) $originalID
);
}
}
// Remove the option if it isn't a valid placemark
if( !$pass )
{
$this->enqueueMessage( $error, 'error' );
unset( $arguments[ 'placemark' ] );
}
}
// Categories
if( isset( $arguments[ 'categories' ] ) )
{
if( is_string( $arguments[ 'categories' ] ) )
$arguments[ 'categories' ] = explode( ',', $arguments[ 'categories' ] );
elseif( !is_array( $arguments[ 'categories' ] ) || empty( $arguments[ 'categories' ] ) )
unset( $arguments[ 'categories' ] );
if( isset( $arguments[ 'categories' ] ) && !empty( $arguments[ 'categories' ] ) )
{
foreach( $arguments[ 'categories' ] as $index => $term )
{
if( !term_exists( $term, self::TAXONOMY ) )
{
unset( $arguments[ 'categories' ][ $index ] ); // Note - This will leave holes in the key sequence, but it doesn't look like that's a problem with the way we're using it.
$this->enqueueMessage( sprintf(
__( '%s shortcode error: %s is not a valid category.', 'bgmp' ),
BGMP_NAME,
$term
), 'error' );
}
}
}
}
// Rename width and height keys to match internal ones. Using different ones in shortcode to make it easier for user.
if( isset( $arguments[ 'width' ] ) )
{
if( is_numeric( $arguments[ 'width' ] ) && $arguments[ 'width' ] > 0 )
$arguments[ 'mapWidth' ] = $arguments[ 'width' ];
else
{
$this->enqueueMessage( sprintf(
__( '%s shortcode error: %s is not a valid width.', 'bgmp' ),
BGMP_NAME,
$arguments[ 'width' ]
), 'error' );
}
unset( $arguments[ 'width' ] );
}
if( isset( $arguments[ 'height' ] ) && $arguments[ 'height' ] > 0 )
{
if( is_numeric( $arguments[ 'height' ] ) )
$arguments[ 'mapHeight' ] = $arguments[ 'height' ];
else
{
$this->enqueueMessage( sprintf(
__( '%s shortcode error: %s is not a valid height.', 'bgmp' ),
BGMP_NAME,
$arguments[ 'height' ]
), 'error' );
}
unset( $arguments[ 'height' ] );
}
// Center
if( isset( $arguments[ 'center' ] ) )
{
// Note: Google's API has a daily request limit, which could be a problem when geocoding map shortcode center address each time page loads. Users could get around that by using a caching plugin, though.
$coordinates = $this->geocode( $arguments[ 'center' ] );
if( $coordinates )
$arguments = array_merge( $arguments, $coordinates );
unset( $arguments[ 'center' ] );
}
// Zoom
if( isset( $arguments[ 'zoom' ] ) )
{
if( !is_numeric( $arguments[ 'zoom' ] ) || $arguments[ 'zoom' ] < self::ZOOM_MIN || $arguments[ 'zoom' ] > self::ZOOM_MAX )
{
$this->enqueueMessage( sprintf(
__( '%s shortcode error: %s is not a valid zoom level.', 'bgmp' ),
BGMP_NAME,
$arguments[ 'zoom' ]
), 'error' );
unset( $arguments[ 'zoom' ] );
}
}
// Type
if( isset( $arguments[ 'type' ] ) )
{
$arguments[ 'type' ] = strtoupper( $arguments[ 'type' ] );
if( !array_key_exists( $arguments[ 'type' ], $this->settings->mapTypes ) )
{
$this->enqueueMessage( sprintf(
__( '%s shortcode error: %s is not a valid map type.', 'bgmp' ),
BGMP_NAME,
$arguments[ 'type' ]
), 'error' );
unset( $arguments[ 'type' ] );
}
}
return apply_filters( self::PREFIX . 'clean-map-shortcode-arguments-return', $arguments );
}
/**
* Checks the current post to see if they contain the map shortcode
* @author Ian Dunn <[email protected]>
* @link http://wordpress.org/support/topic/plugin-basic-google-maps-placemarks-can-i-use-the-shortcode-on-any-php-without-assign-it-in-functionphp
* @return bool
*/
protected function mapShortcodeCalled()
{
global $post;
$this->mapShortcodeCalled = apply_filters( self::PREFIX .'mapShortcodeCalled', $this->mapShortcodeCalled ); // @todo - deprecated b/c not consistent w/ shortcode naming scheme. need a way to notify people
$this->mapShortcodeCalled = apply_filters( self::PREFIX .'map-shortcode-called', $this->mapShortcodeCalled );
if( $this->mapShortcodeCalled )
return true;
if( !$post ) // note: this needs to run after the above code, so that templates can call do_shortcode(...) from templates that don't have $post, like 404.php. See link in phpDoc @link for background.
return false;
$shortcodes = $this->getShortcodes( $post->post_content ); // note: don't use setup_postdata/get_the_content() in this instance -- http://lists.automattic.com/pipermail/wp-hackers/2013-January/045053.html
for( $i = 0; $i < count( $shortcodes[ 2 ] ); $i++ )
if( $shortcodes[ 2 ][ $i ] == 'bgmp-map' )
return true;
return false;
}
/**
* Load CSS and JavaScript files
* @author Ian Dunn <[email protected]>
*/
public function loadResources()
{
if( is_admin() )
{
if( did_action( 'admin_enqueue_scripts' ) !== 1 )
return;
}
else
{
if( did_action( 'wp' ) !== 1 )
return;
}
$googleMapsLanguage = apply_filters( self::PREFIX . 'map-language', '' );
if( $googleMapsLanguage )
$googleMapsLanguage = '&language=' . $googleMapsLanguage;
wp_register_script(
'googleMapsAPI',
'http'. ( is_ssl() ? 's' : '' ) .'://maps.google.com/maps/api/js?sensor=false' . $googleMapsLanguage,
array(),
false,
true
);
wp_register_script(
'markerClusterer',
plugins_url( 'includes/marker-clusterer/markerclusterer_packed.js', __FILE__ ),
array(),
'1.0',
true
);
wp_register_script(
'bgmp',
plugins_url( 'functions.js', __FILE__ ),
array( 'googleMapsAPI', 'jquery' ),
self::VERSION,
true
);
wp_register_style(
self::PREFIX .'style',
plugins_url( 'style.css', __FILE__ ),
false,
self::VERSION
);
$this->mapShortcodeCalled = $this->mapShortcodeCalled();
// Load front-end resources
if( !is_admin() && $this->mapShortcodeCalled )
{
wp_enqueue_script( 'googleMapsAPI' );
if( $this->settings->markerClustering )
wp_enqueue_script( 'markerClusterer' );
wp_enqueue_script( 'bgmp' );
}
if( $this->mapShortcodeCalled )
wp_enqueue_style( self::PREFIX . 'style' );
// Load meta box resources for settings page
if( isset( $_GET[ 'page' ] ) && $_GET[ 'page' ] == self::PREFIX . 'settings' ) // @todo better way than $_GET ?
{
wp_enqueue_style( self::PREFIX . 'style' );
wp_enqueue_script( 'dashboard' );
}
}
/**
* Outputs elements in the <head> section of the front-end
* @author Ian Dunn <[email protected]>
*/
public function outputHead()
{
if( did_action( 'wp_head' ) !== 1 )
return;
if( $this->mapShortcodeCalled )
{
do_action( BasicGoogleMapsPlacemarks::PREFIX . 'head-before' );
require_once( dirname(__FILE__) . '/views/front-end-head.php' );
do_action( BasicGoogleMapsPlacemarks::PREFIX . 'head-after' );
}
}
/**
* Registers the custom post type
* @author Ian Dunn <[email protected]>
*/
public function createPostType()
{
if( did_action( 'init' ) !== 1 )
return;
if( !post_type_exists( self::POST_TYPE ) )
{
$labels = array(
'name' => __( 'Placemarks', 'bgmp' ),
'singular_name' => __( 'Placemark', 'bgmp' ),
'add_new' => __( 'Add New', 'bgmp' ),
'add_new_item' => __( 'Add New Placemark', 'bgmp' ),
'edit' => __( 'Edit', 'bgmp' ),
'edit_item' => __( 'Edit Placemark', 'bgmp' ),
'new_item' => __( 'New Placemark', 'bgmp' ),
'view' => __( 'View Placemark', 'bgmp' ),
'view_item' => __( 'View Placemark', 'bgmp' ),
'search_items' => __( 'Search Placemarks', 'bgmp' ),
'not_found' => __( 'No Placemarks found', 'bgmp' ),
'not_found_in_trash' => __( 'No Placemarks found in Trash', 'bgmp' ),
'parent' => __( 'Parent Placemark', 'bgmp' )
);
$postTypeParams = array(
'labels' => $labels,
'singular_label' => __( 'Placemarks', 'bgmp' ),
'public' => true,
'menu_position' => 20,
'hierarchical' => false,
'capability_type' => 'post',
'rewrite' => array( 'slug' => 'placemarks', 'with_front' => false ),
'query_var' => true,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'revisions' )
);
register_post_type(
self::POST_TYPE,
apply_filters( self::PREFIX . 'post-type-params', $postTypeParams )
);
}
}
/**
* Registers the category taxonomy
* @author Ian Dunn <[email protected]>
*/
public function createCategoryTaxonomy()
{
if( did_action( 'init' ) !== 1 )
return;
if( !taxonomy_exists( self::TAXONOMY ) )
{
$taxonomyParams = array(
'label' => __( 'Category', 'bgmp' ),
'labels' => array( 'name' => __( 'Categories', 'bgmp' ), 'singular_name' => __( 'Category', 'bgmp' ) ),
'hierarchical' => true,
'rewrite' => array( 'slug' => self::TAXONOMY ),
'update_count_callback' => '_update_post_term_count'
);
register_taxonomy(
self::TAXONOMY,
self::POST_TYPE,
apply_filters( self::PREFIX . 'category-taxonomy-params', $taxonomyParams )
);
}
}
/**
* Sorts the posts by the title in the admin view posts screen
* @author Ian Dunn <[email protected]>
*/
function sortAdminView( $query )
{
global $pagenow;
if( is_admin() && $pagenow == 'edit.php' && array_key_exists( 'post_type', $_GET ) && $_GET[ 'post_type' ] == self::POST_TYPE )
{
$query->query_vars[ 'order' ] = apply_filters( self::PREFIX . 'admin-sort-order', 'ASC' );
$query->query_vars[ 'orderby' ] = apply_filters( self::PREFIX . 'admin-sort-orderby', 'title' );
// @todo - should just have a filter on $query, or don't even need one at all, since they can filter $query directly?
}
}
/**
* Adds meta boxes for the custom post type
* @author Ian Dunn <[email protected]>
*/
public function addMetaBoxes()
{
if( did_action( 'admin_init' ) !== 1 )
return;
add_meta_box(
self::PREFIX . 'placemark-address',
__( 'Placemark Address', 'bgmp' ),
array( $this, 'markupAddressFields' ),
self::POST_TYPE,
'normal',
'high'
);
add_meta_box(
self::PREFIX . 'placemark-zIndex',
__( 'Stacking Order', 'bgmp' ),
array( $this, 'markupZIndexField' ),
self::POST_TYPE,
'side',
'low'
);
}
/**
* Outputs the markup for the address fields
* @author Ian Dunn <[email protected]>
*/
public function markupAddressFields()
{
global $post;
$address = get_post_meta( $post->ID, self::PREFIX . 'address', true );
$latitude = get_post_meta( $post->ID, self::PREFIX . 'latitude', true );
$longitude = get_post_meta( $post->ID, self::PREFIX . 'longitude', true );
$showGeocodeResults = ( $address && !self::validateCoordinates( $address ) && $latitude && $longitude ) ? true : false;
$showGeocodeError = ( $address && ( !$latitude || !$longitude ) ) ? true : false;
require_once( dirname(__FILE__) . '/views/meta-address.php' );
}
/**
* Outputs the markup for the stacking order field
* @author Ian Dunn <[email protected]>
*/
public function markupZIndexField()
{
global $post;
$zIndex = get_post_meta( $post->ID, self::PREFIX . 'zIndex', true );
if( filter_var( $zIndex, FILTER_VALIDATE_INT ) === FALSE )
$zIndex = 0;
require_once( dirname(__FILE__) . '/views/meta-z-index.php' );
}
/**
* Saves values of the the custom post type's extra fields
* @param int $postID
* @author Ian Dunn <[email protected]>
*/
public function saveCustomFields( $postID )
{
if( did_action( 'save_post' ) !== 1 )
return;
global $post;
$coordinates = false;
$ignoredActions = array( 'trash', 'untrash', 'restore' );
// Check preconditions
if( isset( $_GET[ 'action' ] ) && in_array( $_GET[ 'action' ], $ignoredActions ) )
return;
if( !$post || $post->post_type != self::POST_TYPE || !current_user_can( 'edit_posts' ) )
return;
if( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || $post->post_status == 'auto-draft' )
return;
// Save address
update_post_meta( $post->ID, self::PREFIX . 'address', $_POST[ self::PREFIX . 'address' ] );
if( $_POST[ self::PREFIX . 'address'] )
$coordinates = $this->geocode( $_POST[ self::PREFIX . 'address' ] );
if( $coordinates )
{
update_post_meta( $post->ID, self::PREFIX . 'latitude', $coordinates[ 'latitude' ] );
update_post_meta( $post->ID, self::PREFIX . 'longitude', $coordinates[ 'longitude' ] );
}
else
{
update_post_meta( $post->ID, self::PREFIX . 'latitude', '' );
update_post_meta( $post->ID, self::PREFIX . 'longitude', '' );
}
// Save z-index
if( filter_var( $_POST[ self::PREFIX . 'zIndex'], FILTER_VALIDATE_INT ) === FALSE )
{
update_post_meta( $post->ID, self::PREFIX . 'zIndex', 0 );
$this->enqueueMessage( __( 'The stacking order has to be an integer.', 'bgmp' ), 'error' );
}
else
update_post_meta( $post->ID, self::PREFIX . 'zIndex', $_POST[ self::PREFIX . 'zIndex'] );
}
/**
* Geocodes an address
* @param string $address
* @author Ian Dunn <[email protected]>
* @return mixed
*/
public function geocode( $address )
{
// @todo - this should be static, or better yet, broken out into an Address class
// Bypass geocoding if already have valid coordinates
$coordinates = self::validateCoordinates( $address );
if( is_array( $coordinates ) )
return $coordinates;
// Geocode address and handle errors
$geocodeResponse = wp_remote_get( 'http://maps.googleapis.com/maps/api/geocode/json?address='. str_replace( ' ', '+', $address ) .'&sensor=false' );
// @todo - esc_url() on address?
if( is_wp_error( $geocodeResponse ) )
{
$this->enqueueMessage( sprintf(
__( '%s geocode error: %s', 'bgmp' ),
BGMP_NAME,
implode( '<br />', $geocodeResponse->get_error_messages() )
), 'error' );
return false;
}
// Check response code
if( !isset( $geocodeResponse[ 'response' ][ 'code' ] ) || !isset( $geocodeResponse[ 'response' ][ 'message' ] ) )
{
$this->enqueueMessage( sprintf(
__( '%s geocode error: Response code not present', 'bgmp' ),
BGMP_NAME
), 'error' );
return false;
}
elseif( $geocodeResponse[ 'response' ][ 'code' ] != 200 )
{
/*
@todo - strip content inside <style> tag. regex inappropriate, but DOMDocument doesn't exist on dev server, but does on most?. would have to wrap this in an if( class_exists() )...
$responseHTML = new DOMDocument();
$responseHTML->loadHTML( $geocodeResponse[ 'body' ] );
// nordmalize it b/c doesn't have <body> tag inside?
$this->describe( $responseHTML->saveHTML() );
*/
$this->enqueueMessage( sprintf(
__( '<p>%s geocode error: %d %s</p> <p>Response: %s</p>', 'bgmp' ),
BGMP_NAME,
$geocodeResponse[ 'response' ][ 'code' ],
$geocodeResponse[ 'response' ][ 'message' ],
strip_tags( $geocodeResponse[ 'body' ] )
), 'error' );
return false;
}
// Decode response and handle errors
$coordinates = json_decode( $geocodeResponse['body'] );
if( function_exists( 'json_last_error' ) && json_last_error() != JSON_ERROR_NONE )
{
// @todo - Once PHP 5.3+ is more widely adopted, remove the function_exists() check here and just bump the PHP requirement to 5.3
$this->enqueueMessage( sprintf( __( '%s geocode error: Response was not formatted in JSON.', 'bgmp' ), BGMP_NAME ), 'error' );
return false;
}
if( isset( $coordinates->status ) && $coordinates->status == 'REQUEST_DENIED' )
{
$this->enqueueMessage( sprintf( __( '%s geocode error: Request Denied.', 'bgmp' ), BGMP_NAME ), 'error' );
return false;
}
if( !isset( $coordinates->results ) || empty( $coordinates->results ) )
{
$this->enqueueMessage( __( "That address couldn't be geocoded, please make sure that it's correct.", 'bgmp' ), "error" );
$this->enqueueMessage(
__( "Geocode response:", 'bgmp' ) . ' <pre>' . print_r( $coordinates, true ) . '</pre>',
"error"
);
return false;
}
return array( 'latitude' => $coordinates->results[ 0 ]->geometry->location->lat, 'longitude' => $coordinates->results[ 0 ]->geometry->location->lng );
}
/**
* Checks if a given string represents a valid set of geographic coordinates
* Expects latitude/longitude notation, not minutes/seconds
*
* @author Ian Dunn <[email protected]>
* @param string $coordinates
* @return mixed false if any of the tests fails | an array with 'latitude' and 'longitude' keys/value pairs if all of the tests succeed
*/
public static function validateCoordinates( $coordinates )
{
// @todo - some languages swap the roles of the commas and decimal point. this assumes english.
$coordinates = str_replace( ' ', '', $coordinates );
if( !$coordinates )
return false;
if( substr_count( $coordinates, ',' ) != 1 )
return false;
$coordinates = explode( ',', $coordinates );
$latitude = $coordinates[ 0 ];
$longitude = $coordinates[ 1 ];
if( !is_numeric( $latitude ) || $latitude < -90 || $latitude > 90 )
return false;
if( !is_numeric( $longitude ) || $longitude < -180 || $longitude > 180 )
return false;
return array( 'latitude' => $latitude, 'longitude' => $longitude );
}
/**
* Reverse-geocodes a set of coordinates
* Google's API has a daily request limit, but this is only called during upgrades from 1.0, so that shouldn't ever be a problem.
*
* @param string $latitude
* @param string $longitude
* @author Ian Dunn <[email protected]>
*/
protected function reverseGeocode( $latitude, $longitude )
{
$geocodeResponse = wp_remote_get( 'http://maps.googleapis.com/maps/api/geocode/json?latlng='. $latitude .','. $longitude .'&sensor=false' );
$address = json_decode( $geocodeResponse['body'] );
if( is_wp_error( $geocodeResponse ) || empty( $address->results ) )
return false;
else
return $address->results[ 0 ]->formatted_address;
}
/**
* Defines the [bgmp-map] shortcode
* @author Ian Dunn <[email protected]>
* @param array $attributes Array of parameters automatically passed in by WordPress
* return string The output of the shortcode
*/
public function mapShortcode( $attributes )
{
if( !wp_script_is( 'googleMapsAPI', 'queue' ) || !wp_script_is( 'bgmp', 'queue' ) || !wp_style_is( self::PREFIX .'style', 'queue' ) )
{
$error = sprintf(
__( '<p class="error">%s error: JavaScript and/or CSS files aren\'t loaded. If you\'re using do_shortcode() you need to add a filter to your theme first. See <a href="%s">the FAQ</a> for details.</p>', 'bgmp' ),
BGMP_NAME,
'http://wordpress.org/extend/plugins/basic-google-maps-placemarks/faq/'
);
// @todo maybe change this to use views/message.php
return $error;
}
if( isset( $attributes[ 'categories' ] ) )
$attributes[ 'categories' ] = apply_filters( self::PREFIX . 'mapShortcodeCategories', $attributes[ 'categories' ] ); // @todo - deprecated b/c 1.9 output bgmpdata in post; can now just set args in do_shortcode() . also not consistent w/ shortcode naming scheme and have filter for all arguments now. need a way to notify people
$attributes = apply_filters( self::PREFIX . 'map-shortcode-arguments', $attributes ); // @todo - deprecated b/c 1.9 output bgmpdata in post...
$attributes = $this->cleanMapShortcodeArguments( $attributes );