-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathLink_Controller.php
More file actions
520 lines (452 loc) · 14.1 KB
/
Copy pathLink_Controller.php
File metadata and controls
520 lines (452 loc) · 14.1 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
<?php
/**
* Class Link_Controller
*
* @link https://github.com/googleforcreators/web-stories-wp
*
* @copyright 2020 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
*/
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
declare(strict_types = 1);
namespace Google\Web_Stories\REST_API;
use DOMElement;
use DOMNode;
use DOMNodeList;
use Google\Web_Stories\Infrastructure\HasRequirements;
use Google\Web_Stories\Story_Post_Type;
use Google\Web_Stories_Dependencies\AmpProject\Dom\Document;
use WP_Error;
use WP_Http;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
/**
* API endpoint to allow parsing of metadata from a URL
*
* Class Link_Controller
*
* @phpstan-type SchemaEntry array{
* description: string,
* type: string,
* context: string[],
* default?: mixed,
* }
* @phpstan-type Schema array{
* properties: array<string, SchemaEntry>
* }
*/
class Link_Controller extends REST_Controller implements HasRequirements {
/**
* Story_Post_Type instance.
*
* @var Story_Post_Type Story_Post_Type instance.
*/
private Story_Post_Type $story_post_type;
/**
* Constructor.
*
* @param Story_Post_Type $story_post_type Story_Post_Type instance.
*/
public function __construct( Story_Post_Type $story_post_type ) {
$this->story_post_type = $story_post_type;
$this->namespace = 'web-stories/v1';
$this->rest_base = 'link';
}
/**
* Get the list of service IDs required for this service to be registered.
*
* Needed because the story post type needs to be registered first.
*
* @since 1.13.0
*
* @return string[] List of required services.
*/
public static function get_requirements(): array {
return [ 'story_post_type' ];
}
/**
* Registers routes for links.
*
* @since 1.0.0
*
* @see register_rest_route()
*/
public function register_routes(): void {
register_rest_route(
// @phpstan-ignore argument.type
$this->namespace,
'/' . $this->rest_base,
[
[
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'parse_link' ],
'permission_callback' => [ $this, 'parse_link_permissions_check' ],
'args' => [
'url' => [
'description' => __( 'The URL to process.', 'web-stories' ),
'required' => true,
'type' => 'string',
'format' => 'uri',
'validate_callback' => [ $this, 'validate_url' ],
],
],
],
]
);
}
/**
* Parses a URL to return some metadata for inserting links.
*
* @SuppressWarnings("PHPMD.CyclomaticComplexity")
* @SuppressWarnings("PHPMD.NPathComplexity")
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
*
* @since 1.0.0
*
* @param WP_REST_Request $request Full data about the request.
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
*/
public function parse_link( $request ) {
/**
* Requested URL.
*
* @var string $url
*/
$url = $request['url'];
$url = untrailingslashit( $url );
/**
* Filters the link data TTL value.
*
* @since 1.0.0
*
* @param int $time Time to live (in seconds). Default is 1 day.
* @param string $url The attempted URL.
*/
$cache_ttl = apply_filters( 'web_stories_link_data_cache_ttl', DAY_IN_SECONDS, $url );
$cache_key = 'web_stories_link_data_' . md5( $url );
$data = get_transient( $cache_key );
if ( \is_string( $data ) && ! empty( $data ) ) {
/**
* Decoded cached link data.
*
* @var array{title: string, image: string, description: string}|null $link
*/
$link = json_decode( $data, true );
if ( $link ) {
$response = $this->prepare_item_for_response( $link, $request );
return rest_ensure_response( $response );
}
}
$data = [
'title' => '',
'image' => '',
'description' => '',
];
// Do not request instagram.com, as it redirects to a login page.
// See https://github.com/GoogleForCreators/web-stories-wp/issues/10451.
$matches = [];
$query_string = wp_parse_url( $url, PHP_URL_QUERY );
$check_url = \is_string( $query_string ) ? str_replace( "?$query_string", '', $url ) : $url;
if ( preg_match( '~^https?://(www\.)?instagram\.com/([^/]+)/?$~', $check_url, $matches ) ) {
$data['title'] = \sprintf(
/* translators: %s: Instagram username. */
__( 'Instagram - @%s', 'web-stories' ),
$matches[2]
);
set_transient( $cache_key, wp_json_encode( $data ), $cache_ttl );
$response = $this->prepare_item_for_response( $data, $request );
return rest_ensure_response( $response );
}
$args = [
'limit_response_size' => 153_600, // 150 KB.
'timeout' => 7, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout
];
/**
* Filters the HTTP request args for link data retrieval.
*
* Can be used to adjust timeout and response size limit.
*
* @since 1.0.0
*
* @param array $args Arguments used for the HTTP request
* @param string $url The attempted URL.
* @phpstan-param array{
* method?: string,
* timeout?: float,
* redirection?: int,
* httpversion?: string,
* user-agent?: string,
* reject_unsafe_urls?: bool,
* blocking?: bool,
* headers?: string|array,
* cookies?: array,
* body?: string|array,
* compress?: bool,
* decompress?: bool,
* sslverify?: bool,
* sslcertificates?: string,
* stream?: bool,
* filename?: string,
* limit_response_size?: int,
* } $args See WP_Http::request()
*/
$args = apply_filters( 'web_stories_link_data_request_args', $args, $url );
$response = wp_safe_remote_get( $url, $args );
if ( is_wp_error( $response ) && 'http_request_failed' === $response->get_error_code() ) {
return new \WP_Error( 'rest_invalid_url', __( 'Invalid URL', 'web-stories' ), [ 'status' => 404 ] );
}
if ( WP_Http::OK !== wp_remote_retrieve_response_code( $response ) ) {
// Not saving to cache since the error might be temporary.
$response = $this->prepare_item_for_response( $data, $request );
return rest_ensure_response( $response );
}
$html = wp_remote_retrieve_body( $response );
// Strip <body>.
$html_head_end = stripos( $html, '</head>' );
if ( $html_head_end ) {
$html = substr( $html, 0, $html_head_end );
}
if ( ! $html ) {
set_transient( $cache_key, wp_json_encode( $data ), $cache_ttl );
$response = $this->prepare_item_for_response( $data, $request );
return rest_ensure_response( $response );
}
try {
$doc = Document::fromHtml( $html );
} catch ( \DOMException $exception ) {
set_transient( $cache_key, wp_json_encode( $data ), $cache_ttl );
$response = $this->prepare_item_for_response( $data, $request );
return rest_ensure_response( $response );
}
if ( ! $doc ) {
set_transient( $cache_key, wp_json_encode( $data ), $cache_ttl );
$response = $this->prepare_item_for_response( $data, $request );
return rest_ensure_response( $response );
}
$xpath = $doc->xpath;
// Link title.
$title = '';
$title_query = $xpath->query( '//title' );
if ( $title_query instanceof DOMNodeList && $title_query->length > 0 ) {
$title_node = $title_query->item( 0 );
if ( $title_node instanceof DOMElement ) {
$title = $title_node->textContent;
}
}
if ( ! $title ) {
/**
* List of found elements.
*
* @var DOMNodeList<DOMElement> $og_title_query
*/
$og_title_query = $xpath->query( '//meta[@property="og:title"]' );
$title = $this->get_dom_attribute_content( $og_title_query, 'content' );
}
if ( ! $title ) {
/**
* List of found elements.
*
* @var DOMNodeList<DOMElement> $og_site_name_query
*/
$og_site_name_query = $xpath->query( '//meta[@property="og:site_name"]' );
$title = $this->get_dom_attribute_content( $og_site_name_query, 'content' );
}
// Site icon.
/**
* List of found elements.
*
* @var DOMNodeList<DOMElement> $og_image_query
*/
$og_image_query = $xpath->query( '//meta[@property="og:image"]' );
$image = $this->get_dom_attribute_content( $og_image_query, 'content' );
if ( ! $image ) {
/**
* List of found elements.
*
* @var DOMNodeList<DOMElement> $icon_query
*/
$icon_query = $xpath->query( '//link[contains(@rel, "icon")]' );
$image = $this->get_dom_attribute_content( $icon_query, 'content' );
}
if ( ! $image ) {
/**
* List of found elements.
*
* @var DOMNodeList<DOMElement> $touch_icon_query
*/
$touch_icon_query = $xpath->query( '//link[contains(@rel, "apple-touch-icon")]' );
$image = $this->get_dom_attribute_content( $touch_icon_query, 'href' );
}
// Link description.
/**
* List of found elements.
*
* @var DOMNodeList<DOMElement> $description_query
*/
$description_query = $xpath->query( '//meta[@name="description"]' );
$description = $this->get_dom_attribute_content( $description_query, 'content' );
if ( ! $description ) {
/**
* List of found elements.
*
* @var DOMNodeList<DOMElement> $og_description_query
*/
$og_description_query = $xpath->query( '//meta[@property="og:description"]' );
$description = $this->get_dom_attribute_content( $og_description_query, 'content' );
}
$data = [
'title' => $title ?: '',
'image' => $image ?: '',
'description' => $description ?: '',
];
$response = $this->prepare_item_for_response( $data, $request );
set_transient( $cache_key, wp_json_encode( $data ), $cache_ttl );
return rest_ensure_response( $response );
}
/**
* Prepares a single lock output for response.
*
* @since 1.10.0
*
* @param array $link Link value, default to false is not set.
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response|WP_Error Response object.
*
* @phpstan-param array{title: string, image: string, description: string} $link
* @phpstan-param WP_REST_Request<array{context: string}> $request
*/
public function prepare_item_for_response( $link, $request ) {
$fields = $this->get_fields_for_response( $request );
$schema = $this->get_item_schema();
$data = [];
$check_fields = array_keys( $link );
foreach ( $check_fields as $check_field ) {
if ( ! empty( $schema['properties'][ $check_field ] ) && rest_is_field_included( $check_field, $fields ) ) {
$data[ $check_field ] = rest_sanitize_value_from_schema( $link[ $check_field ], $schema['properties'][ $check_field ] );
}
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
// Wrap the data in a response object.
return rest_ensure_response( $data );
}
/**
* Retrieves the link's schema, conforming to JSON Schema.
*
* @since 1.10.0
*
* @return array Item schema data.
*
* @phpstan-return Schema
*/
public function get_item_schema(): array {
if ( $this->schema ) {
/**
* Schema.
*
* @phpstan-var Schema $schema
*/
$schema = $this->add_additional_fields_schema( $this->schema );
return $schema;
}
$schema = [
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => 'link',
'type' => 'object',
'properties' => [
'title' => [
'description' => __( 'Link\'s title', 'web-stories' ),
'type' => 'string',
'context' => [ 'view', 'edit', 'embed' ],
],
'image' => [
'description' => __( 'Link\'s image', 'web-stories' ),
'type' => 'string',
'format' => 'uri',
'context' => [ 'view', 'edit', 'embed' ],
],
'description' => [
'description' => __( 'Link\'s description', 'web-stories' ),
'type' => 'string',
'context' => [ 'view', 'edit', 'embed' ],
],
],
];
$this->schema = $schema;
/**
* Schema
*
* @phpstan-var Schema $schema
*/
$schema = $this->add_additional_fields_schema( $this->schema );
return $schema;
}
/**
* Checks if current user can process links.
*
* @since 1.0.0
*
* @return true|WP_Error True if the request has read access, WP_Error object otherwise.
*/
public function parse_link_permissions_check() {
if ( ! $this->story_post_type->has_cap( 'edit_posts' ) ) {
return new \WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to process links.', 'web-stories' ), [ 'status' => rest_authorization_required_code() ] );
}
return true;
}
/**
* Callback to validate urls.
*
* @since 1.11.0
*
* @param string $value Value to be validated.
* @return true|WP_Error
*/
public function validate_url( $value ) {
$url = untrailingslashit( $value );
if ( empty( $url ) || ! wp_http_validate_url( $url ) ) {
return new \WP_Error( 'rest_invalid_url', __( 'Invalid URL', 'web-stories' ), [ 'status' => 400 ] );
}
return true;
}
/**
* Retrieve content of a given DOM node attribute.
*
* @since 1.0.0
*
* @param DOMNodeList<DOMElement>|false $query XPath query result.
* @param string $attribute Attribute name.
* @return string|false Attribute content on success, false otherwise.
*/
protected function get_dom_attribute_content( $query, string $attribute ) {
if ( ! $query instanceof DOMNodeList || 0 === $query->length ) {
return false;
}
/**
* DOMElement
*
* @var DOMElement|DOMNode $node
*/
$node = $query->item( 0 );
if ( ! $node instanceof DOMElement ) {
return false;
}
return $node->getAttribute( $attribute );
}
}