-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcarztheme-api.php
More file actions
3171 lines (2730 loc) · 94.4 KB
/
Copy pathcarztheme-api.php
File metadata and controls
3171 lines (2730 loc) · 94.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Paradigma REST API
* Plugin URI: https://paradigma.lat
* Description: Cria endpoints REST API personalizados para listar todos os veículos com suas informações completas. Quando solicitado via GET, retorna JSON com todos os dados dos carros.
* Version: 2.0.0
* Author: UnkDev
* Author URI: https://unkdev.com.br
* Text Domain: carztheme-api
* Domain Path: /languages
* Requires at least: 5.0
* Requires PHP: 7.0
*/
// Se este arquivo for chamado diretamente, aborte.
if ( ! defined( 'WPINC' ) ) {
die;
}
// Definir constantes do plugin primeiro
define( 'CARZ_API_VERSION', '2.0.0' );
define( 'CARZ_API_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'CARZ_API_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
// Incluir JWT Handler
require_once CARZ_API_PLUGIN_DIR . 'jwt-handler.php';
/**
* Classe principal do plugin
*/
class Carz_REST_API_Provider {
/**
* Instância única do plugin
*/
private static $instance = null;
/**
* Slug do post type de carros
*/
private $cars_post_type = 'cpt_cars';
/**
* Namespace da API REST padrão do WordPress
*/
private $api_namespace = 'carz-api/v1';
/**
* Retorna a instância única do plugin
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Construtor privado para Singleton
*/
private function __construct() {
$this->init_hooks();
}
/**
* Inicializa os hooks do WordPress
*/
private function init_hooks() {
// Verificar se TRX Addons está ativo
add_action( 'plugins_loaded', array( $this, 'check_dependencies' ) );
// Registrar endpoints REST API padrão do WordPress
add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
// Adicionar página de configurações no admin
add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
add_action( 'admin_init', array( $this, 'register_settings' ) );
// Adicionar coluna no admin
add_filter( 'manage_' . $this->cars_post_type . '_posts_columns', array( $this, 'add_sync_column' ) );
add_action( 'manage_' . $this->cars_post_type . '_posts_custom_column', array( $this, 'show_sync_column_content' ), 10, 2 );
// Adicionar avisos de admin
add_action( 'admin_notices', array( $this, 'show_admin_notices' ) );
// Adicionar rewrite rules para endpoint personalizado
add_action( 'init', array( $this, 'add_rewrite_rules' ) );
add_filter( 'query_vars', array( $this, 'add_query_vars' ) );
add_action( 'template_redirect', array( $this, 'handle_custom_endpoint' ) );
// Hook de ativação para flush rewrite rules
register_activation_hook( __FILE__, array( $this, 'activate' ) );
register_deactivation_hook( __FILE__, array( $this, 'deactivate' ) );
// Adicionar scripts admin
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
// AJAX para gerar API Key
add_action( 'wp_ajax_carz_generate_api_key', array( $this, 'ajax_generate_api_key' ) );
// AJAX para testar endpoint
add_action( 'wp_ajax_carz_test_endpoint', array( $this, 'ajax_test_endpoint' ) );
}
/**
* Hook de ativação do plugin
*/
public function activate() {
$this->add_rewrite_rules();
flush_rewrite_rules();
}
/**
* Hook de desativação do plugin
*/
public function deactivate() {
flush_rewrite_rules();
}
/**
* Verifica se as dependências estão ativas
*/
public function check_dependencies() {
if ( ! defined( 'TRX_ADDONS_VERSION' ) ) {
add_action( 'admin_notices', array( $this, 'trx_addons_missing_notice' ) );
return false;
}
// Verificar se o CPT de carros existe
if ( ! post_type_exists( $this->cars_post_type ) ) {
add_action( 'admin_notices', array( $this, 'cars_cpt_missing_notice' ) );
return false;
}
return true;
}
/**
* Aviso quando TRX Addons não está ativo
*/
public function trx_addons_missing_notice() {
?>
<div class="notice notice-error">
<p><?php esc_html_e( 'Carz REST API Provider requer o TRX Addons para funcionar. Por favor, instale e ative o TRX Addons.', 'carztheme-api' ); ?></p>
</div>
<?php
}
/**
* Aviso quando CPT de carros não existe
*/
public function cars_cpt_missing_notice() {
?>
<div class="notice notice-error">
<p><?php esc_html_e( 'Carz REST API Provider: O Custom Post Type de Carros não foi encontrado. Verifique se o TRX Addons está configurado corretamente.', 'carztheme-api' ); ?></p>
</div>
<?php
}
/**
* Registra as rotas REST API padrão do WordPress
*/
public function register_rest_routes() {
// Rota para listar todos os carros (GET) e criar novo (POST)
register_rest_route( $this->api_namespace, '/vehicles', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_vehicles' ),
'permission_callback' => array( $this, 'check_api_permission' ),
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_vehicle' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para obter (GET), atualizar (PUT) e deletar (DELETE) um carro específico
register_rest_route( $this->api_namespace, '/vehicles/(?P<id>\d+)', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_single_vehicle' ),
'permission_callback' => array( $this, 'check_api_permission' ),
'args' => array(
'id' => array(
'validate_callback' => function( $param ) {
return is_numeric( $param );
},
),
),
),
array(
'methods' => 'PUT',
'callback' => array( $this, 'update_vehicle' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
'args' => array(
'id' => array(
'validate_callback' => function( $param ) {
return is_numeric( $param );
},
),
),
),
array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_vehicle' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
'args' => array(
'id' => array(
'validate_callback' => function( $param ) {
return is_numeric( $param );
},
),
),
),
) );
// Rota para listar todos os fabricantes (makers) e criar novo
register_rest_route( $this->api_namespace, '/makers', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_makers' ),
'permission_callback' => array( $this, 'check_api_permission' ),
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_maker' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para deletar fabricante específico
register_rest_route( $this->api_namespace, '/makers/(?P<id>\d+)', array(
array(
'methods' => 'PUT',
'callback' => array( $this, 'update_maker' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_maker' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para listar todos os modelos (models) ou filtrar por fabricante, e criar novo
register_rest_route( $this->api_namespace, '/models', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_models' ),
'permission_callback' => array( $this, 'check_api_permission' ),
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_model' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para deletar modelo específico
register_rest_route( $this->api_namespace, '/models/(?P<id>\d+)', array(
array(
'methods' => 'PUT',
'callback' => array( $this, 'update_model' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_model' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para listar todos os recursos (features) e criar novo
register_rest_route( $this->api_namespace, '/features', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_features' ),
'permission_callback' => array( $this, 'check_api_permission' ),
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_feature' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para deletar recurso específico
register_rest_route( $this->api_namespace, '/features/(?P<id>\d+)', array(
array(
'methods' => 'PUT',
'callback' => array( $this, 'update_feature' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_feature' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Types (Tipos de veículo)
register_rest_route( $this->api_namespace, '/types', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_types' ),
'permission_callback' => '__return_true',
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_type' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
register_rest_route( $this->api_namespace, '/types/(?P<id>\d+)', array(
array(
'methods' => 'PUT',
'callback' => array( $this, 'update_type' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_type' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Status (Alugar/Vender)
register_rest_route( $this->api_namespace, '/status', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_status' ),
'permission_callback' => '__return_true',
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_status' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
register_rest_route( $this->api_namespace, '/status/(?P<id>\d+)', array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_status' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
) );
// Labels (Rótulos)
register_rest_route( $this->api_namespace, '/labels', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_labels' ),
'permission_callback' => '__return_true',
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_label' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
register_rest_route( $this->api_namespace, '/labels/(?P<id>\d+)', array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_label' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
) );
// Cities (Cidades)
register_rest_route( $this->api_namespace, '/cities', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_all_cities' ),
'permission_callback' => '__return_true',
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_city' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
register_rest_route( $this->api_namespace, '/cities/(?P<id>\d+)', array(
array(
'methods' => 'PUT',
'callback' => array( $this, 'update_city' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_city' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para upload de imagens
register_rest_route( $this->api_namespace, '/upload', array(
array(
'methods' => 'POST',
'callback' => array( $this, 'upload_image' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para deletar imagem
register_rest_route( $this->api_namespace, '/media/(?P<id>\d+)', array(
array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_media' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para listar agentes/vendedores
register_rest_route( $this->api_namespace, '/agents', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_agents' ),
'permission_callback' => array( $this, 'check_api_permission' ),
),
array(
'methods' => 'POST',
'callback' => array( $this, 'create_agent' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
// Rota para agente individual
register_rest_route( $this->api_namespace, '/agents/(?P<id>\d+)', array(
array(
'methods' => 'GET',
'callback' => array( $this, 'get_agent' ),
'permission_callback' => array( $this, 'check_api_permission' ),
),
array(
'methods' => 'PUT',
'callback' => array( $this, 'update_agent' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
array(
'methods' => 'DELETE',
'callback' => array( $this, 'delete_agent' ),
'permission_callback' => array( $this, 'check_jwt_permission' ),
),
) );
}
/**
* Verifica permissão de acesso à API (para métodos GET)
*/
public function check_api_permission( $request ) {
$require_auth = get_option( 'carz_api_require_auth', '0' );
// Se não requer autenticação, permitir acesso
if ( $require_auth !== '1' ) {
return true;
}
// Verificar API Key no header ou query string
$api_key = $request->get_header( 'X-API-Key' );
if ( empty( $api_key ) ) {
$api_key = $request->get_param( 'api_key' );
}
$stored_key = get_option( 'carz_api_key', '' );
if ( empty( $stored_key ) || $api_key !== $stored_key ) {
return new WP_Error(
'rest_forbidden',
__( 'API Key inválida ou ausente.', 'carztheme-api' ),
array( 'status' => 401 )
);
}
return true;
}
/**
* Verifica permissão JWT para métodos POST, PUT e DELETE
*/
public function check_jwt_permission( $request ) {
error_log( 'JWT Permission: Verificando autenticação' );
// Obter token do header Authorization
$auth_header = $request->get_header( 'Authorization' );
error_log( 'JWT Permission: Auth header - ' . ( $auth_header ? 'presente' : 'ausente' ) );
if ( empty( $auth_header ) ) {
error_log( 'JWT Permission: Token ausente' );
return new WP_Error(
'rest_forbidden',
__( 'Token de autenticação ausente. Use o header Authorization: Bearer {token}', 'carztheme-api' ),
array( 'status' => 401 )
);
}
// Extrair token do formato "Bearer {token}"
$token = null;
if ( preg_match( '/Bearer\s+(\S+)/', $auth_header, $matches ) ) {
$token = $matches[1];
}
error_log( 'JWT Permission: Token extraído - ' . ( $token ? 'sim' : 'não' ) );
if ( empty( $token ) ) {
error_log( 'JWT Permission: Formato de token inválido' );
return new WP_Error(
'rest_forbidden',
__( 'Formato de token inválido. Use: Authorization: Bearer {token}', 'carztheme-api' ),
array( 'status' => 401 )
);
}
// Obter JWT_SECRET (prioritariamente do .env do dashboard)
$jwt_secret = $this->get_jwt_secret();
error_log( 'JWT Permission: JWT_SECRET - ' . ( $jwt_secret ? 'configurado' : 'ausente' ) );
if ( empty( $jwt_secret ) ) {
error_log( 'JWT Permission: JWT_SECRET não configurado' );
return new WP_Error(
'rest_forbidden',
__( 'JWT_SECRET não configurado no servidor.', 'carztheme-api' ),
array( 'status' => 500 )
);
}
// Validar token JWT
try {
$payload = Carz_JWT_Handler::validate_token( $token, $jwt_secret );
error_log( 'JWT Permission: Payload - ' . print_r( $payload, true ) );
if ( ! $payload ) {
error_log( 'JWT Permission: Token inválido ou expirado' );
return new WP_Error(
'rest_forbidden',
__( 'Token JWT inválido ou expirado.', 'carztheme-api' ),
array( 'status' => 401 )
);
}
error_log( 'JWT Permission: Autenticação bem-sucedida' );
// Token válido
return true;
} catch ( Exception $e ) {
error_log( 'JWT Permission: Exceção - ' . $e->getMessage() );
return new WP_Error(
'rest_forbidden',
__( 'Erro ao validar token JWT: ', 'carztheme-api' ) . $e->getMessage(),
array( 'status' => 401 )
);
}
}
/**
* Obtém o JWT_SECRET do ambiente ou wp-config
*/
private function get_jwt_secret() {
// Tentar obter do wp-config.php
if ( defined( 'JWT_SECRET' ) ) {
return JWT_SECRET;
}
// Tentar obter de variável de ambiente
if ( getenv( 'JWT_SECRET' ) ) {
return getenv( 'JWT_SECRET' );
}
// Tentar obter de $_ENV
if ( isset( $_ENV['JWT_SECRET'] ) ) {
return $_ENV['JWT_SECRET'];
}
// Como fallback, tentar obter do banco de dados (se configurado)
return get_option( 'carz_jwt_secret', '' );
}
/**
* Retorna todos os veículos via REST API padrão
*/
public function get_all_vehicles( $request ) {
$args = array(
'post_type' => $this->cars_post_type,
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
);
$cars = get_posts( $args );
$vehicles_data = array();
foreach ( $cars as $car ) {
$vehicles_data[] = $this->get_car_data( $car->ID );
}
// Retornar array direto (cada item será processado separadamente)
return new WP_REST_Response( $vehicles_data, 200 );
}
/**
* Retorna um veículo específico via REST API padrão
*/
public function get_single_vehicle( $request ) {
$car_id = $request->get_param( 'id' );
if ( get_post_type( $car_id ) !== $this->cars_post_type ) {
return new WP_Error(
'rest_not_found',
__( 'Veículo não encontrado.', 'carztheme-api' ),
array( 'status' => 404 )
);
}
$car_data = $this->get_car_data( $car_id );
// Retornar objeto direto (sem wrapper)
return new WP_REST_Response( $car_data, 200 );
}
/**
* Cria um novo veículo via REST API (POST)
*/
public function create_vehicle( $request ) {
$params = $request->get_json_params();
if ( empty( $params ) ) {
return new WP_Error(
'rest_invalid_data',
__( 'Dados inválidos ou ausentes.', 'carztheme-api' ),
array( 'status' => 400 )
);
}
// Validar campos obrigatórios
if ( empty( $params['title'] ) ) {
return new WP_Error(
'rest_invalid_data',
__( 'O campo "title" é obrigatório.', 'carztheme-api' ),
array( 'status' => 400 )
);
}
// Preparar dados do post
$post_data = array(
'post_type' => $this->cars_post_type,
'post_title' => sanitize_text_field( $params['title'] ),
'post_content' => isset( $params['description'] ) ? wp_kses_post( $params['description'] ) : '',
'post_excerpt' => isset( $params['excerpt'] ) ? sanitize_textarea_field( $params['excerpt'] ) : '',
'post_status' => isset( $params['status'] ) ? sanitize_text_field( $params['status'] ) : 'publish',
);
// Criar o post
$car_id = wp_insert_post( $post_data, true );
if ( is_wp_error( $car_id ) ) {
return new WP_Error(
'rest_insert_failed',
__( 'Erro ao criar veículo: ', 'carztheme-api' ) . $car_id->get_error_message(),
array( 'status' => 500 )
);
}
// Atualizar meta dados e taxonomias
$this->update_car_metadata( $car_id, $params );
// Featured Image
if ( isset( $params['featured_image_id'] ) && ! empty( $params['featured_image_id'] ) ) {
set_post_thumbnail( $car_id, intval( $params['featured_image_id'] ) );
}
// Retornar o veículo criado
$car_data = $this->get_car_data( $car_id );
return new WP_REST_Response( $car_data, 201 );
}
/**
* Atualiza um veículo existente via REST API (PUT)
*/
public function update_vehicle( $request ) {
$car_id = $request->get_param( 'id' );
$params = $request->get_json_params();
if ( empty( $params ) ) {
return new WP_Error(
'rest_invalid_data',
__( 'Dados inválidos ou ausentes.', 'carztheme-api' ),
array( 'status' => 400 )
);
}
// Verificar se o veículo existe
if ( get_post_type( $car_id ) !== $this->cars_post_type ) {
return new WP_Error(
'rest_not_found',
__( 'Veículo não encontrado.', 'carztheme-api' ),
array( 'status' => 404 )
);
}
// Preparar dados do post para atualização
$post_data = array(
'ID' => $car_id,
);
if ( isset( $params['title'] ) ) {
$post_data['post_title'] = sanitize_text_field( $params['title'] );
}
if ( isset( $params['description'] ) ) {
$post_data['post_content'] = wp_kses_post( $params['description'] );
}
if ( isset( $params['excerpt'] ) ) {
$post_data['post_excerpt'] = sanitize_textarea_field( $params['excerpt'] );
}
if ( isset( $params['status'] ) ) {
$post_data['post_status'] = sanitize_text_field( $params['status'] );
}
// Atualizar o post se houver alterações
if ( count( $post_data ) > 1 ) {
$result = wp_update_post( $post_data, true );
if ( is_wp_error( $result ) ) {
return new WP_Error(
'rest_update_failed',
__( 'Erro ao atualizar veículo: ', 'carztheme-api' ) . $result->get_error_message(),
array( 'status' => 500 )
);
}
}
// Atualizar meta dados e taxonomias
$this->update_car_metadata( $car_id, $params );
// Featured Image
if ( isset( $params['featured_image_id'] ) ) {
if ( ! empty( $params['featured_image_id'] ) ) {
set_post_thumbnail( $car_id, intval( $params['featured_image_id'] ) );
} else {
delete_post_thumbnail( $car_id );
}
}
// Retornar o veículo atualizado
$car_data = $this->get_car_data( $car_id );
return new WP_REST_Response( $car_data, 200 );
}
/**
* Deleta um veículo via REST API (DELETE)
*/
public function delete_vehicle( $request ) {
$car_id = $request->get_param( 'id' );
// Verificar se o veículo existe
if ( get_post_type( $car_id ) !== $this->cars_post_type ) {
return new WP_Error(
'rest_not_found',
__( 'Veículo não encontrado.', 'carztheme-api' ),
array( 'status' => 404 )
);
}
// Obter dados do veículo antes de deletar
$car_data = $this->get_car_data( $car_id );
// Deletar o post
$result = wp_delete_post( $car_id, true );
if ( ! $result ) {
return new WP_Error(
'rest_delete_failed',
__( 'Erro ao deletar veículo.', 'carztheme-api' ),
array( 'status' => 500 )
);
}
// Retornar resposta de sucesso com os dados do veículo deletado
return new WP_REST_Response(
array(
'deleted' => true,
'previous' => $car_data,
),
200
);
}
/**
* Atualiza os metadados e taxonomias de um veículo
*
* @param int $car_id O ID do veículo
* @param array $params Os parâmetros recebidos
*/
private function update_car_metadata( $car_id, $params ) {
// Atualizar imagem destacada
if ( isset( $params['featured_image_id'] ) ) {
set_post_thumbnail( $car_id, intval( $params['featured_image_id'] ) );
}
// Preparar array de opções do TRX Addons
$trx_options = get_post_meta( $car_id, 'trx_addons_options', true );
if ( ! is_array( $trx_options ) ) {
$trx_options = array();
}
// Preços
if ( isset( $params['prices'] ) && is_array( $params['prices'] ) ) {
if ( isset( $params['prices']['price'] ) ) {
$trx_options['price'] = sanitize_text_field( $params['prices']['price'] );
}
if ( isset( $params['prices']['price2'] ) ) {
$trx_options['price2'] = sanitize_text_field( $params['prices']['price2'] );
}
if ( isset( $params['prices']['price_prefix'] ) ) {
$trx_options['before_price'] = sanitize_text_field( $params['prices']['price_prefix'] );
}
if ( isset( $params['prices']['price2_prefix'] ) ) {
$trx_options['after_price'] = sanitize_text_field( $params['prices']['price2_prefix'] );
}
}
// Especificações técnicas
if ( isset( $params['specifications'] ) && is_array( $params['specifications'] ) ) {
$specs = $params['specifications'];
if ( isset( $specs['id'] ) ) {
$trx_options['id'] = sanitize_text_field( $specs['id'] );
}
if ( isset( $specs['year'] ) ) {
$trx_options['produced'] = sanitize_text_field( $specs['year'] );
}
if ( isset( $specs['mileage'] ) ) {
$trx_options['mileage'] = sanitize_text_field( $specs['mileage'] );
}
if ( isset( $specs['fuel'] ) ) {
$trx_options['fuel'] = sanitize_text_field( $specs['fuel'] );
}
if ( isset( $specs['engine_size'] ) ) {
$trx_options['engine_size'] = sanitize_text_field( $specs['engine_size'] );
}
if ( isset( $specs['transmission'] ) ) {
$trx_options['transmission'] = sanitize_text_field( $specs['transmission'] );
}
if ( isset( $specs['drive'] ) ) {
$trx_options['type_drive'] = sanitize_text_field( $specs['drive'] );
}
if ( isset( $specs['color'] ) ) {
$trx_options['color'] = sanitize_text_field( $specs['color'] );
}
if ( isset( $specs['doors'] ) ) {
$trx_options['doors'] = sanitize_text_field( $specs['doors'] );
}
if ( isset( $specs['seats'] ) ) {
$trx_options['seats'] = sanitize_text_field( $specs['seats'] );
}
// Fabricante (Maker) - Aceitar ID diretamente ou criar/buscar por nome
if ( isset( $specs['maker'] ) && ! empty( $specs['maker'] ) ) {
// Se for um número, é um ID de termo
if ( is_numeric( $specs['maker'] ) ) {
$maker_term_id = intval( $specs['maker'] );
wp_set_object_terms( $car_id, $maker_term_id, 'cpt_cars_maker' );
$trx_options['maker'] = $maker_term_id;
}
// Se for texto, buscar ou criar o termo (para compatibilidade)
else {
$maker_name = sanitize_text_field( $specs['maker'] );
$maker_term = get_term_by( 'name', $maker_name, 'cpt_cars_maker' );
if ( $maker_term ) {
wp_set_object_terms( $car_id, $maker_term->term_id, 'cpt_cars_maker' );
$trx_options['maker'] = $maker_term->term_id;
}
}
}
// Modelo (Model) - Aceitar ID diretamente ou criar/buscar por nome
if ( isset( $specs['model'] ) && ! empty( $specs['model'] ) ) {
// Se for um número, é um ID de termo
if ( is_numeric( $specs['model'] ) ) {
$model_term_id = intval( $specs['model'] );
wp_set_object_terms( $car_id, $model_term_id, 'cpt_cars_model' );
$trx_options['model'] = $model_term_id;
}
// Se for texto, buscar ou criar o termo (para compatibilidade)
else {
$model_name = sanitize_text_field( $specs['model'] );
$model_term = get_term_by( 'name', $model_name, 'cpt_cars_model' );
if ( $model_term ) {
wp_set_object_terms( $car_id, $model_term->term_id, 'cpt_cars_model' );
$trx_options['model'] = $model_term->term_id;
}
}
}
}
// Localização
if ( isset( $params['location'] ) && is_array( $params['location'] ) ) {
if ( isset( $params['location']['city'] ) ) {
$trx_options['city'] = sanitize_text_field( $params['location']['city'] );
}
if ( isset( $params['location']['country'] ) ) {
$trx_options['country'] = sanitize_text_field( $params['location']['country'] );
}
if ( isset( $params['location']['address'] ) ) {
$trx_options['address'] = sanitize_text_field( $params['location']['address'] );
}
}
// Vídeo
if ( isset( $params['video'] ) && is_array( $params['video'] ) ) {
if ( isset( $params['video']['url'] ) ) {
$trx_options['video'] = esc_url_raw( $params['video']['url'] );
}
if ( isset( $params['video']['description'] ) ) {
$trx_options['video_description'] = sanitize_textarea_field( $params['video']['description'] );
}
}
// Galeria de imagens
if ( isset( $params['gallery'] ) && is_array( $params['gallery'] ) ) {
$gallery_urls = array();
foreach ( $params['gallery'] as $image ) {
// Se for uma string (URL direta), usar diretamente
if ( is_string( $image ) ) {
$gallery_urls[] = esc_url_raw( $image );
}
// Se for um objeto com 'url', usar a URL
elseif ( is_array( $image ) && isset( $image['url'] ) ) {
$gallery_urls[] = esc_url_raw( $image['url'] );
}
}
$trx_options['gallery'] = implode( '|', $gallery_urls );
}
// Agente/Vendedor
if ( isset( $params['agent'] ) && is_array( $params['agent'] ) ) {
// Se tem ID de agente, usar o tipo 'agent'
if ( isset( $params['agent']['id'] ) && ! empty( $params['agent']['id'] ) ) {
$trx_options['agent_type'] = 'agent';
$trx_options['agent'] = intval( $params['agent']['id'] );
}
// Senão, usar tipo 'owner' com os dados manuais (fallback)
else {
$trx_options['agent_type'] = 'owner';
if ( isset( $params['agent']['name'] ) ) {
$trx_options['owner_name'] = sanitize_text_field( $params['agent']['name'] );
}
if ( isset( $params['agent']['email'] ) ) {
$trx_options['owner_email'] = sanitize_email( $params['agent']['email'] );
}
if ( isset( $params['agent']['phone'] ) ) {
$trx_options['owner_phone'] = sanitize_text_field( $params['agent']['phone'] );
}
}
}
// Salvar trx_addons_options
update_post_meta( $car_id, 'trx_addons_options', $trx_options );
// Processar Type (tipo de veículo)
if ( isset( $params['type_id'] ) && ! empty( $params['type_id'] ) ) {
wp_set_object_terms( $car_id, intval( $params['type_id'] ), 'cpt_cars_type' );
}
// Processar Status
if ( isset( $params['status_ids'] ) && is_array( $params['status_ids'] ) ) {
$status_ids = array_map( 'intval', $params['status_ids'] );
wp_set_object_terms( $car_id, $status_ids, 'cpt_cars_status' );
}
// Processar Labels
if ( isset( $params['label_ids'] ) && is_array( $params['label_ids'] ) ) {
$label_ids = array_map( 'intval', $params['label_ids'] );
wp_set_object_terms( $car_id, $label_ids, 'cpt_cars_labels' );
}
// Processar City
if ( isset( $params['city_id'] ) && ! empty( $params['city_id'] ) ) {
wp_set_object_terms( $car_id, intval( $params['city_id'] ), 'cpt_cars_city' );
}
// Atualizar taxonomias
if ( isset( $params['taxonomies'] ) && is_array( $params['taxonomies'] ) ) {
// Fabricante (Maker)
if ( isset( $params['taxonomies']['maker'] ) && is_array( $params['taxonomies']['maker'] ) ) {
$maker_ids = array();
foreach ( $params['taxonomies']['maker'] as $maker ) {
if ( isset( $maker['id'] ) ) {
$maker_ids[] = intval( $maker['id'] );
}
}
if ( ! empty( $maker_ids ) ) {
wp_set_object_terms( $car_id, $maker_ids, 'cpt_cars_maker' );
}