-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.php
367 lines (276 loc) · 9.07 KB
/
functions.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
<?php
/**
* Funções para o plugin de API
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
// Carrega template para página 404
add_filter( '404_template', function () {
return SAPI_PATH . 'templates/404.php';
});
// Redirecionamento 404
function sapi_redir404() {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
require get_404_template();
exit;
}
// Retorna valor de settings do grupo, ou padrão
function sapi_setting( $setting, $default = null ) {
$group = get_option(SAPI_SET_GROUP);
if ( isset($group[$setting]) && !empty($group[$setting]) ) {
// Retorna setting
return $group[$setting];
}
else {
if ( !empty($default) ) {
// Setting não existe, retorna padrão
return $default;
}
else {
return false;
}
}
}
// Retorna slug para página de login escondida
function sapi_get_custom_login() {
$df_cl = SAPI_CUSTOM_LOGIN;
$slug = sapi_setting('sapi_login_slug', $df_cl['slug']);
return array(
'slug' => sanitize_title($slug),
'key' => $df_cl['key'],
);
}
// Verifica autenticação na hora do response nos endpoints da APi
add_filter( 'rest_request_before_callbacks', function ( $response, $handler, WP_REST_Request $request ) {
if ( is_user_logged_in() ) {
// Libera o response para usuários logados (painel web)
return $response;
}
if ( !$request->get_header('authorization') || !isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ) {
// Não tem Auth no header
// Não tem user ou password na autenticação
sapi_redir404();
}
if ( is_multisite() ) {
// Se for Multisite, verifica se o usuário está no site do endpoint
$blog_id = get_current_blog_id();
$user_id = username_exists( sanitize_text_field( $_SERVER['PHP_AUTH_USER'] ) );
if ( $user_id && !is_user_member_of_blog( $user_id, $blog_id ) ) {
// Usuário existe
// Mas não é desse site (multisite)
sapi_redir404();
}
}
return $response;
}, 10, 3 );
// Considera erros de autenticação nos endpoints da Rest API
add_filter( 'rest_authentication_errors', function ( $error ) {
// Passthrough other errors
if ( !empty($error) ) {
return $error;
}
global $wp_json_basic_auth_error;
return $wp_json_basic_auth_error;
});
// Bloqueia todo o acesso ao site
// Libera tela de login
add_action( 'after_setup_theme', function () {
$login = sapi_get_custom_login();
// var_dump($_REQUEST['login']);
// exit();
if ( is_admin() || is_user_logged_in() ) {
// Páginas do painel ou usuário logado
return;
}
else {
if ( $GLOBALS['pagenow'] === 'wp-login.php' ) {
if ( !empty( $_POST ) )
// Login lost password sent
return;
if ( isset($_REQUEST[$login['key']]) && $_REQUEST[$login['key']] === $login['slug'] )
// Login form
return;
if ( isset($_REQUEST['action']) && ($_REQUEST['action'] === 'rp' || $_REQUEST['action'] === 'lostpassword') )
// Link de ativação por e-mail
return;
if ( isset($_REQUEST['checkemail']) && $_REQUEST['checkemail'] === 'confirm' )
// Recuperar senha depois do link de ativação
return;
}
elseif ( isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) ) {
// Rest API
return;
}
}
sapi_redir404();
}, 10 );
// Cria novo caminho para login usando query secreta
add_action( 'after_setup_theme', function () {
$login = sapi_get_custom_login();
// Verifica se tem slug com home + masterpanel
$safe_slug = home_url(
$path = $login['slug'],
$scheme = 'relative'
);
if ( strpos($_SERVER['REQUEST_URI'], $safe_slug) !== false ) {
$destiny = esc_url( add_query_arg(
$login['key'], $login['slug'],
home_url('/') . 'wp-login.php'
));
wp_redirect( $destiny );
exit();
}
}, 9 );
// Define nova URL para 'Esqueci minha senha'
add_filter( 'lostpassword_url', function () {
$login = sapi_get_custom_login();
return esc_url( add_query_arg(
array(
$login['key'] => $login['slug'],
'action' => 'lostpassword',
),
home_url('/') . 'wp-login.php'
));
}, 10, 0 );
// Define nova URL para 'Login'
add_filter( 'login_url', function ( $login_url, $redirect, $force_reauth ) {
$login = sapi_get_custom_login();
$login_url = esc_url( add_query_arg(
$login['key'], $login['slug'],
home_url('/') . 'wp-login.php'
));
if ( ! empty( $redirect ) ) {
$login_url = add_query_arg( 'redirect_to', urlencode( $redirect ), $login_url );
}
if ( $force_reauth ) {
$login_url = add_query_arg( 'reauth', '1', $login_url );
}
return $login_url;
}, 10, 3 );
// Redireciona para o site após o logout
add_action( 'wp_logout', function () {
$ur_logout = sapi_setting('sapi_logout_redir', get_home_url());
wp_redirect( esc_url($ur_logout) );
exit();
});
// Evita o redirecionamento para a 'login url' no caminho /wp-admin
add_action( 'init', function () {
remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
});
add_filter( 'auth_redirect_scheme', function ( $scheme ) {
if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) {
return $scheme;
}
sapi_redir404();
}, 9999 );
// Muda o prefixo do endpoint da API Rest
add_filter( 'rest_url_prefix', function () {
$api_prefix = sapi_setting('sapi_api_prefix', SAPI_API_PREFIX);
return sanitize_title($api_prefix);
}, 999 );
// Retorna certos campos posts de uma Query
function get_posts_fields( $args = array() ) {
/** $available_args = array(
* 'ID', // int
* 'post_author', // string
* 'post_type', // string
* 'post_mime_type', // string
* 'post_name', // string
* 'post_date', // string
* 'post_modified', // string
* 'menu_order', // int
* 'post_parent', // int
* 'post_status', // string
* 'comment_status', // string
* 'comment_count', // int
* 'orderby', // string, a valid field name
* 'order', // string 'ASC', or 'DESC',
* 'posts_per_page', // int
* 'include', // array (or comma separed string) of post ids
* 'exclude', // array (or comma separed string) of post ids
* 'search', // string if passed will search for it in post title
* 'fields', // array (or comma separed string) of fields to retrieve.
* // If only 1 field is passed a 'flat' array is returned
* ); */
$valid_fields = array(
'ID' => '%d',
'post_author' => '%d',
'post_type' => '%s',
'post_mime_type' => '%s',
'post_title' => false,
'post_name' => '%s',
'post_date' => '%s',
'post_modified' => '%s',
'menu_order' => '%d',
'post_parent' => '%d',
'post_excerpt' => false,
'post_content' => false,
'post_status' => '%s',
'comment_status' => false,
'ping_status' => false,
'to_ping' => false,
'pinged' => false,
'comment_count' => '%d'
);
$defaults = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => get_option('posts_per_page'),
);
global $wpdb;
$args = wp_parse_args($args, $defaults);
$where = "";
foreach ( $valid_fields as $field => $can_query ) {
if ( isset($args[$field]) && $can_query ) {
if ( $where != "" ) $where .= " AND ";
$where .= $wpdb->prepare( $field . " = " . $can_query, $args[$field] );
}
}
if ( isset($args['search']) && is_string($args['search']) ) {
if ( $where != "" ) $where .= " AND ";
$where .= $wpdb->prepare("post_title LIKE %s", "%" . $args['search'] . "%");
}
if ( isset($args['include']) ) {
if ( is_string($args['include']) ) $args['include'] = explode(',', $args['include']);
if ( is_array($args['include']) ) {
$args['include'] = array_map('intval', $args['include']);
if ( $where != "" ) $where .= " OR ";
$where .= "ID IN (" . implode(',', $args['include'] ). ")";
}
}
if ( isset($args['exclude']) ) {
if ( is_string($args['exclude']) ) $args['exclude'] = explode(',', $args['exclude']);
if ( is_array($args['exclude']) ) {
$args['exclude'] = array_map('intval', $args['exclude']);
if ( $where != "" ) $where .= " AND ";
$where .= "ID NOT IN (" . implode(',', $args['exclude'] ). ")";
}
}
extract($args);
$iscol = false;
if ( isset($fields) ) {
if ( is_string($fields) ) $fields = explode(',', $fields);
if ( is_array($fields) ) {
$fields = array_intersect($fields, array_keys($valid_fields));
if( count($fields) == 1 ) $iscol = true;
$fields = implode(',', $fields);
}
}
if ( empty($fields) ) $fields = '*';
if ( ! in_array($orderby, $valid_fields) ) $orderby = 'post_date';
if ( ! in_array( strtoupper($order), array('ASC','DESC')) ) $order = 'DESC';
if ( ! intval($posts_per_page) && $posts_per_page != -1) {
$posts_per_page = $defaults['posts_per_page'];
}
if ( $where == "" ) $where = "1";
$q = "SELECT $fields FROM $wpdb->posts WHERE " . $where;
$q .= " ORDER BY $orderby $order";
if ( $posts_per_page != -1) $q .= " LIMIT $posts_per_page";
return $iscol ? $wpdb->get_col($q) : $wpdb->get_results($q);
}