PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.5.3
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.5.3
3.7.5 3.7.4 3.7.3 3.7.2 1-final 3.7.1 3.7.0 3.6.8 3.6.7 3.6.6 3.6.5 3.6.4 3.6.3 3.6.2 3.6.1 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.0.9 3.1.0 3.1.1 3.1.10 All 111 releases
templately / includes / Utils / Http.php

Http.php in Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! 3.5.3, at includes/Utils/Http.php

330 lines 10.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Templately\Utils;
3
4 use Templately\API\Login;
5 use WP_Error;
6
7 class Http extends Base {
8 /**
9 * API Endpoint
10 * @var string
11 */
12 private $url = 'https://app.templately.com/api/plugin';
13
14 /**
15 * Development Mode
16 * @var boolean
17 */
18 private $dev_mode = false;
19
20 /**
21 * API Query
22 * @var string
23 */
24 public $query = null;
25 /**
26 * API Endpoint
27 * @var string
28 */
29 public $endpoint = null;
30
31 /**
32 * Setting the development mode.
33 */
34 public function __construct() {
35 $this->dev_mode = Helper::is_dev_api();
36 }
37
38 /**
39 * Determining the endpoint URL based on the mode.
40 *
41 * @return string
42 */
43 public function url() {
44 if ( Helper::is_dev_api() ) {
45 $this->url = 'https://app.templately.dev/api/plugin';
46 }
47
48 /**
49 * Filter the API endpoint URL
50 *
51 * @since 3.5.0
52 * @param string $url The endpoint URL
53 */
54 $this->url = apply_filters('templately_dev_api_endpoint_url', $this->url);
55
56 return $this->url;
57 }
58
59 /**
60 * Generate Google OAuth authentication URL
61 *
62 * @param string $redirect_to Optional redirect path after authentication
63 * @return string The Google auth URL with query parameters
64 */
65 public function google_auth_url($redirect_to = '', $current_url = '') {
66 $base_url = $this->url();
67 // Replace /api/plugin with /api/auth/plugin/google
68 $auth_url = str_replace('/api/plugin', '/api/auth/plugin/google', $base_url);
69
70 // Get the referer to return to the exact same page we initiated login from securely
71 if ( ! empty( $current_url ) ) {
72 $referer = esc_url_raw( $current_url );
73 } else {
74 $referer = isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '';
75 }
76
77 $return_url = wp_validate_redirect( $referer, '' );
78
79 if ( empty( $return_url ) ) {
80 $return_url = admin_url( 'admin.php?page=templately' );
81 }
82
83 $return_params = [
84 'templately_google_login' => '1',
85 ];
86
87 // Add redirect-to parameter if provided
88 if (!empty($redirect_to)) {
89 $return_params['redirect-to'] = $redirect_to;
90 }
91
92 $site_url_with_params = add_query_arg($return_params, $return_url);
93
94 $query_params = [
95 'site_url' => urlencode($site_url_with_params),
96 'site_ip' => Helper::get_ip(),
97 'state' => wp_generate_password(32, false) // Add unique random state for cache busting
98 ];
99
100 return add_query_arg($query_params, $auth_url);
101 }
102
103 /**
104 * @param array $args
105 * @return string
106 */
107 protected function prepareArgs( $args ) {
108 $prepareArgs = "";
109 foreach ( $args as $key => $value ) {
110 switch ( true ) {
111 case is_int( $value ):
112 case is_bool( $value ):
113 case is_string( $value ) && ( $value === 'true' || $value === 'false' ):
114 $prepareArgs .= "$key:" . $value . ",";
115 break;
116 default:
117 $prepareArgs .= "$key:" . '"' . $value . '"' . ",";
118 break;
119 }
120 }
121
122 return rtrim( $prepareArgs, ',' );
123 }
124
125 /**
126 * Preparing query for the endpoint.
127 *
128 * @param string $query_name
129 * @param string $params
130 * @param array $funcArgs
131 * @param array ...$args
132 * @return Http
133 */
134 public function query( $query_name, $params, $funcArgs = [], ...$args ) {
135 $query = '{';
136 $query .= $query_name;
137 if ( is_array( $funcArgs ) && ! empty( $funcArgs ) ) {
138 $query .= "(" . $this->prepareArgs( $funcArgs ) . ")";
139 }
140 if ( ! empty( $params ) ) {
141 $query .= "{";
142 $query .= $params;
143 $query .= "}";
144 }
145 $query .= '}';
146
147 $this->endpoint = $query_name;
148 $this->query = ! empty( $args ) ? sprintf( $query, ...$args ) : $query;
149 return $this;
150 }
151
152 /**
153 * Preparing mutation for the endpoint.
154 *
155 * @param string $mutate
156 * @param string $params
157 * @param array $funcArgs
158 * @param array ...$args
159 * @return Http
160 */
161 public function mutation( $mutate, $params, $funcArgs = [], ...$args ) {
162 $this->query( $mutate, $params, $funcArgs, ...$args );
163 $mutation = 'mutation';
164 $mutation .= $this->query;
165 $this->endpoint = $mutate;
166 $this->query = ! empty( $args ) ? sprintf( $mutation, ...$args ) : $mutation;
167 return $this;
168 }
169
170 /**
171 * This function is responsible for Remote HTTP POST
172 *
173 * @param string $query
174 * @param array $args
175 * @return mixed
176 */
177 public function post( $args = [] ) {
178 if ( empty( $query ) ) {
179 $query = $this->query;
180 }
181
182 $headers = [
183 'Content-Type' => 'application/json',
184 'x-templately-ip' => Helper::get_ip(),
185 'x-templately-url' => home_url( '/' ),
186 'x-templately-version' => TEMPLATELY_VERSION,
187 ];
188
189 if ( ! empty( $args['headers'] ) ) {
190 $headers = wp_parse_args( $args['headers'], $headers );
191 unset( $args['headers'] );
192 }
193
194 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
195 Helper::log( 'URL: ' . $this->url() );
196 Helper::log( 'QUERY: ' . $query );
197 }
198
199 $_default_args = [
200 'timeout' => $this->dev_mode ? 40 : 30,
201 'headers' => $headers,
202 'body' => wp_json_encode( [
203 'query' => $query
204 ] )
205 ];
206
207 $retryCount = 0;
208 $maxRetries = defined('TEMPLATELY_HTTP_RETRY') ? TEMPLATELY_HTTP_RETRY : 3;
209 $args = wp_parse_args( $args, $_default_args );
210 do {
211 $response = wp_remote_post( $this->url(), $args );
212 $retryCount++;
213 } while ( is_wp_error( $response ) && $retryCount < $maxRetries );
214
215 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
216 Helper::log( 'Retry Count: ' . $retryCount );
217 // Helper::log( 'RAW RESPONSE: ' );
218 // Helper::log( $response );
219 // Helper::log( 'END RAW RESPONSE' );
220 }
221
222 return $this->maybeErrors( $response, $args );
223 }
224
225 /**
226 * Formatting the self::post() response
227 *
228 * @param mixed $response
229 * @param array $args
230 * @return mixed
231 */
232 private function maybeErrors( &$response, $args = [] ) {
233 if ( $response instanceof WP_Error ) {
234 return $response; // Return WP_Error, if it is an error.
235 }
236
237 // Check for verification header before processing response body
238 Helper::check_verification_header( $response );
239 Helper::check_site_disconnection( $response );
240
241 $response_code = wp_remote_retrieve_response_code( $response );
242 $response_message = wp_remote_retrieve_response_message( $response );
243
244 /**
245 * Retrieve Data from Response Body.
246 */
247 $response = json_decode( wp_remote_retrieve_body( $response ), true );
248 /**
249 * If the graphql hit with any error.
250 */
251 if ( ! empty( $response['errors'] ) ) {
252 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
253 Helper::log( 'ERROR: ' );
254 Helper::log( $response['errors'] );
255 Helper::log( 'END ERROR' );
256 }
257 if ( is_array( $response['errors'] ) ) {
258 $wp_error = new WP_Error;
259 array_walk( $response['errors'], function ( $error ) use ( &$wp_error ) {
260 if ( isset( $error['message'] ) ) {
261 if ( $error['message'] === 'validation' ) {
262 array_walk( $error['extensions'], function ( $_error, $_error_key ) use ( &$wp_error ) {
263 if ( $_error_key == 'validation' ) {
264 array_walk( $_error, function ( $v_error, $key ) use ( &$wp_error ) {
265 $wp_error->add( "{$key}_error", $v_error[0] );
266 } );
267 }
268 } );
269 } else {
270 $error_data = [];
271 if(!empty($error["extensions"]["statusText"])) {
272 $error_data["statusText"] = $error["extensions"]["statusText"];
273 }
274 if ( isset( $error['debugMessage'] ) ) {
275 $wp_error->add( 'templately_graphql_error', $error['debugMessage'] );
276 } else {
277 $wp_error->add( 'templately_graphql_error', $error['message'], $error_data );
278 }
279 }
280 }
281 } );
282
283 if( $wp_error->get_error_code() === 'templately_graphql_error' ) {
284 if( $wp_error->get_error_message() == 'Unauthorized' ) {
285 $global_user = Login::get_instance()->delete();
286
287 return [
288 'redirect' => true,
289 'url' => 'sign-in',
290 'user' => $global_user,
291 ];
292 }
293 }
294
295 return $wp_error;
296 }
297 } elseif ( ! empty( $response['status'] ) && $response['status'] === 'error' ) {
298
299 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
300 Helper::log( 'ERROR: ' );
301 Helper::log( $response );
302 Helper::log( 'END ERROR' );
303 }
304
305 $error_data = [];
306 if ( ! empty( $response['statusText'] ) ) {
307 $error_data['statusText'] = $response['statusText'];
308 }
309
310 $error_message = ! empty( $response['message'] ) ? $response['message'] : __( 'Unknown error occurred', 'templately' );
311
312 return new WP_Error( 'templately_api_error', $error_message, $error_data );
313 }
314
315 $_response = isset( $response['data'][$this->endpoint] ) ? $response['data'][$this->endpoint] : [];
316 // {"data":{"connectWithApiKey":{"status":"error","message":"Invalid API key.","user":null}}}
317 if ( ! empty( $response['status'] ) && $response['status'] === 'error' ) {
318
319 }
320
321 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
322 Helper::log( 'RESPONSE: ' );
323 Helper::log( $_response );
324 Helper::log( 'END RESPONSE' );
325 }
326
327 return $_response;
328 }
329 }
330