-
Notifications
You must be signed in to change notification settings - Fork 16
/
geo-mashup-db.php
2187 lines (1944 loc) · 76 KB
/
geo-mashup-db.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
/**
* Geo Mashup Data Access
*
* @package GeoMashup
*/
// Init at load time - just adds hooks
GeoMashupDB::init();
/**
* Static class to provide a namespace for Geo Mashup data functions.
*
* @since 1.2
* @package GeoMashup
*/
class GeoMashupDB {
/**
* Current installed database version.
*
* @since 1.4
* @var string
*/
private static $installed_version = null;
/**
* Flag for objects that have geodata fields copied to.
* Key $meta_type-$object_id, value true.
*
* @since 1.4
* @var array
*/
private static $copied_to_geodata = array();
/**
* Meta keys used to store geodata
*
* @since 1.4
* @var array
*/
private static $geodata_keys = array( 'geo_latitude', 'geo_longitude', 'geo_address' );
/**
* The last geocode error, or empty if no error.
* @var WP_Error
*/
public static $geocode_error = array();
/**
* WordPress action to set up data-related WordPress hooks.
*
* @since 1.4
*/
public static function init() {
global $geo_mashup_options;
// Enable the geo_mashup_query var
add_filter( 'query_vars', array( 'GeoMashupDB', 'query_vars' ) );
add_filter( 'posts_fields', array( 'GeoMashupDB', 'posts_fields' ), 10, 2 );
add_filter( 'posts_join', array( 'GeoMashupDB', 'posts_join' ), 10, 2 );
add_filter( 'posts_where', array( 'GeoMashupDB', 'posts_where' ), 10, 2 );
add_action( 'parse_query', array( 'GeoMashupDB', 'parse_query' ) );
// Some caching plugins don't implement this
if ( function_exists( 'wp_cache_add_global_groups' ) )
wp_cache_add_global_groups( array( 'geo_mashup_object_locations', 'geo_mashup_locations' ) );
// Avoid orphans
add_action( 'delete_post', array( 'GeoMashupDB', 'delete_post' ) );
add_action( 'delete_comment', array( 'GeoMashupDB', 'delete_comment' ) );
add_action( 'delete_user', array( 'GeoMashupDB', 'delete_user' ) );
if ( 'true' == $geo_mashup_options->get( 'overall', 'copy_geodata' ) or '' != $geo_mashup_options->get( 'overall', 'import_custom_field' ) )
self::add_geodata_sync_hooks();
}
/**
* Add hooks to synchronize Geo Mashup ojbect locations with WordPress geodata.
*
* @since 1.4
*/
public static function add_geodata_sync_hooks() {
add_filter( 'update_post_metadata', array( 'GeoMashupDB', 'filter_update_post_metadata' ), 10, 5 );
add_action( 'added_post_meta', array( 'GeoMashupDB', 'action_added_post_meta' ), 10, 4 );
add_action( 'updated_post_meta', array( 'GeoMashupDB', 'action_added_post_meta' ), 10, 4 );
add_filter( 'update_user_metadata', array( 'GeoMashupDB', 'filter_update_user_metadata' ), 10, 5 );
add_action( 'added_user_meta', array( 'GeoMashupDB', 'action_added_user_meta' ), 10, 4 );
add_action( 'updated_user_meta', array( 'GeoMashupDB', 'action_added_user_meta' ), 10, 4 );
add_filter( 'update_comment_metadata', array( 'GeoMashupDB', 'filter_update_comment_metadata' ), 10, 5 );
add_action( 'added_comment_meta', array( 'GeoMashupDB', 'action_added_comment_meta' ), 10, 4 );
add_action( 'updated_comment_meta', array( 'GeoMashupDB', 'action_added_comment_meta' ), 10, 4 );
// AJAX calls use a slightly different hook - triksy!
add_action( 'added_postmeta', array( 'GeoMashupDB', 'action_added_post_meta' ), 10, 4 );
add_action( 'updated_postmeta', array( 'GeoMashupDB', 'action_added_post_meta' ), 10, 4 );
add_action( 'geo_mashup_added_object_location', array( 'GeoMashupDB', 'copy_to_geodata' ), 10, 4 );
add_action( 'geo_mashup_updated_object_location', array( 'GeoMashupDB', 'copy_to_geodata' ), 10, 4 );
}
/**
* Remove hooks to synchronize Geo Mashup ojbect locations with WordPress geodata.
*
* @since 1.4
*/
public static function remove_geodata_sync_hooks() {
remove_filter( 'update_post_metadata', array( 'GeoMashupDB', 'filter_update_post_metadata' ), 10, 5 );
remove_action( 'added_post_meta', array( 'GeoMashupDB', 'action_added_post_meta' ), 10, 4 );
remove_action( 'updated_post_meta', array( 'GeoMashupDB', 'action_added_post_meta' ), 10, 4 );
remove_filter( 'update_user_metadata', array( 'GeoMashupDB', 'filter_update_user_metadata' ), 10, 5 );
remove_action( 'added_user_meta', array( 'GeoMashupDB', 'action_added_user_meta' ), 10, 4 );
remove_action( 'updated_user_meta', array( 'GeoMashupDB', 'action_added_user_meta' ), 10, 4 );
remove_filter( 'update_comment_metadata', array( 'GeoMashupDB', 'filter_update_comment_metadata' ), 10, 5 );
remove_action( 'added_comment_meta', array( 'GeoMashupDB', 'action_added_comment_meta' ), 10, 4 );
remove_action( 'updated_comment_meta', array( 'GeoMashupDB', 'action_added_comment_meta' ), 10, 4 );
// AJAX calls use a slightly different hook - triksy!
remove_action( 'added_postmeta', array( 'GeoMashupDB', 'action_added_post_meta' ), 10, 4 );
remove_action( 'updated_postmeta', array( 'GeoMashupDB', 'action_added_post_meta' ), 10, 4 );
remove_action( 'geo_mashup_added_object_location', array( 'GeoMashupDB', 'copy_to_geodata' ), 10, 4 );
remove_action( 'geo_mashup_updated_object_location', array( 'GeoMashupDB', 'copy_to_geodata' ), 10, 4 );
}
/**
* WordPress action to update Geo Mashup post location when geodata custom fields are updated.
*
* @since 1.4
*/
public static function action_added_post_meta( $meta_id, $post_id, $meta_key, $meta_value ) {
self::copy_from_geodata( 'post', $meta_id, $post_id, $meta_key, $meta_value );
}
/**
* WordPress action to update Geo Mashup user location when geodata custom fields are updated.
*
* @since 1.4
*/
public static function action_added_user_meta( $meta_id, $user_id, $meta_key, $meta_value ) {
self::copy_from_geodata( 'user', $meta_id, $user_id, $meta_key, $meta_value );
}
/**
* WordPress action to update Geo Mashup comment location when geodata custom fields are updated.
*
* @since 1.4
*/
public static function action_added_comment_meta( $meta_id, $comment_id, $meta_key, $meta_value ) {
self::copy_from_geodata( 'comment', $meta_id, $comment_id, $meta_key, $meta_value );
}
/**
* WordPress filter to prevent updates to geodata fields we've already updated.
*
* @since 1.4
*/
public static function filter_update_post_metadata( $ok, $object_id, $meta_key, $meta_value, $prev_value ) {
if ( !in_array( $meta_key, self::$geodata_keys ) )
return $ok;
if ( isset( self::$copied_to_geodata['post-' . $object_id] ) )
return false;
else
return $ok;
}
/**
* WordPress filter to prevent updates to geodata fields we've already updated.
*
* @since 1.4
*/
public static function filter_update_user_metadata( $ok, $object_id, $meta_key, $meta_value, $prev_value ) {
if ( !in_array( $meta_key, self::$geodata_keys ) )
return $ok;
if ( isset( self::$copied_to_geodata['user-' . $object_id] ) )
return false;
else
return $ok;
}
/**
* WordPress filter to prevent updates to geodata fields we've already updated.
*
* @since 1.4
*/
public static function filter_update_comment_metadata( $ok, $object_id, $meta_key, $meta_value, $prev_value ) {
if ( !in_array( $meta_key, self::$geodata_keys ) )
return $ok;
if ( isset( self::$copied_to_geodata['comment-' . $object_id] ) )
return false;
else
return $ok;
}
/**
* Create a Geo Mashup object location from WordPress geodata.
*
* @since 1.4
* @see http://codex.wordpress.org/Geodata
*/
private static function copy_from_geodata( $meta_type, $meta_id, $object_id, $meta_key, $meta_value ) {
global $geo_mashup_options, $wpdb;
// Do nothing if meta_key is not a known location field
$location_keys = array();
$is_copy_geodata_on = ( 'true' === $geo_mashup_options->get( 'overall', 'copy_geodata' ) );
$copy_imported_geodata = false;
if ( $is_copy_geodata_on ) {
$location_keys = array_merge( $location_keys, array( 'geo_latitude', 'geo_longitude', 'geo_lat_lng' ) );
}
$import_custom_keys = preg_split( '/\s*,\s*/', trim( $geo_mashup_options->get( 'overall', 'import_custom_field' ) ) );
$location_keys = array_merge( $location_keys, $import_custom_keys );
if ( ! in_array( $meta_key, $location_keys ) )
return;
$existing_location = self::get_object_location( $meta_type, $object_id );
$location = array();
// Do nothing unless both latitude and longitude exist for the object
if ( 'geo_lat_lng' == $meta_key ) {
$lat_lng = preg_split( '/\s*[, ]\s*/', trim( $meta_value ) );
if ( 2 != count( $lat_lng ) ) {
return;
}
$location['lat'] = $lat_lng[0];
$location['lng'] = $lat_lng[1];
} else if ( 'geo_latitude' == $meta_key ) {
$location['lat'] = $meta_value;
$lng = get_metadata( $meta_type, $object_id, 'geo_longitude', true );
if ( empty( $lng ) )
return;
$location['lng'] = $lng;
} else if ( 'geo_longitude' == $meta_key ) {
$location['lng'] = $meta_value;
$lat = get_metadata( $meta_type, $object_id, 'geo_latitude', true );
if ( empty( $lat ) )
return;
$location['lat'] = $lat;
} else if ( in_array( $meta_key, $import_custom_keys ) ) {
$lat_lng = preg_split( '/\s*[, ]\s*/', trim( $meta_value ) );
if ( count( $lat_lng ) == 2 and is_numeric( $lat_lng[0] ) and is_numeric( $lat_lng[1] ) ) {
$location['lat'] = $lat_lng[0];
$location['lng'] = $lat_lng[1];
} else if ( !empty( $meta_value ) ) {
$geocode_values = array();
foreach( $import_custom_keys as $import_custom_key ) {
if ( $meta_key == $import_custom_key ) {
$geocode_values[] = $meta_value;
} else {
// All keys must have a value - do nothing if not
if ( !metadata_exists( $meta_type, $object_id, $import_custom_key ) )
return;
$geocode_values[] = get_metadata( $meta_type, $object_id, $import_custom_key, true );
}
}
$location = self::blank_location( ARRAY_A );
self::geocode( implode( ',', $geocode_values ), $location );
if ( self::$geocode_error ) {
update_metadata( $meta_type, $object_id, 'geocoding_error', self::$geocode_error->get_error_message() );
return;
}
if ( $is_copy_geodata_on ) {
$copy_imported_geodata = true;
}
}
}
// Do nothing if the location already exists
if ( !empty( $existing_location ) ) {
$epsilon = 0.00001;
if ( abs( $location['lat'] - $existing_location->lat ) < $epsilon and abs( $location['lng'] - $existing_location->lng ) < $epsilon )
return;
}
// Save the location, attempt reverse geocoding
self::remove_geodata_sync_hooks();
// Use geo date if it exists
$geo_date = get_metadata( $meta_type, $object_id, 'geo_date', true );
$location_id = self::set_object_location( $meta_type, $object_id, $location, null, $geo_date );
if ( $copy_imported_geodata ) {
self::copy_to_geodata( $meta_type, $object_id, $geo_date, $location_id );
}
self::add_geodata_sync_hooks();
}
/**
* Update object geodata if needed.
*
* @since 1.4
*
* @param string $meta_type 'post','user','comment'
* @param int $object_id
* @param string $geo_date
* @param int $location_id The location to copy from.
*/
public static function copy_to_geodata( $meta_type, $object_id, $geo_date, $location_id ) {
$geo_latitude = get_metadata( $meta_type, $object_id, 'geo_latitude', true );
$geo_longitude = get_metadata( $meta_type, $object_id, 'geo_longitude', true );
$existing_object_location = self::get_object_location( $meta_type, $object_id );
// Do nothing if the geodata already exists
if ( $geo_latitude and $geo_longitude ) {
$epsilon = 0.00001;
if ( abs( $geo_latitude - $existing_object_location->lat ) < $epsilon and abs( $geo_longitude - $existing_object_location->lng ) < $epsilon )
return;
}
self::remove_geodata_sync_hooks();
update_metadata( $meta_type, $object_id, 'geo_latitude', $existing_object_location->lat );
update_metadata( $meta_type, $object_id, 'geo_longitude', $existing_object_location->lng );
update_metadata( $meta_type, $object_id, 'geo_address', $existing_object_location->address );
update_metadata( $meta_type, $object_id, 'geo_date', $existing_object_location->geo_date );
self::$copied_to_geodata[$meta_type . '-' . $object_id] = true;
self::add_geodata_sync_hooks();
}
/**
* Set the installed database version.
*
* @since 1.4
*
* @param string $new_version
*/
private static function set_installed_version( $new_version ) {
self::$installed_version = $new_version;
update_option( 'geo_mashup_db_version', $new_version );
}
/**
* Get the installed database version.
*
* @since 1.2
*
* @return string The installed database version.
*/
public static function installed_version() {
if ( is_null( self::$installed_version ) ) {
self::$installed_version = get_option( 'geo_mashup_db_version' );
}
return self::$installed_version;
}
/**
* Get or set storage information for an object name.
*
* Potentially you could add storage information for a new kind of object:
* <code>
* GeoMashupDB::object_storage( 'foo', array(
* 'table' => $wpdb->prefix . 'foos',
* 'id_column' => 'foo_id',
* 'label_column' => 'foo_display_name',
* 'sort' => 'foo_order ASC' )
* );
* </code>
* Would add the necessary information for a custom table of foo objects. By convention the
* object name is the singular form of the table name without a prefix.
*
* @since 1.3
*
* @param string $object_name A type of object to be stored, default is 'post', 'user', and 'comment'.
* @param array $new_storage If provided, adds or replaces the storage information for the object name.
* @return array|bool The storage information array, or false if not found.
*/
public static function object_storage( $object_name, $new_storage = null ) {
global $wpdb;
static $objects = null;
if ( is_null( $objects ) ) {
$objects = array(
'post' => array(
'table' => $wpdb->posts,
'id_column' => 'ID',
'label_column' => 'post_title',
'date_column' => 'post_date',
'sort' => 'post_status ASC, geo_date DESC' ),
'user' => array(
'table' => $wpdb->users,
'id_column' => 'ID',
'label_column' => 'display_name',
'date_column' => 'user_registered',
'sort' => 'display_name ASC' ),
'comment' => array(
'table' => $wpdb->comments,
'id_column' => 'comment_ID',
'label_column' => 'comment_author',
'date_column' => 'comment_date',
'sort' => 'comment_date DESC' )
);
}
if ( !empty( $new_storage ) ) {
$objects[$object_name] = $new_storage;
}
return ( isset( $objects[$object_name] ) ) ? $objects[$object_name] : false;
}
/**
* Return a conventional object name given a table name.
*
* @since 1.7
*
* @param string $table
* @return string
*/
public static function table_to_object_name( $table ) {
global $wpdb;
$object_name = str_replace( $wpdb->prefix, '', $table );
if ( 's' === substr( $object_name, -1 ) ) {
$object_name = substr( $object_name, 0, strlen( $object_name ) - 1 );
}
return $object_name;
}
/**
* Toggle joining of WordPress queries with Geo Mashup tables.
*
* Use the public wrapper GeoMashup::join_post_queries()
*
* @since 1.3
* @deprecated Use the geo_mashup_query query var
*
* @param bool $new_value If provided, replaces the current active state.
* @return bool The current state.
*/
public static function join_post_queries( $new_value = null) {
static $active = null;
if ( is_bool( $new_value ) ) {
_deprecated_function( __METHOD__, '1.7', 'the geo_mashup_query query var' );
$active = $new_value;
}
return $active;
}
/**
* WordPress filter to add Geo Mashup public query variables.
*
* query_vars {@link http://codex.wordpress.org/Plugin_API/Filter_Reference filter}
* called by Wordpress.
*
* @since 1.3
*/
public static function query_vars( $public_query_vars ) {
if ( self::join_post_queries() ) {
$public_query_vars[] = 'geo_mashup_date';
$public_query_vars[] = 'geo_mashup_saved_name';
$public_query_vars[] = 'geo_mashup_country_code';
$public_query_vars[] = 'geo_mashup_postal_code';
$public_query_vars[] = 'geo_mashup_admin_code';
$public_query_vars[] = 'geo_mashup_locality';
}
return $public_query_vars;
}
/**
* Set or get custom data associated with a WP_Query object.
*
* @since 1.7
*
* @param WP_Query $query
* @param string $key Optional - return all data for the query if missing.
* @param mixed $value Optional - set or overwrite data for the key if present.
* @return mixed Extension data if present.
*/
private static function query_extension( $query, $key = null, $value = null ) {
static $extensions = array();
$hash = spl_object_hash( $query );
if ( is_null( $key ) )
return $extensions;
if ( !isset( $extensions[$hash] ) )
$extensions[$hash] = array();
if ( !is_null( $value ) )
$extensions[$hash][$key] = $value;
else if ( !isset( $extensions[$hash][$key] ) )
return null;
return $extensions[$hash][$key];
}
/**
* WordPress action to capture custom orderby field before it is removed.
*
* parse_query {@link http://codex.wordpress.org/Plugin_API/Action_Reference action}
* called by WordPress.
*
* @since 1.3
* @access private
* @static
*/
public static function parse_query( $query ) {
global $wpdb;
if ( !self::join_post_queries() )
return;
// Check for geo mashup fields in the orderby before they are removed as invalid
switch ( $query->query_vars['orderby'] ) {
case 'geo_mashup_date':
self::query_extension( $query, 'orderby', $wpdb->prefix . 'geo_mashup_location_relationships.geo_date' );
break;
case 'geo_mashup_locality':
self::query_extension( $query, 'orderby', $wpdb->prefix . 'geo_mashup_locations.locality_name' );
break;
case 'geo_mashup_saved_name':
self::query_extension( $query, 'orderby', $wpdb->prefix . 'geo_mashup_locations.saved_name' );
break;
case 'geo_mashup_country_code':
self::query_extension( $query, 'orderby', $wpdb->prefix . 'geo_mashup_locations.country_code' );
break;
case 'geo_mashup_admin_code':
self::query_extension( $query, 'orderby', $wpdb->prefix . 'geo_mashup_locations.admin_code' );
break;
case 'geo_mashup_postal_code':
self::query_extension( $query, 'orderby', $wpdb->prefix . 'geo_mashup_locations.postal_code' );
break;
}
}
/**
* WordPress filter to add Geo Mashup fields to WordPress post queries.
*
* posts_fields {@link http://codex.wordpress.org/Plugin_API/Filter_Reference filter}
* called by WordPress.
*
* @since 1.3
*/
public static function posts_fields( $fields, $query ) {
global $wpdb;
if ( self::join_post_queries() ) {
$fields .= ',' . $wpdb->prefix . 'geo_mashup_location_relationships.geo_date' .
',' . $wpdb->prefix . 'geo_mashup_locations.*';
}
return $fields;
}
/**
* WordPress filter to join Geo Mashup tables to WordPress post queries.
*
* posts_join {@link http://codex.wordpress.org/Plugin_API/Filter_Reference filter}
* called by WordPress.
*
* @since 1.3
*/
public static function posts_join( $join, $query ) {
global $wpdb;
if ( self::join_post_queries() ) {
$gmlr = $wpdb->prefix . 'geo_mashup_location_relationships';
$gml = $wpdb->prefix . 'geo_mashup_locations';
$join .= " INNER JOIN $gmlr ON ($gmlr.object_name = 'post' AND $gmlr.object_id = $wpdb->posts.ID)" .
" INNER JOIN $gml ON ($gml.id = $gmlr.location_id) ";
}
return $join;
}
/**
* WordPress filter to incorporate geo mashup query vars in WordPress post queries.
*
* posts_where {@link http://codex.wordpress.org/Plugin_API/Filter_Reference filter}
* called by WordPress.
*
* @since 1.3
*/
public static function posts_where( $where, $query ) {
global $wpdb;
if ( !self::join_post_queries() )
return $where;
$gmlr = $wpdb->prefix . 'geo_mashup_location_relationships';
$gml = $wpdb->prefix . 'geo_mashup_locations';
$geo_date = get_query_var( 'geo_mashup_date' );
if ( $geo_date ) {
$where .= $wpdb->prepare( " AND $gmlr.geo_date = %s ", $geo_date );
}
$saved_name = get_query_var( 'geo_mashup_saved_name' );
if ( $saved_name ) {
$where .= $wpdb->prepare( " AND $gml.saved_name = %s ", $saved_name );
}
$locality = get_query_var( 'geo_mashup_locality' );
if ( $locality ) {
$where .= $wpdb->prepare( " AND $gml.locality_name = %s ", $locality );
}
$country_code = get_query_var( 'geo_mashup_country_code' );
if ( $country_code ) {
$where .= $wpdb->prepare( " AND $gml.country_code = %s ", $country_code );
}
$admin_code = get_query_var( 'geo_mashup_admin_code' );
if ( $admin_code ) {
$where .= $wpdb->prepare( " AND $gml.admin_code = %s ", $admin_code );
}
$postal_code = get_query_var( 'geo_mashup_postal_code' );
if ( $postal_code ) {
$where .= $wpdb->prepare( " AND $gml.postal_code = %s ", $postal_code );
}
return $where;
}
/**
* Append to the activation log.
*
* Add a message and optionally write the activation log.
* Needs to be written before the end of the request or it will not be saved.
*
* @since 1.4
*
* @param string $message The message to append.
* @param boolean $write Whether to save the log.
* @return string The current log.
*/
public static function activation_log( $message = null, $write = false ) {
static $log = null;
if ( is_null( $log ) ) {
$log = get_option( 'geo_mashup_activation_log' );
}
if ( ! is_null( $message ) ) {
$log .= "\n" . $message;
}
if ( $write ) {
update_option( 'geo_mashup_activation_log', $log );
}
return $log;
}
/**
* Install or update Geo Mashup tables.
*
* @uses GeoMashupDB::activation_log()
* @since 1.2
*/
public static function install() {
global $wpdb, $geo_mashup_options;
self::activation_log( date( 'r' ) . ' ' . __( 'Activating Geo Mashup', 'GeoMashup' ) );
$location_table_name = $wpdb->prefix . 'geo_mashup_locations';
$relationships_table_name = $wpdb->prefix . 'geo_mashup_location_relationships';
$administrative_names_table_name = $wpdb->prefix . 'geo_mashup_administrative_names';
$charset_collate = '';
if ( ! empty($wpdb->charset) )
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty($wpdb->collate) )
$charset_collate .= " COLLATE $wpdb->collate";
if ( self::installed_version() != GEO_MASHUP_DB_VERSION ) {
$sql = "
CREATE TABLE $location_table_name (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
lat FLOAT(11,7) NOT NULL,
lng FLOAT(11,7) NOT NULL,
address TINYTEXT NULL,
saved_name VARCHAR(100) NULL,
geoname TINYTEXT NULL,
postal_code TINYTEXT NULL,
country_code VARCHAR(2) NULL,
admin_code VARCHAR(20) NULL,
sub_admin_code VARCHAR(80) NULL,
locality_name TINYTEXT NULL,
PRIMARY KEY (id),
UNIQUE KEY saved_name (saved_name),
UNIQUE KEY latlng (lat,lng),
KEY lat (lat),
KEY lng (lng)
) $charset_collate;
CREATE TABLE $relationships_table_name (
object_name VARCHAR(80) NOT NULL,
object_id BIGINT(20) NOT NULL,
location_id MEDIUMINT(9) NOT NULL,
geo_date DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (object_name,object_id,location_id),
KEY object_name (object_name,object_id),
KEY object_date_key (object_name,geo_date)
) $charset_collate;
CREATE TABLE $administrative_names_table_name (
country_code VARCHAR(2) NOT NULL,
admin_code VARCHAR(20) NOT NULL,
isolanguage VARCHAR(7) NOT NULL,
geoname_id MEDIUMINT(9) NULL,
name VARCHAR(200) NOT NULL,
PRIMARY KEY (country_code,admin_code,isolanguage)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
// Capture error messages - some are ok
$old_show_errors = $wpdb->show_errors( true );
ob_start();
dbDelta( $sql );
$errors = ob_get_contents();
ob_end_clean();
$have_create_errors = preg_match( '/^(CREATE|INSERT|UPDATE)/m', $errors );
$have_bad_alter_errors = preg_match( '/^ALTER TABLE.*ADD (?!KEY|PRIMARY KEY|UNIQUE KEY)/m', $errors );
$have_bad_errors = $have_create_errors || $have_bad_alter_errors;
if ( $errors && $have_bad_errors ) {
// Any errors other than duplicate or multiple primary key could be trouble
self::activation_log( $errors, true );
} else {
self::convert_prior_locations();
self::set_installed_version( GEO_MASHUP_DB_VERSION );
}
$wpdb->show_errors( $old_show_errors );
}
if ( self::installed_version() == GEO_MASHUP_DB_VERSION ) {
if ( 'true' == $geo_mashup_options->get( 'overall', 'copy_geodata' ) )
self::duplicate_geodata();
self::activation_log( __( 'Geo Mashup database is up to date.', 'GeoMashup' ), true );
return true;
} else {
self::activation_log( __( 'Geo Mashup database upgrade failed.', 'GeoMashup' ), true );
return false;
}
}
/**
* Try to get a language-sensitive place administrative name.
*
* First look in the names cached in the database, then query geonames.org for it.
* If a name can't be found for the requested language, a default name is returned,
* usually in the local language. If nothing can be found, returns NULL.
*
* @since 1.4
*
* @param string $country_code Two-character ISO country code.
* @param string $admin_code Code for the administrative area within the country, or NULL to get the country name.
* @param string $language Language code, defaults to the WordPress locale language.
* @return string|null Place name in the appropriate language, or if not available in the default language.
*/
public static function get_administrative_name( $country_code, $admin_code = null, $language = '' ) {
$language = self::primary_language_code( $language );
$name = GeoMashupDB::get_cached_administrative_name( $country_code, $admin_code, $language );
if ( empty( $name ) ) {
// Look it up with Geonames
if ( !class_exists( 'GeoMashupHttpGeocoder' ) )
include_once( path_join( GEO_MASHUP_DIR_PATH, 'geo-mashup-geocoders.php' ) );
$geocoder = new GeoMashupGeonamesGeocoder();
$name = $geocoder->get_administrative_name( $country_code, $admin_code );
if ( is_wp_error( $name ) )
$name = null;
}
return $name;
}
/**
* Look in the database for a cached administrative name.
*
* @since 1.2
*
* @param string $country_code Two-character ISO country code.
* @param string $admin_code Code for the administrative area within the country, or NULL to get the country name.
* @param string $language Language code, defaults to the WordPress locale language.
* @return string|null Place name or NULL.
*/
private static function get_cached_administrative_name( $country_code, $admin_code = '', $language = '' ) {
global $wpdb;
$language = self::primary_language_code( $language );
$select_string = "SELECT name
FROM {$wpdb->prefix}geo_mashup_administrative_names
WHERE " .
$wpdb->prepare( 'isolanguage = %s AND country_code = %s AND admin_code = %s', $language, $country_code, $admin_code );
return $wpdb->get_var( $select_string );
}
/**
* Trim a locale or browser accepted languages string down to the 2 or 3 character
* primary language code.
*
* @since 1.2
*
* @param string $language Local or language code string, NULL for blog locale.
* @return string Two (rarely three?) character language code.
*/
public static function primary_language_code( $language = null ) {
if ( empty( $language ) ) {
$language = get_locale( );
}
if ( strlen( $language ) > 3 ) {
if ( ctype_alpha( $language[2] ) ) {
$language = substr( $language, 0, 3 );
} else {
$language = substr( $language, 0, 2 );
}
}
return $language;
}
/**
* Try to fill in coordinates and other fields of a location from a textual
* location search.
*
* Multiple geocoding services may be used. Google services are only used
* if the default map provider is Google.
*
* @since 1.3
*
* @param mixed $query The search string.
* @param array $location The location array to geocode, modified.
* @param string $language
* @return bool Whether a lookup succeeded.
*/
public static function geocode( $query, &$location, $language = '' ) {
global $geo_mashup_options;
if ( empty( $location ) ) {
$location = self::blank_location();
} else if ( !is_array( $location ) and !is_object( $location ) ) {
return false;
}
$status = false;
if ( !class_exists( 'GeoMashupHttpGeocoder' ) )
include_once( path_join( GEO_MASHUP_DIR_PATH, 'geo-mashup-geocoders.php' ) );
// Try GeoCoding services (google, nominatim, geonames) until one gives an answer
$results = array();
if ( $geo_mashup_options->get( 'overall', 'google_server_key' ) ) {
// Only try the google service if a google server key is present
$google_geocoder = new GeoMashupGoogleGeocoder( array( 'language' => $language ) );
$results = $google_geocoder->geocode( $query );
}
if ( is_wp_error( $results ) or empty( $results ) ) {
self::$geocode_error = $results;
$nominatim_geocoder = new GeoMashupNominatimGeocoder( array( 'language' => $language ) );
$results = $nominatim_geocoder->geocode( $query );
}
if ( is_wp_error( $results ) or empty( $results ) ) {
self::$geocode_error = $results;
$geonames_geocoder = new GeoMashupGeonamesGeocoder( array( 'language' => $language ) );
$results = $geonames_geocoder->geocode( $query );
}
if ( is_wp_error( $results ) or empty( $results ) ) {
self::$geocode_error = $results;
} else {
self::fill_empty_location_fields( $location, $results[0] );
$status = true;
}
return $status;
}
/**
* Check a location for empty fields.
*
* @since 1.4
*
* @param array $location The location to check.
* @param array $fields The fields to check.
* @return bool Whether any of the specified fields are empty.
*/
public static function are_any_location_fields_empty( $location, $fields = null ) {
if ( ! is_array( $location ) ) {
$location = (array)$location;
}
if ( is_null( $fields ) ) {
$fields = array_keys( $location );
}
foreach( $fields as $field ) {
if ( empty( $location[$field] ) ) {
return true;
}
}
return false;
}
/**
* Copy empty fields in one location array from another.
*
* @since 1.4
*
* @param array $primary Location to copy to, modified.
* @param array $secondary Location to copy from.
*/
private static function fill_empty_location_fields( &$primary, $secondary ) {
$secondary = (array)$secondary;
foreach( $primary as $field => $value ) {
if ( empty( $value ) and !empty( $secondary[$field] ) ) {
if ( is_object( $primary ) )
$primary->$field = $secondary[$field];
else
$primary[$field] = $secondary[$field];
}
}
}
/**
* Add missing location fields, and update country and admin codes with
* authoritative Geonames values.
*
* @since 1.3
*
* @param array $location The location to geocode, modified.
* @param string $language Optional ISO language code.
* @return bool Success.
*/
private static function reverse_geocode_location( &$location, $language = '' ) {
// Coordinates are required
if ( self::are_any_location_fields_empty( $location, array( 'lat', 'lng' ) ) )
return false;
// Don't bother unless there are missing geocodable fields
$geocodable_fields = array( 'country_code', 'admin_code', 'address', 'locality_name', 'postal_code' );
$have_empties = self::are_any_location_fields_empty( $location, $geocodable_fields );
if ( ! $have_empties )
return false;
$status = false;
if ( !class_exists( 'GeoMashupHttpGeocoder' ) )
include_once( path_join( GEO_MASHUP_DIR_PATH, 'geo-mashup-geocoders.php' ) );
$geonames_geocoder = new GeoMashupGeonamesGeocoder();
$geonames_results = $geonames_geocoder->reverse_geocode( $location['lat'], $location['lng'] );
if ( is_wp_error( $geonames_results ) or empty( $geonames_results ) ) {
self::$geocode_error = $geonames_results;
} else {
if ( !empty( $geonames_results[0]->admin_code ) )
$location['admin_code'] = $geonames_results[0]->admin_code;
if ( !empty( $geonames_results[0]->country_code ) )
$location['country_code'] = $geonames_results[0]->country_code;
self::fill_empty_location_fields( $location, (array)($geonames_results[0]) );
$status = true;
}
$have_empties = self::are_any_location_fields_empty( $location, $geocodable_fields );
$alternate_geocoder = self::make_alternate_reverse_geocoder();
if ( $have_empties and $alternate_geocoder ) {
$next_results = $alternate_geocoder->reverse_geocode( $location['lat'], $location['lng'] );
if ( is_wp_error( $next_results ) or empty( $next_results ) )
self::$geocode_error = $next_results;
else
self::fill_empty_location_fields( $location, (array)($next_results[0]) );
$status = true;
}
return $status;
}
private static function make_alternate_reverse_geocoder() {
global $geo_mashup_options;
// Choose a geocoding service based on the default API in use
if ( $geo_mashup_options->get( 'overall', 'google_server_key' ) ) {
return new GeoMashupGoogleGeocoder();
} else if ( 'openlayers' == $geo_mashup_options->get( 'overall', 'map_api' ) ) {
return new GeoMashupNominatimGeocoder();
}
return null;
}
/**
* Try to reverse-geocode all locations with relevant missing data.
*
* Used by the options page. Tries to comply with the PHP maximum execution
* time, and delay requests if Google sends a 604.
*
* @since 1.3
* @return string An HTML log of the actions performed.
*/
public static function bulk_reverse_geocode() {
global $wpdb;
$log = date( 'r' ) . '<br/>';
$select_string = 'SELECT * ' .
"FROM {$wpdb->prefix}geo_mashup_locations ".
"WHERE country_code IS NULL ".
"OR admin_code IS NULL " .
"OR address IS NULL " .
"OR locality_name IS NULL " .
"OR postal_code IS NULL ";
$locations = $wpdb->get_results( $select_string, ARRAY_A );
if ( empty( $locations ) ) {
$log .= __( 'No locations found with missing address fields.', 'GeoMashup' ) . '<br/>';
return $log;
}
$log .= __( 'Locations to geocode: ', 'GeoMashup' ) . count( $locations ) . '<br />';
$time_limit = ini_get( 'max_execution_time' );
if ( empty( $time_limit ) || !is_numeric( $time_limit ) ) {
$time_limit = 270;
} else {
$time_limit -= ( $time_limit / 10 );