key = $key; $this->webhook = $webhook; $this->authorization = $authorization; } public function register(): void { add_filter('rest_pre_serve_request', [$this, 'keepOutOfCaches'], 10, 4); register_rest_route(self::NAMESPACE, '/authorize', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'startAuthorization'], 'permission_callback' => '__return_true', ]); register_rest_route(self::NAMESPACE, '/token', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [$this, 'token'], 'permission_callback' => '__return_true', 'args' => [ 'code' => ['type' => 'string', 'required' => true], 'code_verifier' => ['type' => 'string', 'required' => true], 'redirect_uri' => ['type' => 'string', 'required' => true], ], ]); $authorized = [$this, 'authorize']; register_rest_route(self::NAMESPACE, '/site', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'site'], 'permission_callback' => $authorized, ]); register_rest_route(self::NAMESPACE, '/posts', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'posts'], 'permission_callback' => $authorized, 'args' => [ 'type' => ['type' => 'string', 'required' => true], 'language' => ['type' => 'string'], 'modified_after' => ['type' => 'string', 'format' => 'date-time'], 'after' => ['type' => 'integer', 'minimum' => 0, 'default' => 0], 'limit' => ['type' => 'integer', 'minimum' => 1, 'maximum' => self::PAGE_LIMIT, 'default' => self::PAGE_LIMIT], ], ]); register_rest_route(self::NAMESPACE, '/posts/(?P\d+)', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'post'], 'permission_callback' => $authorized, ]); register_rest_route(self::NAMESPACE, '/posts/(?P\d+)/translations', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [$this, 'postTranslations'], 'permission_callback' => $authorized, ]); register_rest_route(self::NAMESPACE, '/posts/(?P\d+)/translations/(?P[A-Za-z0-9_-]+)', [ 'methods' => 'PUT', 'callback' => [$this, 'writeTranslation'], 'permission_callback' => $authorized, 'args' => [ 'fields' => ['type' => 'object', 'required' => true], 'status' => ['type' => 'string', 'enum' => ['publish', 'draft'], 'required' => true], 'sourceHash' => ['type' => 'string', 'required' => true], 'targetHash' => ['type' => ['string', 'null'], 'default' => null], ], ]); register_rest_route(self::NAMESPACE, '/webhook', [ [ 'methods' => 'PUT', 'callback' => [$this, 'saveWebhook'], 'permission_callback' => $authorized, 'args' => ['url' => ['type' => 'string', 'format' => 'uri', 'required' => true]], ], [ 'methods' => WP_REST_Server::DELETABLE, 'callback' => [$this, 'forgetWebhook'], 'permission_callback' => $authorized, ], ]); } public function keepOutOfCaches(bool $served, WP_HTTP_Response $result, WP_REST_Request $request, WP_REST_Server $server): bool { $route = strtolower($request->get_route()); if ($route === '/' . self::NAMESPACE || strpos($route, '/' . self::NAMESPACE . '/') === 0) { $server->send_header('Cache-Control', 'no-store, private'); $server->send_header('X-Accel-Expires', '0'); } return $served; } public function authorize(WP_REST_Request $request) { if (!$this->key->exists()) { return new WP_Error( 'lingo_dev_no_key', 'Connect the site in Lingo.dev first.', ['status' => 401] ); } $key = $request->get_header(Key::HEADER); return is_string($key) && $this->key->verify($key) ? true : new WP_Error('lingo_dev_unauthorized', 'The Lingo.dev key is missing or wrong.', ['status' => 401]); } public function startAuthorization(WP_REST_Request $request) { $params = Authorization::request($request->get_query_params(), Authorization::redirectUris()); if ($params === null) { return new WP_Error( 'lingo_dev_invalid_authorization', 'This link to connect Lingo.dev is incomplete or does not come from Lingo.dev. Start again in Lingo.dev.', ['status' => 400] ); } $response = new WP_REST_Response(null, 302); $response->header('Location', Admin::authorizationUrl($params)); return $response; } public function token(WP_REST_Request $request) { $redeemed = $this->authorization->redeem( (string) $request->get_param('code'), (string) $request->get_param('code_verifier'), (string) $request->get_param('redirect_uri'), time() ); if (!$redeemed) { return new WP_Error( 'lingo_dev_invalid_grant', 'The authorization code is wrong, used or expired. Connect the site again in Lingo.dev.', ['status' => 400] ); } return ['key' => $this->key->issue()]; } public function site(): array { $languages = Plugin::languages(); return [ 'plugin' => Plugin::VERSION, 'wordpress' => get_bloginfo('version'), 'name' => get_bloginfo('name'), 'url' => home_url(), 'restUrl' => rest_url(), 'multilingual' => $languages === null ? null : $languages->name(), 'defaultLanguage' => $languages === null ? null : $languages->defaultLanguage(), 'languages' => $languages === null ? [] : $languages->languages(), 'postTypes' => $languages === null ? [] : $this->postTypes($languages), 'webhook' => $this->webhook->url() !== null, ]; } public function posts(WP_REST_Request $request) { $languages = Plugin::languages(); if ($languages === null) { return $this->noMultilingualPlugin(); } $type = (string) $request->get_param('type'); if (!post_type_exists($type) || !$languages->isTranslated($type)) { return new WP_Error('lingo_dev_invalid_post_type', 'The post type is not translated.', ['status' => 400]); } $language = $request->get_param('language'); $language = is_string($language) && $language !== '' ? $language : $languages->defaultLanguage(); if ($language === null || !$this->isLanguage($languages, $language)) { return new WP_Error('lingo_dev_invalid_language', 'The language is not set up on this site.', ['status' => 400]); } $limit = (int) $request->get_param('limit'); $args = [ 'post_type' => $type, 'post_status' => self::LISTED_STATUSES, 'orderby' => 'ID', 'order' => 'ASC', 'posts_per_page' => $limit, 'ignore_sticky_posts' => true, 'no_found_rows' => true, 'update_post_meta_cache' => false, 'lingo_dev_after' => (int) $request->get_param('after'), ]; $modifiedAfter = $request->get_param('modified_after'); if (is_string($modifiedAfter) && $modifiedAfter !== '') { $timestamp = strtotime($modifiedAfter); if ($timestamp === false) { return new WP_Error('lingo_dev_invalid_date', 'modified_after is not a date.', ['status' => 400]); } $args['lingo_dev_modified_after'] = [ 'gmt' => gmdate('Y-m-d H:i:s', $timestamp), 'local' => wp_date('Y-m-d H:i:s', $timestamp), ]; } add_filter('posts_where', [$this, 'where'], 10, 2); try { $query = $languages->query($args, $language); } finally { remove_filter('posts_where', [$this, 'where'], 10); } $posts = []; foreach ($query->posts as $post) { if (!$post instanceof WP_Post) { continue; } $posts[] = [ 'id' => $post->ID, 'type' => $post->post_type, 'status' => $post->post_status, 'modified' => Content::modified($post), 'title' => $post->post_title, 'translations' => $this->otherTranslations($languages, $post->ID, $language), ]; } $last = end($posts); return [ 'posts' => $posts, 'next' => count($posts) === $limit && $last !== false ? $last['id'] : null, ]; } public function where(string $where, WP_Query $query): string { global $wpdb; $after = (int) $query->get('lingo_dev_after'); if ($after > 0) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.ID > %d", $after); } $modified = $query->get('lingo_dev_modified_after'); if (is_array($modified) && is_string($modified['gmt'] ?? null) && is_string($modified['local'] ?? null)) { $where .= $wpdb->prepare( " AND ({$wpdb->posts}.post_modified_gmt >= %s OR ({$wpdb->posts}.post_modified_gmt = '0000-00-00 00:00:00' AND {$wpdb->posts}.post_modified >= %s))", $modified['gmt'], $modified['local'] ); } return $where; } public function post(WP_REST_Request $request) { $languages = Plugin::languages(); if ($languages === null) { return $this->noMultilingualPlugin(); } $post = $this->translatedPost($languages, (int) $request->get_param('id')); return $post === null ? $this->postNotFound() : $this->view($languages, $post); } public function postTranslations(WP_REST_Request $request) { $languages = Plugin::languages(); if ($languages === null) { return $this->noMultilingualPlugin(); } $source = $this->translatedPost($languages, (int) $request->get_param('id')); if ($source === null) { return $this->postNotFound(); } if ($languages instanceof TranslatePress) { return ['translations' => (object) (new Translations($languages))->read($source)]; } $language = $languages->postLanguage($source->ID); $translations = []; foreach ($language === null ? [] : (array) $this->otherTranslations($languages, $source->ID, $language) as $code => $id) { $translation = $this->translatedPost($languages, (int) $id); if ($translation !== null) { $translations[$code] = $this->view($languages, $translation); } } return ['translations' => (object) $translations]; } public function writeTranslation(WP_REST_Request $request) { $languages = Plugin::languages(); if ($languages === null) { return $this->noMultilingualPlugin(); } $source = $this->translatedPost($languages, (int) $request->get_param('id')); if ($source === null) { return $this->postNotFound(); } $language = (string) $request->get_param('language'); $sourceLanguage = $languages->postLanguage($source->ID); if ($sourceLanguage === null || $language === $sourceLanguage || !$this->isLanguage($languages, $language)) { return new WP_Error( 'lingo_dev_invalid_language', 'The language is not set up on this site, or it is the source post\'s own language.', ['status' => 400] ); } $fields = $request->get_param('fields'); $supported = Content::fieldsOf($source->post_type); if (!is_array($fields) || $fields === []) { return $this->invalidFields($supported); } foreach ($fields as $name => $value) { if (!in_array($name, $supported, true) || !is_string($value)) { return $this->invalidFields($supported); } } $targetHash = $request->get_param('targetHash'); $translation = $languages instanceof TranslatePress ? new Translations($languages) : new Translation($languages, $this->webhook); return $translation->write( $source, $language, $fields, (string) $request->get_param('status'), (string) $request->get_param('sourceHash'), is_string($targetHash) ? $targetHash : null ); } public function saveWebhook(WP_REST_Request $request) { $url = (string) $request->get_param('url'); if (!$this->webhook->accepts($url)) { return new WP_Error('lingo_dev_invalid_webhook', 'The webhook URL must use https.', ['status' => 400]); } $this->webhook->save($url); return ['webhook' => true]; } public function forgetWebhook(): array { $this->webhook->forget(); return ['webhook' => false]; } private function view(Languages $languages, WP_Post $post): array { $language = $languages->postLanguage($post->ID); $fields = Content::read($post); return [ 'id' => $post->ID, 'type' => $post->post_type, 'status' => $post->post_status, 'language' => $language, 'modified' => Content::modified($post), 'fields' => $fields, 'hash' => Content::hash($fields), 'translations' => $language === null ? [] : $this->otherTranslations($languages, $post->ID, $language), ]; } private function postTypes(Languages $languages): array { $postTypes = []; foreach (get_post_types(['show_ui' => true], 'objects') as $postType) { if ($postType->name === 'attachment' || !$languages->isTranslated($postType->name)) { continue; } $fields = Content::fieldsOf($postType->name); if ($fields === []) { continue; } $postTypes[] = ['name' => $postType->name, 'label' => $postType->labels->name, 'fields' => $fields]; } return $postTypes; } private function translatedPost(Languages $languages, int $id): ?WP_Post { $post = get_post($id); return $post instanceof WP_Post && in_array($post->post_status, self::LISTED_STATUSES, true) && $languages->isTranslated($post->post_type) ? $post : null; } private function otherTranslations(Languages $languages, int $postId, string $language): object { $translations = $languages->translations($postId); unset($translations[$language]); return (object) $translations; } private function isLanguage(Languages $languages, string $code): bool { foreach ($languages->languages() as $language) { if ($language['code'] === $code) { return true; } } return false; } private function noMultilingualPlugin(): WP_Error { return new WP_Error( 'lingo_dev_no_multilingual_plugin', "Lingo.dev didn't recognize a translation plugin on this site. Contact support@lingo.dev.", ['status' => 409] ); } private function postNotFound(): WP_Error { return new WP_Error('lingo_dev_post_not_found', 'No translated post has this ID.', ['status' => 404]); } private function invalidFields(array $supported): WP_Error { return new WP_Error( 'lingo_dev_invalid_fields', 'fields must map some of these names to strings: ' . implode(', ', $supported) . '.', ['status' => 400] ); } }