-
Notifications
You must be signed in to change notification settings - Fork 11
/
bgeo-data.php
913 lines (769 loc) · 25.2 KB
/
bgeo-data.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
<?php
/*
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_urban_areas_landscan.geojson --namekeys=name_conve --woetypes=7 --offset=0 --limit=1100
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_urban_areas_landscan.geojson --namekeys=name_conve --woetypes=7 --offset=1100 --limit=1100
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_urban_areas_landscan.geojson --namekeys=name_conve --woetypes=7 --offset=2200 --limit=1100
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_urban_areas_landscan.geojson --namekeys=name_conve --woetypes=7 --offset=3300 --limit=1100
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_urban_areas_landscan.geojson --namekeys=name_conve --woetypes=7 --offset=4400 --limit=1100
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_urban_areas_landscan.geojson --namekeys=name_conve --woetypes=7 --offset=5500 --limit=1100
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_parks_and_protected_lands_area.geojson --namekeys=unit_name,unit_type --woetypes=13,16,20
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_geography_marine_polys.geojson --namekeys=name --woetypes=15,37,38
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_lakes.geojson --namekeys=name,featurecla,name_alt --woetypes=15,37,38
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_admin_1_states_provinces_lakes_shp.geojson --namekeys=name,admin,name_alt,name_local --woetypes=8 --offset=0 --limit=1400
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_admin_1_states_provinces_lakes_shp.geojson --namekeys=name,admin,name_alt,name_local --woetypes=8 --offset=1400 --limit=1400
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_admin_1_states_provinces_lakes_shp.geojson --namekeys=name,admin,name_alt,name_local --woetypes=8 --offset=2800 --limit=1400
wp --url=bgeo.me --require=./bgeo-data.php bgeodata simplify_and_correlate naturalearthdata/ne_10m_admin_0_countries_lakes.geojson --namekeys=admin,sovereignt --woetypes=12
*/
class bGeo_Data extends WP_CLI_Command
{
const VERBOSE = 0;
public function count_features( $args, $assoc_args )
{
if ( empty( $args ) )
{
WP_CLI::error( 'No input file was specified.' );
return;
}
// attempt to read the source file$
$source = json_decode( file_get_contents( $args[0] ) );
WP_CLI::success( count( $source->features ) . ' features in ' . $args[0] );
}
public function name_features( $args, $assoc_args )
{
if ( empty( $args ) )
{
WP_CLI::error( 'No input file was specified.' );
return;
}
if ( ! is_array( $assoc_args ) )
{
$assoc_args = array();
}
$assoc_args['source'] = $args[0];
$args = (object) array_intersect_key( $assoc_args, array(
'source' => TRUE,
'namekeys' => TRUE,
) );
if ( ! isset( $args->source, $args->namekeys ) )
{
WP_CLI::error( 'Input file and --namekeys values are required.' );
return;
}
$args->namekeys = array_map( 'trim', explode( ',', $args->namekeys ) );
if ( empty( $args->namekeys ) )
{
WP_CLI::error( '--namekeys arg has no parsed values' );
return;
}
// attempt to read the source file$
$source = json_decode( file_get_contents( $args->source ) );
// iterate through the source, separate features
foreach ( $source->features as $k => $feature )
{
$feature_name = implode( ', ' , array_intersect_key( (array) $feature->properties, array_flip( $args->namekeys ) ) );
$geometry = bgeo()->new_geometry( $feature, 'json', TRUE );
$feature_name .= ' ' . self::centroid( $geometry )->latlon;
WP_CLI::line( $k . ': ' . $feature_name );
}
WP_CLI::success( count( $source->features ) . ' features in ' . $args->source );
}
public function simplify_and_correlate( $args, $assoc_args )
{
if ( empty( $args ) )
{
WP_CLI::error( 'No input file was specified.' );
return;
}
if ( ! is_array( $assoc_args ) )
{
$assoc_args = array();
}
$assoc_args['source'] = $args[0];
$args = (object) array_intersect_key( $assoc_args, array(
'source' => TRUE,
'namekeys' => TRUE,
'woetypes' => TRUE,
'offset' => TRUE,
'limit' => TRUE,
) );
if ( ! isset( $args->source, $args->namekeys, $args->woetypes ) )
{
WP_CLI::error( 'Input file, --namekeys, and --woetypes values are required.' );
return;
}
$args->namekeys = array_map( 'trim', explode( ',', $args->namekeys ) );
$args->woetypes = wp_parse_id_list( $args->woetypes );
if ( empty( $args->namekeys ) )
{
WP_CLI::error( '--namekeys arg has no parsed values' );
return;
}
if ( empty( $args->woetypes ) )
{
WP_CLI::error( '--woetypes arg has no parsed values' );
return;
}
$error = (object) array(
'matched' => 0,
'unmatched' => 0,
'unmatched_list' => array(),
'inserted' => 0,
'notinserted' => 0,
'notinserted_list' => array(),
);
// attempt to read the source file
$source = json_decode( file_get_contents( $args->source ) );
// sanity check that read
if ( ! is_object( $source ) )
{
$error->text = 'can\'t json_decode() or read source file from ' . $args->source;
return $error;
}
if ( isset( $args->offset ) || isset( $args->limit ) )
{
// both are set
if ( isset( $args->offset, $args->limit ) )
{
$source->features = array_slice( $source->features, $args->offset, $args->limit );
}
// just the offset is set
elseif ( isset( $args->offset ) )
{
$source->features = array_slice( $source->features, $args->offset );
$args->limit = 0;
}
// just the limit is set
else
{
$source->features = array_slice( $source->features, 0, $args->limit );
$args->offset = 0;
}
}
// iterate through the source, separate features
foreach ( $source->features as $k => $feature )
{
//print_r( $feature->properties );
// iterate through the name keys, adding pieces until the search returns a result that works, hopefully
$geometry = bgeo()->new_geometry( $feature, 'json', TRUE );
if ( ! is_object( $geometry ) )
{
self::log( array(
'source' => basename( $args->source ),
'status' => 'Can\'t load geometry from feature.',
'item' => "$search_name (feature #" . ( $k + $args->offset ) . ")",
) );
$error->unmatched++;
$error->unmatched_list[] = ( $k + $args->offset ) . ' in ' . $args->source;
WP_CLI::warning( "Failed to load geometry from feature " . ( $k + $args->offset ) . " in $args->source" );
continue;
}
$geometry = self::simplify( $geometry );
$search_name = self::centroid( $geometry )->latlon;
foreach ( $args->namekeys as $name_key )
{
$search_name .= ' ' . str_replace( '|', ' ', preg_replace( '/[0-9]*/', '', $feature->properties->$name_key ) );
WP_CLI::line( "Searching for $search_name" );
$locations = bgeo()->admin()->posts()->locationlookup( $search_name );
if ( ! is_array( $locations ) )
{
self::log( array(
'source' => basename( $args->source ),
'status' => 'API returned no results for search.',
'item' => "$search_name (feature #" . ( $k + $args->offset ) . ")",
) );
$error->unmatched++;
$error->unmatched_list[] = ( $k + $args->offset ) . ' in ' . $args->source;
WP_CLI::warning( "No locations found for $search_name, feature " . ( $k + $args->offset ) . " in $args->source" );
continue;
}
//print_r( $feature->properties );
// the location lookup can return multiple locations, inspect each
foreach ( $locations as $location )
{
$match = self::match( $location, $geometry, $args->woetypes );
if ( $match )
{
if ( self::VERBOSE )
{
WP_CLI::line( "Matched" );
}
else
{
echo '.';
}
self::log( array(
'source' => basename( $args->source ),
'status' => 'Success! Matched feature to API result.',
'item' => "$search_name (feature #" . ( $k + $args->offset ) . ", WOEID: $location->api_id)",
) );
$error->matched++;
//insert this geo
if ( ! self::insert_or_merge_geo(
$location,
$geometry
) )
{
$error->notinserted++;
$error->notinserted_list[] = $search_name;
}
else
{
$error->inserted++;
}
break 2;
}
WP_CLI::warning( "NOT Matched" );
}
}
if ( ! $match )
{
self::log( array(
'source' => basename( $args->source ),
'status' => 'No API results matched feature.',
'item' => "$search_name (feature #" . ( $k + $args->offset ) . ")",
) );
$error->unmatched++;
$error->unmatched_list[] = $search_name;
}
WP_CLI::line( "\n\n" );
}
// return any errors
WP_CLI::success( 'Done! ' . print_r( $error, TRUE ) );
}
private function match( $location, $geometry, $woe_types, $recursion = FALSE )
{
if (
! is_object( $location ) ||
is_wp_error( $location )
)
{
WP_CLI::warning( "Location NOT valid" );
return FALSE;
}
// is the centroid of this looked up location inside the source geography envelope?
if ( ! self::contains( $geometry, (object) array( 'lon' => $location->point_lon, 'lat' => $location->point_lat ) ) )
{
WP_CLI::warning( "Location NOT coincident" );
return FALSE;
}
// is the found location a valid WOE type?
if ( in_array( (int) $location->api_raw->placeTypeName->code, $woe_types ) )
{
if ( self::VERBOSE )
{
WP_CLI::line( "WOEID type is valid" );
}
return $location;
}
elseif ( ! $recursion )
{
WP_CLI::warning( "WOEID type is NOT valid ( {$location->api_raw->placeTypeName->code} ), recursing into belongtos" );
foreach ( $location->belongtos as $belongto )
{
if ( 'woeid' != $belongto->api )
{
continue;
}
return self::match( bgeo()->new_geo_by_woeid( $belongto->api_id ), $geometry, $woe_types, TRUE );
}
}
// this is a failed response
// successful responses are handled above
return FALSE;
}
private function sanitize_belongtos( $woeids )
{
if ( ! is_array( $woeids ) )
{
return array();
}
rsort( $woeids );
return array_filter( array_unique( (array) $woeids ) );
}
private function insert_or_merge_geo( $location, $geometry, $recursion = FALSE )
{
if ( 'woeid' != $location->api )
{
WP_CLI::warning( "insert_or_merge_geo requires a WOEID, returning without action" );
return FALSE;
}
self::get_lock( $location->api_id );
// the data to insert or merge
$data = (object) array(
'woeid' => $location->api_id,
'woe_raw' => $location->api_raw,
'woe_belongtos' => self::sanitize_belongtos( wp_list_pluck( $location->belongtos, 'api_id' ) ),
'bgeo_geometry' => $geometry,
);
// check for an existing record for this WOEID
$existing = self::get_row( $location->api_id );
if ( ! $existing )
{
// insert if this is the first try at this WOEID
WP_CLI::line( "Inserting new row for WOEID $location->api_id" );
self::insert_row( $data );
}
else
{
WP_CLI::line( "Updating existing row for WOEID $location->api_id" );
// we've been here before, merge the parts and update
// attempt to union the geometry
try
{
// @TODO: this has started fatalling with exceptions.
// Using the try-catch-reduce workaround for now, but why did the errors just appear?
$unioned_geometry = $existing->bgeo_geometry->union( $data->bgeo_geometry );
$existing->bgeo_geometry = $unioned_geometry;
}
catch ( Exception $e )
{
WP_CLI::warning( "Caught exception while trying to union() geometries near " . __FILE__ . ':' . __LINE__ . '.' );
WP_CLI::warning( 'Attempted to union ' . $data->bgeo_geometry->geometryType() . ' into ' . $existing->bgeo_geometry->geometryType() . '.' );
$existing->bgeo_geometry = self::reduce( array( $existing->bgeo_geometry, $data->bgeo_geometry ) );
WP_CLI::warning( 'Instead reduced to ' . $existing->bgeo_geometry->geometryType() . ' with ' . count( (array) $existing->bgeo_geometry->getComponents() ) . ' components.' );
// attempt to merge the hack-unioned geometry
try
{
$unioned_geometry = self::merge_into_one( $existing->bgeo_geometry );
$existing->bgeo_geometry = $unioned_geometry;
WP_CLI::warning( 'Finally merged to ' . $existing->bgeo_geometry->geometryType() . ' with ' . count( (array) $existing->bgeo_geometry->getComponents() ) . ' components.' );
}
catch ( Exception $e )
{
WP_CLI::warning( "Caught exception while trying to merge_into_one() near " . __FILE__ . ':' . __LINE__ . '.' );
}
}
$existing->woe_belongtos = self::sanitize_belongtos( array_merge( (array) $existing->woe_belongtos, (array) $data->woe_belongtos ) );
self::insert_row( $existing );
}
self::release_lock( $location->api_id );
if ( ! $recursion )
{
foreach ( $data->woe_belongtos as $woeid )
{
WP_CLI::line( "recursing belongtos with $woeid" );
self::insert_or_merge_geo( bgeo()->new_geo_by_woeid( $woeid ), $geometry, TRUE );
}
}
// @TODO how to communicate success or failure back, maybe?
return TRUE;
}
private function get_table_name()
{
global $wpdb;
return $wpdb->prefix . 'bgeo_data';
}
private function maybe_create_table()
{
static $did_create_table = FALSE;
if ( ! $did_create_table )
{
self::create_table();
$did_create_table = TRUE;
}
}//end maybe_create_table
private function create_table()
{
global $wpdb;
if ( ! empty( $wpdb->charset ) )
{
$charset_collate = 'DEFAULT CHARACTER SET '. $wpdb->charset;
}
if ( ! empty( $wpdb->collate ) )
{
$charset_collate .= ' COLLATE '. $wpdb->collate;
}
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
WP_CLI::warning( 'Don\'t be surprised by error messages about duplicate primary keys. Other errors might be an issue, though...' );
return dbDelta( "
CREATE TABLE " . self::get_table_name() . " (
`woeid` int(16) unsigned NOT NULL,
`woe_raw` text NOT NULL,
`woe_belongtos` text NOT NULL,
`bgeo_geometry` geometrycollection NOT NULL,
PRIMARY KEY (`woeid`)
) ENGINE=MyISAM $charset_collate;
" );
}//end create_table
private function get_row( $woeid )
{
self::maybe_create_table();
global $wpdb;
$row = $wpdb->get_row('
SELECT
woeid,
woe_raw,
woe_belongtos,
AsText(bgeo_geometry) AS bgeo_geometry
FROM ' . self::get_table_name() . '
WHERE 1 = 1
AND woeid = ' . (int) $woeid . '
LIMIT 1
');
if ( empty( $row ) )
{
return FALSE;
}
// convert the geometry into a proper object
if ( ! empty( $row->bgeo_geometry ) )
{
$row->bgeo_geometry = bgeo()->new_geometry( $row->bgeo_geometry, 'wkt', TRUE );
}
// unserialize the pieces
foreach ( array( 'woe_raw', 'woe_belongtos' ) as $key )
{
$row->$key = maybe_unserialize( $row->$key );
}
$row->woe_belongtos = self::sanitize_belongtos( $row->woe_belongtos );
return $row;
}
private function insert_row( $data )
{
self::maybe_create_table();
if ( empty( $data->bgeo_geometry ) )
{
WP_CLI::warning( "Empty geometry! " . print_r( $data ) );
return FALSE;
}
global $wpdb;
$sql = $wpdb->prepare(
'INSERT INTO ' . self::get_table_name() . '
(
woeid,
woe_raw,
woe_belongtos,
bgeo_geometry
)
VALUES(
\'%1$s\',
\'%2$s\',
\'%3$s\',
GeomFromText( "%4$s" )
)
ON DUPLICATE KEY UPDATE
woeid = VALUES( woeid ),
woe_raw = VALUES( woe_raw ),
woe_belongtos = VALUES( woe_belongtos ),
bgeo_geometry = VALUES( bgeo_geometry )
',
$data->woeid,
maybe_serialize( $data->woe_raw ),
maybe_serialize( $data->woe_belongtos ),
$data->bgeo_geometry->asText()
);
// execute the query
$wpdb->query( $sql );
// ...and export as a file while we have the data
self::export( $data );
// @TODO how to communicate success or failure back, maybe?
return TRUE;
}
private function get_lock( $woeid )
{
$i = 0;
while (
( $lock = wp_cache_get( $woeid, 'bgeo-data-lock', TRUE ) ) &&
(bool) $lock
)
{
if ( 1000 < $i )
{
WP_CLI::warning( "\nGiving up waiting for lock on $woeid. Previous lock set " . ( time() - $lock ) . " seconds ago." );
break;
}
if ( ! $i )
{
WP_CLI::warning( "Waiting for lock on $woeid. Previous lock set " . ( time() - $lock ) . " seconds ago." );
}
else
{
echo '.';
}
sleep( 2 );
$i++;
}
// if we've been putting dots on the screen, clear the line
if ( $i )
{
WP_CLI::line( '' );
}
wp_cache_set( $woeid, time(), 'bgeo-data-lock', 3600 );
return TRUE;
}
private function release_lock( $woeid )
{
wp_cache_delete( $woeid, 'bgeo-data-lock' );
return TRUE;
}
private function export( $geo )
{
$out_file = $out_path = __DIR__ . '/correlated-geos';
if ( isset( $geo->woe_raw->country->content ) )
{
$out_file .= '/Countries/' . $geo->woe_raw->country->content;
if ( isset( $geo->woe_raw->admin1->content ) )
{
$out_file .= '/' . $geo->woe_raw->admin1->content;
}
}
else
{
$out_file .= '/' . $geo->woe_raw->placeTypeName->content;
}
$out_file .= '/' . $geo->woe_raw->woeid . '-' . $geo->woe_raw->name . '.geojson';
$out_path = dirname( $out_file );
// check for and attempt to create the output directory
if ( ! ( file_exists( $out_path ) && is_dir( $out_path ) ) )
{
if ( ! mkdir( $out_path, 0755, TRUE ) )
{
$error->text = 'can\'t create output directory';
return $error;
}
}
// the skeleton object for the geo feature
$output = (object) array(
'type' => 'Feature',
'properties' => (object) array(
'name' => $geo->woe_raw->name,
'woeid' => $geo->woe_raw->woeid,
),
'geometry' => json_decode( self::maybe_simplify( $geo->bgeo_geometry )->out( 'json' ) ),
);
WP_CLI::line( "Exporting $out_file" );
file_put_contents( $out_file, self::json_encode( $output ) );
}
private function log( $data )
{
static $log_handle = FALSE;
// get the file handle on the first run
if ( ! $log_handle )
{
$log_handle = self::get_log_handle();
// insert the array keys as column headers in the CSV, just on the first pass
fputcsv( $log_handle, array_keys( $data ) );
}
// it's up to the caller to make sure the number and order of array keys is consistent
fputcsv( $log_handle, $data );
}
private function get_log_handle()
{
// check for and attempt to create the log directory
$log_path = __DIR__ . '/logs';
if ( ! ( file_exists( $log_path ) && is_dir( $log_path ) ) )
{
if ( ! mkdir( $log_path, 0755, TRUE ) )
{
WP_CLI::error( "Can't create log file directory" );
return FALSE;
}
}
// start the log csv file
$log_file = $log_path . '/' . date( DATE_ATOM ) . '.csv';
$log_handle = fopen( $log_file, 'w' );
if ( ! $log_handle )
{
WP_CLI::error( "Can't create log file directory" );
return FALSE;
}
return $log_handle;
}
private function json_encode( $src )
{
return str_ireplace(
array(
'"features":', // separates the preamble from the content
']],[[', // separates features from eachother
'},{', // separates features from eachother
',"geometry"', // separates the geometry from the properties
),
array(
"\"features\":\n",
"]]\n,\n\t[[",
"}\n,\n\t{",
",\n\"geometry\"",
),
json_encode( $src )
);
}
private function maybe_simplify( $geometry )
{
// merge multipolygons into a single polygon, if possible
if ( 'MultiPolygon' == $geometry->geometryType() )
{
// try to reduce it further by unioning the pieces
try
{
// @TODO: this has started fatalling with exceptions.
// Using the try-catch-reduce workaround for now, but why did the errors just appear?
$unioned_geometry = self::merge_into_one( $geometry );
$geometry = $unioned_geometry;
}
catch ( Exception $e )
{
// what else can I do?
WP_CLI::warning( "Caught exception while trying to merge_into_one() near " . __FILE__ . ':' . __LINE__ . '.' );
WP_CLI::warning( 'Geometry is ' . $geometry->geometryType() . ' with ' . count( (array) $geometry->getComponents() ) . ' components.' );
}
// simplify the individual components of the resulting geometry
$geometry = self::simplify( $geometry );
}
return $geometry;
}
private function simplify( $geometry )
{
// get the original area for comparison later
$orig_area = $geometry->envelope()->area();
if ( 1 < self::VERBOSE )
{
WP_CLI::line( "simp orig: " . $geometry->geometryType() . ': ' . count( (array) $geometry->getComponents() ) . ' components with ' . $geometry->envelope()->area() . " area" );
}
else
{
echo '.';
}
$buffer_factor = 1.09;
$buffer_buffer_factor = 0.020;
$simplify_factor = 0.050;
$iteration = 1;
do
{
if ( 1 < self::VERBOSE )
{
WP_CLI::line( "simp attempt $iteration with buffer( " . ( $buffer_factor + $buffer_buffer_factor ) . " ) and simplify( $simplify_factor )" );
}
else
{
echo '.';
}
$simple_geometry = clone $geometry;
$simple_geometry = $simple_geometry->buffer( $buffer_factor + $buffer_buffer_factor )->simplify( $simplify_factor, FALSE )->buffer( $buffer_factor * -1 );
$simple_area = $simple_geometry->envelope()->area();
// $buffer_factor += 0.01;
$buffer_buffer_factor += 0.01;
$simplify_factor -= 0.002;
$iteration += 1;
}
while ( $orig_area > $simple_area );
if ( 1 < self::VERBOSE )
{
WP_CLI::line( "simp simp: " . $simple_geometry->geometryType() . ': ' . count( (array) $simple_geometry->getComponents() ) . ' components with ' . $simple_geometry->envelope()->area() . " area" );
}
else
{
WP_CLI::line( '' );
}
return $simple_geometry;
}
private function merge_into_one( $geometry, $recursion = FALSE )
{
if ( 1 < self::VERBOSE )
{
WP_CLI::line( "merge orig: " . $geometry->geometryType() . ': ' . count( (array) $geometry->getComponents() ) . ' components with ' . $geometry->area() . " area" );
}
else
{
echo '.';
}
// break the geometry into sub-components
$parts = array_reverse( $geometry->getComponents() );
// sanity check
if ( ! is_array( $parts ) )
{
return $geometry;
}
// merge the parts into a single whole
$whole = $parts[0];
$extras = FALSE;
unset( $parts[0] );
foreach ( $parts as $k => $part )
{
// attempt to union the geometry
try
{
// @TODO: this has started fatalling with exceptions.
// Using the try-catch-reduce workaround for now, but why did the errors just appear?
$unioned_geometry = $whole->union( $part );
$whole = $unioned_geometry;
if ( 1 < self::VERBOSE )
{
WP_CLI::line( 'merge step ' . $k . ': ' . $whole->geometryType() . ': ' . count( (array) $whole->getComponents() ) . ' components with ' . $whole->area() . ' area' );
}
else
{
echo '.';
}
}
catch ( Exception $e )
{
if ( ! self::VERBOSE )
{
WP_CLI::line( '' );
}
WP_CLI::warning( 'Caught exception while trying to union() geometries near ' . __FILE__ . ':' . __LINE__ . ",\nstep " . $k . ': ' . $whole->geometryType() . ': ' . count( (array) $whole->getComponents() ) . ' components with ' . $whole->area() . ' area' );
WP_CLI::warning( 'Attempted to union ' . $part->geometryType() . ' into ' . $whole->geometryType() . '.' );
if ( ! $extras )
{
$extras = $part;
}
else
{
$extras = self::reduce( array( $extras, $part ) );
}
// now take a big leap of faith and try merging thest extras
if ( ! $recursion )
{
$extras = self::merge_into_one( $extras, TRUE );
}
if ( ! self::VERBOSE )
{
WP_CLI::line( '' );
}
WP_CLI::warning( 'Extra items on step ' . $k . ': ' . $extras->geometryType() . ': ' . count( (array) $extras->getComponents() ) . ' components with ' . $extras->area() . ' area' );
}
}
if (
is_object( $extras ) &&
is_callable( array( $extras, 'getComponents' ) ) &&
count( (array) $extras->getComponents() )
)
{
$whole = self::reduce( array( $whole, $extras ) );
}
if ( 1 < self::VERBOSE )
{
WP_CLI::line( "merge merged: " . $whole->geometryType() . ': ' . count( (array) $whole->getComponents() ) . ' components with ' . $whole->envelope()->area() . " area" );
}
else
{
echo ".\n";
}
// return the merged result
return $whole;
}
private function centroid( $geometry )
{
$centroid = $geometry->centroid();
return (object) array(
'latlon' => $centroid->y() . ' ' . $centroid->x(),
'y' => $centroid->y(),
'lat' => $centroid->y(),
'x' => $centroid->x(),
'lon' => $centroid->x(),
);
}
private function contains( $geometry, $point )
{
$bigenvelope = $geometry->buffer( 1.05 )->envelope();
// create a point geo from the provided point lat and lon
$point = bgeo()->new_geometry( 'POINT (' . $point->lon . ' ' . $point->lat . ')', 'wkt', TRUE );
// is the point inside the geo?
return $bigenvelope->contains( $point );
}
public function reduce( $components )
{
$geometry = new MultiPolygon( $components );
return geoPHP::geometryReduce( $geometry );
}//end new_geometry
}//END class
WP_CLI::add_command( 'bgeodata', 'bGeo_Data' );