PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.5.1
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.5.1
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.1, at includes/Utils/Http.php

319 lines 10.2 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 = '') {
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 // Build the site_url with admin-ajax path
71 $admin_url = admin_url('admin-ajax.php');
72 $admin_params = [
73 'action' => 'templately_google_login',
74 ];
75
76 // Add redirect-to parameter if provided
77 if (!empty($redirect_to)) {
78 $admin_params['redirect-to'] = $redirect_to;
79 }
80
81 $site_url_with_params = add_query_arg($admin_params, $admin_url);
82
83 $query_params = [
84 'site_url' => urlencode($site_url_with_params),
85 'site_ip' => Helper::get_ip(),
86 'state' => wp_generate_password(32, false) // Add unique random state for cache busting
87 ];
88
89 return add_query_arg($query_params, $auth_url);
90 }
91
92 /**
93 * @param array $args
94 * @return string
95 */
96 protected function prepareArgs( $args ) {
97 $prepareArgs = "";
98 foreach ( $args as $key => $value ) {
99 switch ( true ) {
100 case is_int( $value ):
101 case is_bool( $value ):
102 case is_string( $value ) && ( $value === 'true' || $value === 'false' ):
103 $prepareArgs .= "$key:" . $value . ",";
104 break;
105 default:
106 $prepareArgs .= "$key:" . '"' . $value . '"' . ",";
107 break;
108 }
109 }
110
111 return rtrim( $prepareArgs, ',' );
112 }
113
114 /**
115 * Preparing query for the endpoint.
116 *
117 * @param string $query_name
118 * @param string $params
119 * @param array $funcArgs
120 * @param array ...$args
121 * @return Http
122 */
123 public function query( $query_name, $params, $funcArgs = [], ...$args ) {
124 $query = '{';
125 $query .= $query_name;
126 if ( is_array( $funcArgs ) && ! empty( $funcArgs ) ) {
127 $query .= "(" . $this->prepareArgs( $funcArgs ) . ")";
128 }
129 if ( ! empty( $params ) ) {
130 $query .= "{";
131 $query .= $params;
132 $query .= "}";
133 }
134 $query .= '}';
135
136 $this->endpoint = $query_name;
137 $this->query = ! empty( $args ) ? sprintf( $query, ...$args ) : $query;
138 return $this;
139 }
140
141 /**
142 * Preparing mutation for the endpoint.
143 *
144 * @param string $mutate
145 * @param string $params
146 * @param array $funcArgs
147 * @param array ...$args
148 * @return Http
149 */
150 public function mutation( $mutate, $params, $funcArgs = [], ...$args ) {
151 $this->query( $mutate, $params, $funcArgs, ...$args );
152 $mutation = 'mutation';
153 $mutation .= $this->query;
154 $this->endpoint = $mutate;
155 $this->query = ! empty( $args ) ? sprintf( $mutation, ...$args ) : $mutation;
156 return $this;
157 }
158
159 /**
160 * This function is responsible for Remote HTTP POST
161 *
162 * @param string $query
163 * @param array $args
164 * @return mixed
165 */
166 public function post( $args = [] ) {
167 if ( empty( $query ) ) {
168 $query = $this->query;
169 }
170
171 $headers = [
172 'Content-Type' => 'application/json',
173 'x-templately-ip' => Helper::get_ip(),
174 'x-templately-url' => home_url( '/' ),
175 'x-templately-version' => TEMPLATELY_VERSION,
176 ];
177
178 if ( ! empty( $args['headers'] ) ) {
179 $headers = wp_parse_args( $args['headers'], $headers );
180 unset( $args['headers'] );
181 }
182
183 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
184 Helper::log( 'URL: ' . $this->url() );
185 Helper::log( 'QUERY: ' . $query );
186 }
187
188 $_default_args = [
189 'timeout' => $this->dev_mode ? 40 : 30,
190 'headers' => $headers,
191 'body' => wp_json_encode( [
192 'query' => $query
193 ] )
194 ];
195
196 $retryCount = 0;
197 $maxRetries = defined('TEMPLATELY_HTTP_RETRY') ? TEMPLATELY_HTTP_RETRY : 3;
198 $args = wp_parse_args( $args, $_default_args );
199 do {
200 $response = wp_remote_post( $this->url(), $args );
201 $retryCount++;
202 } while ( is_wp_error( $response ) && $retryCount < $maxRetries );
203
204 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
205 Helper::log( 'Retry Count: ' . $retryCount );
206 // Helper::log( 'RAW RESPONSE: ' );
207 // Helper::log( $response );
208 // Helper::log( 'END RAW RESPONSE' );
209 }
210
211 return $this->maybeErrors( $response, $args );
212 }
213
214 /**
215 * Formatting the self::post() response
216 *
217 * @param mixed $response
218 * @param array $args
219 * @return mixed
220 */
221 private function maybeErrors( &$response, $args = [] ) {
222 if ( $response instanceof WP_Error ) {
223 return $response; // Return WP_Error, if it is an error.
224 }
225
226 // Check for verification header before processing response body
227 Helper::check_verification_header( $response );
228 Helper::check_site_disconnection( $response );
229
230 $response_code = wp_remote_retrieve_response_code( $response );
231 $response_message = wp_remote_retrieve_response_message( $response );
232
233 /**
234 * Retrieve Data from Response Body.
235 */
236 $response = json_decode( wp_remote_retrieve_body( $response ), true );
237 /**
238 * If the graphql hit with any error.
239 */
240 if ( ! empty( $response['errors'] ) ) {
241 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
242 Helper::log( 'ERROR: ' );
243 Helper::log( $response['errors'] );
244 Helper::log( 'END ERROR' );
245 }
246 if ( is_array( $response['errors'] ) ) {
247 $wp_error = new WP_Error;
248 array_walk( $response['errors'], function ( $error ) use ( &$wp_error ) {
249 if ( isset( $error['message'] ) ) {
250 if ( $error['message'] === 'validation' ) {
251 array_walk( $error['extensions'], function ( $_error, $_error_key ) use ( &$wp_error ) {
252 if ( $_error_key == 'validation' ) {
253 array_walk( $_error, function ( $v_error, $key ) use ( &$wp_error ) {
254 $wp_error->add( "{$key}_error", $v_error[0] );
255 } );
256 }
257 } );
258 } else {
259 $error_data = [];
260 if(!empty($error["extensions"]["statusText"])) {
261 $error_data["statusText"] = $error["extensions"]["statusText"];
262 }
263 if ( isset( $error['debugMessage'] ) ) {
264 $wp_error->add( 'templately_graphql_error', $error['debugMessage'] );
265 } else {
266 $wp_error->add( 'templately_graphql_error', $error['message'], $error_data );
267 }
268 }
269 }
270 } );
271
272 if( $wp_error->get_error_code() === 'templately_graphql_error' ) {
273 if( $wp_error->get_error_message() == 'Unauthorized' ) {
274 $global_user = Login::get_instance()->delete();
275
276 return [
277 'redirect' => true,
278 'url' => 'sign-in',
279 'user' => $global_user,
280 ];
281 }
282 }
283
284 return $wp_error;
285 }
286 } elseif ( ! empty( $response['status'] ) && $response['status'] === 'error' ) {
287
288 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
289 Helper::log( 'ERROR: ' );
290 Helper::log( $response );
291 Helper::log( 'END ERROR' );
292 }
293
294 $error_data = [];
295 if ( ! empty( $response['statusText'] ) ) {
296 $error_data['statusText'] = $response['statusText'];
297 }
298
299 $error_message = ! empty( $response['message'] ) ? $response['message'] : __( 'Unknown error occurred', 'templately' );
300
301 return new WP_Error( 'templately_api_error', $error_message, $error_data );
302 }
303
304 $_response = isset( $response['data'][$this->endpoint] ) ? $response['data'][$this->endpoint] : [];
305 // {"data":{"connectWithApiKey":{"status":"error","message":"Invalid API key.","user":null}}}
306 if ( ! empty( $response['status'] ) && $response['status'] === 'error' ) {
307
308 }
309
310 if ( defined( 'TEMPLATELY_DEBUG_LOG' ) && TEMPLATELY_DEBUG_LOG ) {
311 Helper::log( 'RESPONSE: ' );
312 Helper::log( $_response );
313 Helper::log( 'END RESPONSE' );
314 }
315
316 return $_response;
317 }
318 }
319