1 | <?php |
---|
2 | /** |
---|
3 | * Utilities. |
---|
4 | * |
---|
5 | * @package automattic/jetpack-publicize |
---|
6 | */ |
---|
7 | |
---|
8 | namespace Automattic\Jetpack\Publicize\Social_Image_Generator; |
---|
9 | |
---|
10 | use Automattic\Jetpack\Connection\Client; |
---|
11 | use Automattic\Jetpack\Publicize\REST_Controller; |
---|
12 | use Automattic\Jetpack\Redirect; |
---|
13 | |
---|
14 | /** |
---|
15 | * Given a post ID, returns the image URL for the generated image. |
---|
16 | * |
---|
17 | * @param int $post_id Post ID to get the URL for. |
---|
18 | * @return string |
---|
19 | */ |
---|
20 | function get_image_url( $post_id ) { |
---|
21 | $post_settings = new Post_Settings( $post_id ); |
---|
22 | $token = $post_settings->get_token(); |
---|
23 | |
---|
24 | if ( ! $post_settings->is_enabled() || empty( $token ) ) { |
---|
25 | return ''; |
---|
26 | } |
---|
27 | |
---|
28 | return add_query_arg( |
---|
29 | array( 'query' => rawurlencode( 't=' . $token ) ), |
---|
30 | Redirect::get_url( 'sigenerate', array( 'site' => null ) ) |
---|
31 | ); |
---|
32 | } |
---|
33 | |
---|
34 | /** |
---|
35 | * Get the parameters for the token body. |
---|
36 | * |
---|
37 | * @param string $text Text to use in the generated image. |
---|
38 | * @param string $image_url Image to use in the generated image. |
---|
39 | * @param string $template Template to use in the generated image. |
---|
40 | * @return array |
---|
41 | */ |
---|
42 | function get_token_body( $text, $image_url, $template ) { |
---|
43 | return array( |
---|
44 | 'text' => $text, |
---|
45 | 'image_url' => $image_url, |
---|
46 | 'template' => $template, |
---|
47 | ); |
---|
48 | } |
---|
49 | |
---|
50 | /** |
---|
51 | * Fetch a token from the WPCOM endpoint. |
---|
52 | * |
---|
53 | * @param string $text The text that will be displayed on the generated image. |
---|
54 | * @param string $image_url The background image URL to be used in the generated image. |
---|
55 | * @param string $template The template slug to use for generating the image. |
---|
56 | * @return string|WP_Error The generated token or a WP_Error object if there's been a problem. |
---|
57 | */ |
---|
58 | function fetch_token( $text, $image_url, $template ) { |
---|
59 | $body = get_token_body( $text, $image_url, $template ); |
---|
60 | $rest_controller = new REST_Controller(); |
---|
61 | $response = Client::wpcom_json_api_request_as_blog( |
---|
62 | sprintf( 'sites/%d/jetpack-social/generate-image-token', absint( \Jetpack_Options::get_option( 'id' ) ) ), |
---|
63 | '2', |
---|
64 | array( |
---|
65 | 'headers' => array( 'content-type' => 'application/json' ), |
---|
66 | 'method' => 'POST', |
---|
67 | ), |
---|
68 | wp_json_encode( array_filter( $body ) ), |
---|
69 | 'wpcom' |
---|
70 | ); |
---|
71 | return $rest_controller->make_proper_response( $response ); |
---|
72 | } |
---|