Version en ingles y español
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Options\Business;
|
||||
|
||||
use WP_Syntex\Polylang\Options\Primitive\Abstract_Boolean;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Class defining machine translation boolean option.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Machine_Translation_Enabled extends Abstract_Boolean {
|
||||
/**
|
||||
* Returns option key.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return 'machine_translation_enabled'
|
||||
*/
|
||||
public static function key(): string {
|
||||
return 'machine_translation_enabled';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the description used in the JSON schema.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_description(): string {
|
||||
return __( 'Enable machine translation.', 'polylang-pro' );
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Options\Business;
|
||||
|
||||
use WP_Error;
|
||||
use WP_Syntex\Polylang\Options\Options;
|
||||
use WP_Syntex\Polylang\Options\Abstract_Option;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Factory;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Deepl as Service;
|
||||
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Class defining machine translation services array option.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @phpstan-import-type DeeplOptions from \WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Deepl
|
||||
*/
|
||||
class Machine_Translation_Services extends Abstract_Option {
|
||||
/**
|
||||
* Returns option key.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return 'machine_translation_services'
|
||||
*/
|
||||
public static function key(): string {
|
||||
return 'machine_translation_services';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes option's value.
|
||||
* Can populate the `$errors` property with blocking and non-blocking errors: in case of non-blocking errors,
|
||||
* the value is sanitized and can be stored.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $value Value to sanitize.
|
||||
* @param Options $options All options.
|
||||
* @return array|WP_Error The sanitized value. An instance of `WP_Error` in case of blocking error.
|
||||
*
|
||||
* @phpstan-return array{deepl: DeeplOptions}|WP_Error
|
||||
*/
|
||||
protected function sanitize( $value, Options $options ) {
|
||||
$value = parent::sanitize( $value, $options );
|
||||
|
||||
if ( is_wp_error( $value ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @var array{deepl: DeeplOptions} $value */
|
||||
if ( empty( $value['deepl']['api_key'] ) ) {
|
||||
// Reset the glossary ID if the API key is empty.
|
||||
$value['deepl']['glossary_id'] = '';
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds information to the site health info array.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param Options $options An instance of the Options class providing additional configuration.
|
||||
*
|
||||
* @return array The updated site health information.
|
||||
*/
|
||||
public function get_site_health_info( Options $options ): array { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
|
||||
/**
|
||||
* @var array{deepl: DeeplOptions} $value
|
||||
*/
|
||||
$value = $this->get();
|
||||
|
||||
if ( empty( $value['deepl']['api_key'] ) ) {
|
||||
return $this->format_single_value_for_site_health_info( __( 'DeepL is activated but no API key is set.', 'polylang-pro' ) );
|
||||
}
|
||||
$service = new Service(
|
||||
array(
|
||||
'api_key' => $value['deepl']['api_key'],
|
||||
'formality' => $value['deepl']['formality'] ?? null,
|
||||
),
|
||||
PLL()->model
|
||||
);
|
||||
|
||||
$result = $service->get_client()->is_api_key_valid();
|
||||
|
||||
if ( $result->has_errors() ) {
|
||||
return $this->format_single_value_for_site_health_info( $result->get_error_message() );
|
||||
}
|
||||
|
||||
return $this->format_single_value_for_site_health_info( __( 'The API key is valid', 'polylang-pro' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default value.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function get_default() {
|
||||
$services = array();
|
||||
|
||||
foreach ( Factory::get_classnames() as $service ) {
|
||||
$services[ $service::get_slug() ] = array();
|
||||
}
|
||||
|
||||
return $services;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the JSON schema part specific to this option.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return array Partial schema.
|
||||
*
|
||||
* @phpstan-return array{
|
||||
* type: 'object',
|
||||
* properties: array<
|
||||
* non-falsy-string,
|
||||
* array{
|
||||
* type: 'object',
|
||||
* properties: array,
|
||||
* additionalProperties: false
|
||||
* }
|
||||
* >,
|
||||
* additionalProperties: false
|
||||
* }
|
||||
*/
|
||||
protected function get_data_structure(): array {
|
||||
$structure = array(
|
||||
'type' => 'object', // Correspond to associative array in PHP, @see{https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#primitive-types}.
|
||||
'properties' => array(),
|
||||
'additionalProperties' => false,
|
||||
);
|
||||
|
||||
foreach ( Factory::get_classnames() as $service ) {
|
||||
$structure['properties'][ $service::get_slug() ] = array(
|
||||
'type' => 'object',
|
||||
'properties' => $service::get_option_schema(),
|
||||
'additionalProperties' => false,
|
||||
);
|
||||
}
|
||||
|
||||
return $structure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the description used in the JSON schema.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_description(): string {
|
||||
return __( 'Settings for machine translation services: DeepL\'s API key, formality, and glossary for now.', 'polylang-pro' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Options\Business;
|
||||
|
||||
use WP_Syntex\Polylang\Options\Abstract_Option;
|
||||
use WP_Syntex\Polylang\Options\Options;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Class defining media array option.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Media extends Abstract_Option {
|
||||
/**
|
||||
* Returns option key.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return 'media'
|
||||
*/
|
||||
public static function key(): string {
|
||||
return 'media';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default value.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function get_default() {
|
||||
return array( 'duplicate' => false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds information to the site health info array.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param Options $options An instance of the Options class providing additional configuration.
|
||||
*
|
||||
* @return array The updated site health information.
|
||||
*/
|
||||
public function get_site_health_info( Options $options ): array { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
|
||||
$key = self::key();
|
||||
$fields = array();
|
||||
|
||||
/** @var array<string, mixed> $value */
|
||||
$value = $this->get();
|
||||
foreach ( $value as $sub_key => $sub_value ) {
|
||||
if ( $sub_value ) {
|
||||
$fields[ "$key-$sub_key" ] = __( 'Enabled', 'polylang-pro' );
|
||||
}
|
||||
}
|
||||
|
||||
return $this->format_single_value_for_site_health_info( $this->format_array_for_site_health_info( $fields ) );
|
||||
}
|
||||
/**
|
||||
* Returns the JSON schema part specific to this option.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return array Partial schema.
|
||||
*
|
||||
* @phpstan-return array{
|
||||
* type: 'object',
|
||||
* properties: array{
|
||||
* duplicate: array{
|
||||
* type: 'boolean',
|
||||
* required: true
|
||||
* }
|
||||
* },
|
||||
* additionalProperties: false
|
||||
* }
|
||||
*/
|
||||
protected function get_data_structure(): array {
|
||||
return array(
|
||||
'type' => 'object', // Correspond to associative array in PHP, @see{https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#primitive-types}.
|
||||
'properties' => array(
|
||||
'duplicate' => array(
|
||||
'type' => 'boolean',
|
||||
'required' => true,
|
||||
),
|
||||
),
|
||||
'additionalProperties' => false,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the description used in the JSON schema.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_description(): string {
|
||||
return __( 'Automatically duplicate media in all languages when uploading a new file.', 'polylang-pro' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Options;
|
||||
|
||||
use WP_Syntex\Polylang\Options\Registry as PLL_Registry;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Polylang Pro's options registry.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Registry extends PLL_Registry {
|
||||
protected const OPTIONS = array(
|
||||
Business\Media::class,
|
||||
Business\Machine_Translation_Enabled::class,
|
||||
Business\Machine_Translation_Services::class,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF;
|
||||
|
||||
use PLL_Abstract_Deactivate;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Labels\Field_Groups;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* ACF integration deactivation class.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Deactivate extends PLL_Abstract_Deactivate {
|
||||
/**
|
||||
* Plugin deactivation.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected static function process(): void {
|
||||
Field_Groups::clear_cache();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF;
|
||||
|
||||
use WP_Post;
|
||||
use WP_Term;
|
||||
use Translations;
|
||||
use PLL_Language;
|
||||
use PLL_Export_Data;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Post;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Term;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Media;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Blocks;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Copy;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Location_Language;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Synchronize;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Collect_Post_Ids;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Collect_Term_Ids;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Abstract_Object;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Holds all hooks registrations regarding field translations logic.
|
||||
* Controls and applies strategies to ACF fields regarding
|
||||
* object types and context (e.g. export, import, update, new translation creation, blocks...).
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Dispatcher {
|
||||
/**
|
||||
* Setup filters.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function on_acf_init() {
|
||||
/*
|
||||
* Removes ACF fields from synchronized metas by Polylang, this way ACF integration manage itself the synchronization.
|
||||
* Applied after `PLL_Sync_Post_Model::copy_post_metas/copy_taxonomies` for it to be effective.
|
||||
*/
|
||||
add_filter( 'pll_copy_post_metas', array( Post::class, 'remove_acf_metas_from_pll_sync' ), 10, 4 );
|
||||
add_filter( 'pll_copy_term_metas', array( Term::class, 'remove_acf_metas_from_pll_sync' ), 10, 4 );
|
||||
|
||||
add_action( 'pll_post_synchronized', array( static::class, 'on_post_synchronized' ), 10, 4 );
|
||||
|
||||
add_action( 'pll_duplicate_term', array( static::class, 'on_duplicate_term' ), 10, 3 );
|
||||
|
||||
add_filter( 'acf/update_value', array( static::class, 'update' ), 5, 3 );
|
||||
add_filter( 'acf/pre_render_field', array( static::class, 'translate_rendered_field' ), 10, 2 );
|
||||
|
||||
add_action( 'pll_after_post_translation', array( static::class, 'translate' ), 10, 4 );
|
||||
add_action( 'pll_after_term_translation', array( static::class, 'translate' ), 10, 4 );
|
||||
add_action( 'pll_after_post_export', array( static::class, 'export' ), 10, 3 );
|
||||
add_action( 'pll_after_term_export', array( static::class, 'export' ), 10, 3 );
|
||||
|
||||
add_filter( 'pll_collect_post_ids', array( static::class, 'collect_post_ids' ), 10, 2 );
|
||||
add_filter( 'pll_collect_term_ids', array( static::class, 'collect_term_ids' ), 10, 2 );
|
||||
|
||||
if ( PLL()->options['media_support'] ) {
|
||||
add_action( 'pll_translate_media', array( static::class, 'copy_media_fields' ), 10, 3 );
|
||||
}
|
||||
|
||||
add_action( 'admin_enqueue_scripts', array( Post::class, 'admin_enqueue_scripts' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( Term::class, 'admin_enqueue_scripts' ) );
|
||||
add_action( 'wp_ajax_acf_post_lang_choice', array( Post::class, 'on_ajax_post_lang_choice' ) );
|
||||
add_action( 'wp_ajax_acf_term_lang_choice', array( Term::class, 'on_ajax_term_lang_choice' ) );
|
||||
add_filter( 'acf/fields/relationship/query', array( static::class, 'add_language_to_query' ), 10, 3 );
|
||||
add_filter( 'acf/fields/post_object/query', array( static::class, 'add_language_to_query' ), 10, 3 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes ACF blocks integration when blocks are registered.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function on_blocks_registered(): void {
|
||||
if ( ! function_exists( 'acf_get_block_types' ) || empty( acf_get_block_types() ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
add_filter( 'pll_collect_post_ids', array( static::class, 'collect_post_ids_in_blocks' ), 10, 2 );
|
||||
add_filter( 'pll_collect_term_ids', array( static::class, 'collect_term_ids_in_blocks' ), 10, 2 );
|
||||
add_filter( 'pll_translate_blocks_with_context', array( static::class, 'copy_blocks' ), 10, 3 );
|
||||
add_filter( 'pll_filter_translated_post', array( static::class, 'translate_blocks' ), 10, 4 );
|
||||
add_action( 'pll_after_post_export', array( static::class, 'export_blocks' ), 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the field about to be rendered.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @param int|string $acf_id ACF post ID.
|
||||
* @return mixed Modified custom field.
|
||||
*/
|
||||
public static function translate_rendered_field( $field, $acf_id ) {
|
||||
$object = static::get_by_acf_id( $acf_id );
|
||||
return empty( $object ) ? $field : $object->translate_rendered_field( $field );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the custom field value when updated.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param mixed $value Custom field value.
|
||||
* @param int|string $acf_id ACF post ID.
|
||||
* @param array $field Custom field definition.
|
||||
* @return mixed Modified custom field value.
|
||||
*/
|
||||
public static function update( $value, $acf_id, $field ) {
|
||||
$object = static::get_by_acf_id( $acf_id );
|
||||
return empty( $object ) ? $value : $object->update( $value, $field );
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies or synchronizes ACF custom fields when using Polylang's copy post function (and not the post-new.php where ACF filters are applied).
|
||||
* (e.g. using bulk translate, creating a synchronized post).
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $post_id ID of the source post.
|
||||
* @param int $tr_post_id ID of the target post.
|
||||
* @param string $lang Language of the target post.
|
||||
* @param string $sync `sync` if doing synchro, `copy` otherwise.
|
||||
* @return void
|
||||
*
|
||||
* @phpstan-param 'sync'|'copy' $sync
|
||||
*/
|
||||
public static function on_post_synchronized( $post_id, $tr_post_id, $lang, $sync ) {
|
||||
( new Post( $post_id ) )->on_post_synchronized( $tr_post_id, $lang, $sync );
|
||||
}
|
||||
|
||||
/**
|
||||
* Export custom fields to translate.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Export_Data $export The export object.
|
||||
* @param object $from The object to export.
|
||||
* @param object|null $to The translated object if it exists, `null` otherwise.
|
||||
* @return void
|
||||
*/
|
||||
public static function export( $export, $from, $to ) {
|
||||
$object = self::get_by_object( $from );
|
||||
if ( ! empty( $object ) && $export instanceof PLL_Export_Data ) {
|
||||
$object->export( $export, $to );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects post IDs from fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int[] $linked_ids Object IDs linked to a post.
|
||||
* @param WP_Post $post The post we get other post from.
|
||||
* @return int[]
|
||||
*/
|
||||
public static function collect_post_ids( $linked_ids, $post ) {
|
||||
$object = self::get_by_object( $post );
|
||||
|
||||
if ( ! empty( $object ) ) {
|
||||
return array_merge( (array) $linked_ids, ( new Collect_Post_Ids() )->get( $object ) );
|
||||
}
|
||||
|
||||
return $linked_ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects post IDs from fields in ACF blocks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int[] $linked_ids Object IDs linked to a post.
|
||||
* @param WP_Post $post The post we get other post from.
|
||||
* @return int[]
|
||||
*/
|
||||
public static function collect_post_ids_in_blocks( $linked_ids, $post ) {
|
||||
if ( has_blocks( $post ) ) {
|
||||
$linked_ids = array_merge( (array) $linked_ids, ( new Collect_Post_Ids() )->get( new Blocks( $post->ID ) ) );
|
||||
}
|
||||
|
||||
return $linked_ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects term IDs from fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int[] $linked_ids Object IDs linked to a post.
|
||||
* @param WP_Post $post The post we get other term from.
|
||||
* @return int[]
|
||||
*/
|
||||
public static function collect_term_ids( $linked_ids, $post ) {
|
||||
$object = self::get_by_object( $post );
|
||||
|
||||
if ( ! empty( $object ) ) {
|
||||
return array_merge( (array) $linked_ids, ( new Collect_Term_Ids() )->get( $object ) );
|
||||
}
|
||||
|
||||
return $linked_ids;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Collects term IDs from fields in ACF blocks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int[] $linked_ids Object IDs linked to a post.
|
||||
* @param WP_Post $post The post we get other term from.
|
||||
* @return int[]
|
||||
*/
|
||||
public static function collect_term_ids_in_blocks( $linked_ids, $post ) {
|
||||
if ( has_blocks( $post ) ) {
|
||||
$linked_ids = array_merge( (array) $linked_ids, ( new Collect_Term_Ids() )->get( new Blocks( $post->ID ) ) );
|
||||
}
|
||||
|
||||
return $linked_ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the custom fields from a given object.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param object $from Source object to get the custom fields from.
|
||||
* @param object $to Translated object to translate the custom fields from.
|
||||
* @param PLL_Language $target_lang Target language object.
|
||||
* @param Translations $translations A set of translations to search the custom fields translations in.
|
||||
* @return void
|
||||
*/
|
||||
public static function translate( $from, $to, $target_lang, $translations ) {
|
||||
/*
|
||||
* Remove filter for `Dispatcher::translate_rendered_field` to avoid running `Strategy\Copy` on the same object.
|
||||
* For instance, when translating fields with DeepL, we don't want to override the translated values with the original ones with `Strategy\Copy`.
|
||||
*/
|
||||
remove_filter( 'acf/pre_render_field', array( self::class, 'translate_rendered_field' ) );
|
||||
|
||||
$object = self::get_by_object( $from );
|
||||
if ( ! empty( $object ) && $target_lang instanceof PLL_Language && $translations instanceof Translations ) {
|
||||
$object->translate( $to, $target_lang, $translations );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds the language of the current object to the arguments that will be used for the query
|
||||
* in the `relationship` and `post_object` ACF fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $args Arguments to retrieve posts.
|
||||
* @param array $field The current field.
|
||||
* @param int|string $acf_id ACF post ID.
|
||||
* @return array The arguments to retrieve posts with the current object language.
|
||||
*/
|
||||
public static function add_language_to_query( $args, $field, $acf_id ) {
|
||||
/**
|
||||
* Gets the language sent with AJAX to reload fields in the right language.
|
||||
* For the term creation page, since there is no current language.
|
||||
* And for the term edit page when switching languages, since the language is not saved on switch.
|
||||
* See `addFilter` on `relationship_ajax_data` and `select2_ajax_data` in `term.js` for the language dispatch.
|
||||
*/
|
||||
$language = isset( $_POST['lang'] ) ? PLL()->model->languages->get( sanitize_key( $_POST['lang'] ) ) : null; // phpcs:ignore WordPress.Security.NonceVerification.Missing
|
||||
if ( isset( $language ) && $language instanceof PLL_Language ) {
|
||||
$args['lang'] = $language->slug;
|
||||
return $args;
|
||||
}
|
||||
|
||||
// Otherwise it's a term editing page (displayed without language switch) or a post editing/creation page.
|
||||
$object = static::get_by_acf_id( $acf_id );
|
||||
return empty( $object ) ? $args : $object->add_language_to_query( $args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the media fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $from_id The source media ID.
|
||||
* @param int $to_id The target media ID.
|
||||
* @param PLL_Language $target_language The target language.
|
||||
* @return void
|
||||
*/
|
||||
public static function copy_media_fields( $from_id, $to_id, $target_language ) {
|
||||
( new Media( $from_id ) )->copy_fields( $to_id, $target_language );
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves ACF fields for a term that was automatically duplicated when a post has been duplicated.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $from Term ID of the source term.
|
||||
* @param int $to Term ID of the new term translation.
|
||||
* @param string $lang Language code of the new translation.
|
||||
* @return void
|
||||
*/
|
||||
public static function on_duplicate_term( $from, $to, $lang ) {
|
||||
$lang = PLL()->model->get_language( $lang );
|
||||
if ( $lang instanceof PLL_Language ) {
|
||||
( new Term( $from ) )->apply_to_all_fields(
|
||||
new Copy(),
|
||||
$to,
|
||||
array( 'target_language' => $lang )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the field values in blocks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $blocks The blocks.
|
||||
* @param PLL_Language $target_lang The target language.
|
||||
* @param WP_Post|null $source_post The source post, `null` if not available.
|
||||
* @return array The blocks.
|
||||
*/
|
||||
public static function copy_blocks( $blocks, $target_lang, $source_post ) {
|
||||
if ( ! is_array( $blocks ) || ! $target_lang instanceof PLL_Language || ! $source_post instanceof WP_Post ) {
|
||||
return $blocks;
|
||||
}
|
||||
return ( new Blocks() )->copy( $blocks, $target_lang, $source_post );
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates fields in blocks during import.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Post $to Translated post where to translate the custom fields included in blocks.
|
||||
* @param WP_Post $from Source post where to get the custom fields included in blocks.
|
||||
* @param PLL_Language $target_lang The target language.
|
||||
* @param Translations $translations A set of translations where to search translations of the custom fields translations included in blocks.
|
||||
* @return WP_Post The translated post.
|
||||
*/
|
||||
public static function translate_blocks( $to, $from, $target_lang, $translations ) {
|
||||
if ( ! $to instanceof WP_Post ) {
|
||||
return $to;
|
||||
}
|
||||
|
||||
return ( new Blocks( $from->ID ) )->translate( $to, $target_lang, $translations );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds ACF fields in blocks to the exported data.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Export_Data $export The export data.
|
||||
* @param WP_Post $from The source post.
|
||||
* @return void
|
||||
*/
|
||||
public static function export_blocks( $export, $from ) {
|
||||
( new Blocks( $from->ID ) )->export( $export );
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an Abstract_Object based on the object type, typically post or term.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int|string $acf_id ACF post ID.
|
||||
* @return Abstract_Object|null.
|
||||
*/
|
||||
protected static function get_by_acf_id( $acf_id ): ?Abstract_Object {
|
||||
$decoded = acf_decode_post_id( $acf_id );
|
||||
$id = (int) $decoded['id'];
|
||||
|
||||
switch ( $decoded['type'] ) {
|
||||
case 'post':
|
||||
if ( PLL()->options['media_support'] && 'attachment' === get_post_type( $id ) ) {
|
||||
return new Media( $id );
|
||||
}
|
||||
if ( pll_is_translated_post_type( (string) get_post_type( $id ) ) ) {
|
||||
return new Post( $id );
|
||||
}
|
||||
break;
|
||||
case 'term':
|
||||
$term = get_term( $id );
|
||||
if ( $term instanceof WP_Term && pll_is_translated_taxonomy( $term->taxonomy ) ) {
|
||||
return new Term( $id );
|
||||
}
|
||||
|
||||
// No nonce to check.
|
||||
if ( 0 === $id && ! empty( $_GET['new_lang'] ) && ! empty( $_GET['taxonomy'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
&& pll_is_translated_taxonomy( sanitize_key( $_GET['taxonomy'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
// This is a term creation with `term_0`, see `acf_form_taxonomy::add_term()`.
|
||||
return new Term( $id );
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an Abstract_Object based on the WP object, typically `WP_Post` or `WP_Term`.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param object $object The object.
|
||||
* @return Abstract_Object|null.
|
||||
*/
|
||||
protected static function get_by_object( $object ): ?Abstract_Object {
|
||||
if ( $object instanceof WP_Post ) {
|
||||
if ( 'attachment' === $object->post_type && PLL()->options['media_support'] ) {
|
||||
return new Media( $object->ID );
|
||||
}
|
||||
if ( pll_is_translated_post_type( $object->post_type ) ) {
|
||||
return new Post( (int) $object->ID );
|
||||
}
|
||||
}
|
||||
if ( $object instanceof WP_Term && pll_is_translated_taxonomy( $object->taxonomy ) ) {
|
||||
return new Term( $object->term_id );
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Entity;
|
||||
|
||||
use Translations;
|
||||
use PLL_Language;
|
||||
use PLL_Export_Data;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Dispatcher;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Copy;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Export;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Import;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Fields\Repeater;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Synchronize;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Abstract_Strategy;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Abstract class to handle objects such posts and terms.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
abstract class Abstract_Object implements Translatable_Entity_Interface {
|
||||
/**
|
||||
* Stores fields to avoid reverse synchronization.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private static $updated = array();
|
||||
|
||||
/**
|
||||
* Object ID, could be a source or target.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $id The object ID, default to 0.
|
||||
*/
|
||||
public function __construct( int $id = 0 ) {
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the field about to be rendered.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return array Custom field of the target object with a value.
|
||||
*/
|
||||
public function translate_rendered_field( $field ) {
|
||||
if ( empty( $_GET['new_lang'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return $field;
|
||||
}
|
||||
|
||||
$lang = PLL()->model->get_language( sanitize_key( $_GET['new_lang'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
if ( empty( $lang ) ) {
|
||||
return $field;
|
||||
}
|
||||
|
||||
$from_id = $this->get_from_id_in_request();
|
||||
if ( empty( $from_id ) || $from_id === $this->get_id() ) {
|
||||
return $field;
|
||||
}
|
||||
|
||||
$from_value = Repeater::get_value( static::acf_id( $from_id ), $field );
|
||||
$original_value = $field['value'] ?? ( $field['default_value'] ?? null );
|
||||
$field['value'] = ( new Copy() )->execute(
|
||||
$this,
|
||||
$from_value,
|
||||
$field,
|
||||
array(
|
||||
'target_language' => $lang,
|
||||
'source_language' => PLL()->model->{$this->get_type()}->get_language( $from_id ),
|
||||
'original_value' => $original_value,
|
||||
)
|
||||
);
|
||||
|
||||
if ( ! empty( $field['value'] ) && Repeater::is_paginated( $field ) ) {
|
||||
add_filter( 'acf/prepare_field', array( Repeater::class, 'change_row_keys' ) );
|
||||
}
|
||||
|
||||
return $field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the custom field value of the current object.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @return mixed Custom field value of the target object.
|
||||
*/
|
||||
public function update( $value, $field ) {
|
||||
// Avoid reverse sync.
|
||||
if ( in_array( $this->get_storage_key( $this->get_id(), $field['key'] ), self::$updated, true ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$strategy = new Synchronize( new Copy() );
|
||||
|
||||
if ( ! $strategy->can_execute( $field ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$translations = PLL()->model->{$this->get_type()}->get_translations( $this->get_id() );
|
||||
|
||||
$this->mark_subfields_as_updated( $field, array_values( $translations ) );
|
||||
|
||||
foreach ( $translations as $lang => $tr_id ) {
|
||||
if ( $this->get_id() === $tr_id ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/** @var PLL_Language */
|
||||
$lang = PLL()->model->get_language( $lang );
|
||||
|
||||
self::$updated[] = $this->get_storage_key( $tr_id, $field['key'] );
|
||||
|
||||
$acf_id = static::acf_id( $tr_id );
|
||||
$tr_value = acf_get_value( $acf_id, $field );
|
||||
$tr_value = $strategy->execute(
|
||||
$this,
|
||||
$value,
|
||||
$field,
|
||||
array(
|
||||
'target_language' => $lang,
|
||||
'original_value' => $tr_value,
|
||||
'target_id' => $tr_id,
|
||||
)
|
||||
);
|
||||
|
||||
if ( ! empty( $field['sub_fields'] ) && is_array( $tr_value ) && empty( $tr_value ) ) {
|
||||
/*
|
||||
* The fields has subfields but they have been removed
|
||||
* by `Abstract_Strategy::apply_on_subfield()`
|
||||
* as they cannot be synchronized, so do not update.
|
||||
*/
|
||||
continue;
|
||||
}
|
||||
|
||||
$tr_value = Repeater::reset_row_keys( $tr_value, $field );
|
||||
|
||||
acf_update_value( $tr_value, $acf_id, $field );
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively pre-marks all subfields of a container field as updated for all translation IDs.
|
||||
*
|
||||
* When ACF saves a container field, its `update_value()` hook calls `acf_update_value()`
|
||||
* for each subfield individually, re-triggering our hook.
|
||||
* This causes redundant sync operations and corrupts the ACF value store for translations that have not yet been
|
||||
* processed by our main loop, shifting their `original_value` indexes.
|
||||
*
|
||||
* Pre-marking all subfield keys prevents these cascade calls from executing.
|
||||
*
|
||||
* @since 3.8.2
|
||||
*
|
||||
* @param array $field The field definition.
|
||||
* @param int[] $object_ids All object IDs in the translation group.
|
||||
* @return void
|
||||
*/
|
||||
private function mark_subfields_as_updated( array $field, array $object_ids ): void {
|
||||
$sub_fields = $field['sub_fields'] ?? array();
|
||||
|
||||
// Merge layouts' subfields into the main subfields array.
|
||||
foreach ( $field['layouts'] ?? array() as $layout ) {
|
||||
$sub_fields = array_merge( $sub_fields, $layout['sub_fields'] ?? array() );
|
||||
}
|
||||
|
||||
// Process all gathered subfields and recurse.
|
||||
foreach ( $sub_fields as $sub_field ) {
|
||||
foreach ( $object_ids as $any_id ) {
|
||||
self::$updated[] = $this->get_storage_key( $any_id, $sub_field['key'] );
|
||||
}
|
||||
$this->mark_subfields_as_updated( $sub_field, $object_ids );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a strategy on fields from the current object to a target object.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Strategy $strategy Strategy to execute.
|
||||
* @param int $to ID of the target object.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type mixed $original_value Optional. The translated value of the field, if any.
|
||||
* @type bool $update Optional. Tells if we can update the target ID fields, default `true`.
|
||||
* }
|
||||
* @return void
|
||||
*/
|
||||
public function apply_to_all_fields( Abstract_Strategy $strategy, int $to = 0, array $args = array() ) {
|
||||
// Removes filters on `Dispatcher::update()` to avoid unnecessary operations on `acf_update_value`.
|
||||
remove_filter( 'acf/update_value', array( Dispatcher::class, 'update' ), 5 );
|
||||
|
||||
$fields = get_field_objects( static::acf_id( $this->get_id() ), false );
|
||||
|
||||
if ( empty( $fields ) ) {
|
||||
$fields = array();
|
||||
}
|
||||
|
||||
$args['update'] = ! isset( $args['update'] ) || (bool) $args['update'];
|
||||
|
||||
foreach ( $fields as $field ) {
|
||||
if ( empty( $field['value'] ) && ! is_string( $field['value'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$args['original_value'] = acf_get_value( static::acf_id( $to ), $field );
|
||||
if ( empty( $args['original_value'] ) ) {
|
||||
$args['original_value'] = $field['default_value'] ?? null;
|
||||
}
|
||||
|
||||
$tr_value = $strategy->execute(
|
||||
$this,
|
||||
$field['value'],
|
||||
$field,
|
||||
$args
|
||||
);
|
||||
|
||||
if ( $to <= 0 || empty( $args['update'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/*
|
||||
* Prevent row duplication with paginated repeaters:
|
||||
* Since we're copying the whole list of rows, we don't need `acf_field_repeater::update_value()` to
|
||||
* decide which row is new, modified, etc. Just save it as we provide it.
|
||||
*/
|
||||
$field['pagination'] = 0;
|
||||
|
||||
acf_update_value(
|
||||
$tr_value,
|
||||
static::acf_id( $to ),
|
||||
$field
|
||||
);
|
||||
}
|
||||
|
||||
// Reset filter for `Dispatcher::update` so our integration works for later operations.
|
||||
add_filter( 'acf/update_value', array( Dispatcher::class, 'update' ), 5, 3 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports custom fields.
|
||||
*
|
||||
* @param PLL_Export_Data $export The export object.
|
||||
* @param object|null $to The translated object if it exists, `null` otherwise.
|
||||
* @return void
|
||||
* @since 3.7
|
||||
*/
|
||||
public function export( PLL_Export_Data $export, ?object $to ) {
|
||||
$this->apply_to_all_fields(
|
||||
new Export( $export ),
|
||||
empty( $to ) ? 0 : $this->get_object_id( $to ),
|
||||
array(
|
||||
'target_language' => $export->get_target_language(),
|
||||
'source_language' => $export->get_source_language(),
|
||||
'update' => false,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the custom fields from the current object.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param object $to The target object.
|
||||
* @param PLL_Language $target_lang Target language object.
|
||||
* @param Translations $translations A set of translations to search the custom fields translations in.
|
||||
* @return object The translated object.
|
||||
*/
|
||||
public function translate( object $to, PLL_Language $target_lang, Translations $translations ): object {
|
||||
$this->apply_to_all_fields(
|
||||
new Import( $translations ),
|
||||
$this->get_object_id( $to ),
|
||||
array(
|
||||
'target_language' => $target_lang,
|
||||
'source_language' => PLL()->model->{$this->get_type()}->get_language( $this->get_id() ),
|
||||
)
|
||||
);
|
||||
|
||||
return $to;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes ACF metas from metas to be synchronized by Polylang.
|
||||
* To use only the ACF integration synchronization mechanism.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param string[] $metas List of custom fields names.
|
||||
* @param bool $sync True if it is synchronization, false if it is a copy.
|
||||
* @param int|string $from ID of the object from which we copy information.
|
||||
* @param int|string $to ID of the object to which we copy information.
|
||||
* @return string[]
|
||||
*/
|
||||
public static function remove_acf_metas_from_pll_sync( $metas, $sync, $from, $to ) {
|
||||
if ( ! is_array( $metas ) ) {
|
||||
return $metas;
|
||||
}
|
||||
|
||||
$from = static::acf_id( (int) $from );
|
||||
$to = static::acf_id( (int) $to );
|
||||
|
||||
$acf_metas = array_merge( (array) acf_get_meta( $from ), (array) acf_get_meta( $to ) );
|
||||
$acf_metas = array_keys( $acf_metas );
|
||||
|
||||
return array_diff( $metas, $acf_metas );
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax response for changing the language of an object in its interface.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Language $language The language slug fetched from the AJAX request.
|
||||
* @param string $fields Fields fetched from the AJAX request.
|
||||
* @return array The AJAX response with the new language slug and fields.
|
||||
*/
|
||||
public function on_lang_choice( PLL_Language $language, string $fields ): array {
|
||||
$response = array(
|
||||
'lang' => $language->slug,
|
||||
);
|
||||
|
||||
$fields = explode( ',', $fields );
|
||||
foreach ( $fields as $field ) {
|
||||
$field_array = acf_get_field( $field );
|
||||
|
||||
if ( false === $field_array ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$from_value = acf_get_value( static::acf_id( $this->get_id() ), $field_array );
|
||||
$field_array['value'] = ( new Copy() )->execute(
|
||||
$this,
|
||||
$from_value,
|
||||
$field_array,
|
||||
array(
|
||||
'target_language' => $language,
|
||||
'original_value' => $from_value,
|
||||
)
|
||||
);
|
||||
acf_update_value( $field_array['value'], static::acf_id( $this->get_id() ), $field_array );
|
||||
|
||||
$field_wrap = $this->render_field( $field_array );
|
||||
|
||||
$response['fields'][] = array(
|
||||
'field_key' => str_replace( '_', '-', $field ),
|
||||
'field_data' => $field_wrap,
|
||||
);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the language of the current object to the arguments that will be used for the query
|
||||
* in the `relationship` and `post_object` ACF fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $args Arguments to retrieve posts.
|
||||
* @return array The arguments to retrieve posts with the current object language.
|
||||
*/
|
||||
public function add_language_to_query( $args ) {
|
||||
if ( isset( $args['lang'] ) ) {
|
||||
return $args;
|
||||
}
|
||||
|
||||
$language = PLL()->model->{$this->get_type()}->get_language( $this->get_id() );
|
||||
if ( empty( $language ) ) {
|
||||
return $args;
|
||||
}
|
||||
|
||||
$args['lang'] = $language->slug;
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues Javascript to refresh fields on language change in translatable entities metabox.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected static function enqueue_scripts() {
|
||||
$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
|
||||
|
||||
wp_enqueue_script( 'pll_acf_post', plugins_url( '/js/build/integrations/acf' . $suffix . '.js', POLYLANG_ROOT_FILE ), array( 'wp-api-fetch', 'acf-input', 'wp-sanitize' ), POLYLANG_VERSION, true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns current object ID.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_id(): int {
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the ACF field key to store.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $id Object ID.
|
||||
* @param string $key The custom field key.
|
||||
* @return string
|
||||
*/
|
||||
protected function get_storage_key( $id, $key ) {
|
||||
return static::acf_id( $id ) . '|' . $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the object ID.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param object $object The object.
|
||||
* @return int
|
||||
*/
|
||||
abstract protected function get_object_id( $object ): int;
|
||||
|
||||
/**
|
||||
* Transforms an object ID to the corresponding ACF post ID.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $id Object ID.
|
||||
* @return int|string ACF post ID.
|
||||
*/
|
||||
abstract protected static function acf_id( $id );
|
||||
|
||||
/**
|
||||
* Returns source object ID passed in the main request if exists.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
abstract protected function get_from_id_in_request(): int;
|
||||
|
||||
/**
|
||||
* Returns current object type.
|
||||
*
|
||||
* The returned value must match:
|
||||
* - the name of the property storing the corresponding model (`PLL()->model->{type}`).
|
||||
* - the `object_type` from `PLL_Export_Data::add_translation_entry()`.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
abstract public function get_type(): string;
|
||||
|
||||
/**
|
||||
* Renders the field with its wrapping element type and instruction render position (label|field).
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field The field to render.
|
||||
* @return string HTML rendered string of the field.
|
||||
*/
|
||||
abstract protected function render_field( array $field ): string;
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Entity;
|
||||
|
||||
use WP_Post;
|
||||
use Translations;
|
||||
use PLL_Language;
|
||||
use PLL_Export_Data;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Copy;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Import;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Export;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Abstract_Strategy;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Synchronizes IDs and translates strings in ACF blocks.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Blocks implements Translatable_Entity_Interface {
|
||||
|
||||
/**
|
||||
* ID of the post that contains blocks.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $id The post ID, defaults to 0.
|
||||
*/
|
||||
public function __construct( int $id = 0 ) {
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the field values in blocks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $blocks The blocks.
|
||||
* @param PLL_Language $target_lang The target language.
|
||||
* @param WP_Post $source_post The source post.
|
||||
* @return array The blocks.
|
||||
*/
|
||||
public function copy( array $blocks, PLL_Language $target_lang, WP_Post $source_post ) {
|
||||
return $this->apply_on_blocks(
|
||||
new Copy(),
|
||||
$blocks,
|
||||
$source_post->ID,
|
||||
$target_lang
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates fields in blocks during import.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Post $to The translated post.
|
||||
* @param PLL_Language $target_lang The target language.
|
||||
* @param Translations $translations A set of translations to search the custom fields translations in.
|
||||
* @return WP_Post The translated post.
|
||||
*/
|
||||
public function translate( WP_Post $to, PLL_Language $target_lang, Translations $translations ): WP_Post {
|
||||
$post = get_post( $this->id );
|
||||
|
||||
if ( empty( $post ) || ! has_blocks( $post ) ) {
|
||||
return $to;
|
||||
}
|
||||
|
||||
$new_post_content = serialize_blocks(
|
||||
$this->apply_on_blocks(
|
||||
new Import( $translations ),
|
||||
parse_blocks( $to->post_content ),
|
||||
$post->ID,
|
||||
$target_lang
|
||||
)
|
||||
);
|
||||
|
||||
$to->post_content = $new_post_content;
|
||||
|
||||
return $to;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds ACF fields to the exported data.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Export_Data $export The export data.
|
||||
* @return void
|
||||
*/
|
||||
public function export( PLL_Export_Data $export ) {
|
||||
$post = get_post( $this->id );
|
||||
|
||||
if ( empty( $post ) || ! has_blocks( $post ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->apply_on_blocks(
|
||||
new Export( $export ),
|
||||
parse_blocks( $post->post_content ),
|
||||
$post->ID,
|
||||
$export->get_target_language()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a strategy on blocks from the current post to a target post.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Strategy $strategy Strategy to execute.
|
||||
* @param int $to ID of the target post. Not used.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type PLL_Language|null $target_language The language used to apply the strategy.
|
||||
* }
|
||||
* @return void
|
||||
*/
|
||||
public function apply_to_all_fields( Abstract_Strategy $strategy, int $to = 0, array $args = array() ) {
|
||||
$post = get_post( $this->id );
|
||||
|
||||
if ( empty( $post ) || ! has_blocks( $post ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->apply_on_blocks(
|
||||
$strategy,
|
||||
parse_blocks( $post->post_content ),
|
||||
$post->ID,
|
||||
$args['target_language'] ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply given strategy to field values in blocks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Strategy $strategy The strategy.
|
||||
* @param array $blocks List of blocks.
|
||||
* @param int $id The post ID.
|
||||
* @param PLL_Language|null $language The language used to apply the strategy:
|
||||
* the target language when applying a translate strategy,
|
||||
* unused i.e. null when collecting linked content.
|
||||
* @return array The blocks.
|
||||
*/
|
||||
private function apply_on_blocks( Abstract_Strategy $strategy, array $blocks, int $id, ?PLL_Language $language = null ): array {
|
||||
foreach ( $blocks as &$block ) {
|
||||
if ( ! isset( $block['blockName'], $block['attrs'] ) ) {
|
||||
// No can do.
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( empty( acf_get_block_type( $block['blockName'] ) ) ) {
|
||||
if ( ! empty( $block['innerBlocks'] ) ) {
|
||||
$block['innerBlocks'] = $this->apply_on_blocks( $strategy, $block['innerBlocks'], $id, $language );
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
/*
|
||||
* Ensure the block has the required keys for `acf_prepare_block()`.
|
||||
*/
|
||||
$block['name'] = $block['blockName'];
|
||||
if ( empty( $block['id'] ) ) {
|
||||
$block['id'] = acf_ensure_block_id_prefix( acf_get_block_id( $block['attrs'] ) );
|
||||
}
|
||||
|
||||
$block = acf_prepare_block( $block );
|
||||
|
||||
if ( ! isset( $block['data'] ) ) {
|
||||
// No can do.
|
||||
continue;
|
||||
}
|
||||
|
||||
// Backward compatibility with ACF < 6.3.
|
||||
if ( function_exists( 'acf_add_block_meta_values' ) && function_exists( 'acf_block_uses_post_meta' ) && acf_block_uses_post_meta( $block ) ) {
|
||||
$block = acf_add_block_meta_values( $block, $id );
|
||||
$block['attrs']['data'] = $block['data'];
|
||||
}
|
||||
|
||||
if ( ! isset( $block['attrs']['data'] ) ) {
|
||||
// No can do.
|
||||
continue;
|
||||
}
|
||||
|
||||
/*
|
||||
* Loads block fields values like ACF does.
|
||||
* @see {acf_render_block()}.
|
||||
*/
|
||||
acf_setup_meta( $block['attrs']['data'], $block['id'], true );
|
||||
|
||||
$values = array();
|
||||
foreach ( acf_get_block_fields( $block['attrs'] ) as $field ) {
|
||||
$value = acf_get_value( $block['id'], $field );
|
||||
$values[ $field['key'] ] = $strategy->execute(
|
||||
new Post( $id ),
|
||||
$value,
|
||||
$field,
|
||||
array(
|
||||
'target_language' => $language,
|
||||
'original_value' => $field['default_value'] ?? null,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! empty( $values ) ) {
|
||||
/*
|
||||
* Converts "data" to "meta" and ensures the block attributes are all set.
|
||||
* `acf_setup_meta()` cannot be used directly because it relies on form data, which is not the case here.
|
||||
* @see {acf_parse_save_blocks_callback()}.
|
||||
*/
|
||||
$block['attrs']['data'] = acf_get_instance( 'ACF_Local_Meta' )
|
||||
->capture(
|
||||
$values,
|
||||
$block['id']
|
||||
);
|
||||
|
||||
// Backward compatibility with ACF < 6.3.
|
||||
if ( function_exists( 'acf_block_uses_post_meta' ) && acf_block_uses_post_meta( $block ) ) {
|
||||
$block = $this->prepare_block_post_meta( $block );
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Reset block data for safety, so we don't change its data tree by mistake.
|
||||
* @see {acf_render_block()}.
|
||||
*/
|
||||
acf_reset_meta( $block['id'] );
|
||||
|
||||
if ( ! empty( $block['innerBlocks'] ) ) {
|
||||
$block['innerBlocks'] = $this->apply_on_blocks( $strategy, $block['innerBlocks'], $id, $language );
|
||||
}
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts block data using meta keys to block data using field keys.
|
||||
* ACF requires a specific format for it to be saved in post meta.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $block The block to convert.
|
||||
* @return array The converted block.
|
||||
*/
|
||||
private function prepare_block_post_meta( array $block ): array {
|
||||
$new_data = array();
|
||||
foreach ( $block['attrs']['data'] as $key => $value ) {
|
||||
if ( ! str_starts_with( $key, '_' ) || empty( $value ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// We got a field key in `$value`.
|
||||
$field = acf_get_field( $value );
|
||||
if ( empty( $field ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$new_data[ $field['key'] ] = acf_get_value( $block['id'], $field );
|
||||
}
|
||||
|
||||
$block['attrs']['data'] = $new_data;
|
||||
|
||||
return $block;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Entity;
|
||||
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Copy;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Handles attachment post type.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Media extends Post {
|
||||
/**
|
||||
* Copies media fields when a new translation is created.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $to_id Target media ID.
|
||||
* @param PLL_Language $target_language The language to translate into.
|
||||
* @return void
|
||||
*/
|
||||
public function copy_fields( $to_id, $target_language ) {
|
||||
$target_language = PLL()->model->get_language( $target_language );
|
||||
if ( empty( $target_language ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->maybe_reset_fields_store( $target_language );
|
||||
|
||||
$this->apply_to_all_fields( new Copy(), $to_id, array( 'target_language' => $target_language ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a post ID to the corresponding ACF post ID.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $id Post ID.
|
||||
* @return string ACF post ID.
|
||||
*/
|
||||
protected static function acf_id( $id ): string {
|
||||
return 'attachment_' . $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does nothing for media. `self::translate_fields()` does the job instead.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return array Custom field of the target object.
|
||||
*/
|
||||
public function translate_rendered_field( $field ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
|
||||
|
||||
/*
|
||||
* Does nothing, media translations are created in two times.
|
||||
* 1. A request is made to create the media translation.
|
||||
* 2. A redirect is made toward the edit page of the media, where ACF loads the fields.
|
||||
*/
|
||||
return $field;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Entity;
|
||||
|
||||
use WP_Post;
|
||||
use PLL_Admin_Links;
|
||||
use PLL_Sync_Post_Model;
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Copy;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Copy_All;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Handles posts.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Post extends Abstract_Object {
|
||||
|
||||
/**
|
||||
* The previous language slug of the target post.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $previous_lang = '';
|
||||
|
||||
/**
|
||||
* Returns the object ID.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Post $object The object.
|
||||
* @return int
|
||||
*/
|
||||
protected function get_object_id( $object ): int {
|
||||
return $object->ID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a post ID to the corresponding ACF post ID.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $id Post ID.
|
||||
* @return int ACF post ID.
|
||||
*/
|
||||
protected static function acf_id( $id ) {
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns source object ID passed in the main request if exists.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function get_from_id_in_request(): int {
|
||||
if ( ! PLL()->links instanceof PLL_Admin_Links ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$data = PLL()->links->get_data_from_new_post_translation_request();
|
||||
|
||||
return ! empty( $data['from_post'] ) ? $data['from_post']->ID : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns current object type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
public function get_type(): string {
|
||||
return 'post';
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the field with its wrapping element type and instruction render position (label|field).
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field The field to render.
|
||||
* @return string HTML rendered string of the field.
|
||||
*/
|
||||
protected function render_field( array $field ): string {
|
||||
ob_start();
|
||||
acf_render_fields( array( $field ), static::acf_id( $this->get_id() ), 'div', 'label' );
|
||||
return (string) ob_get_clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies or synchronizes ACF custom fields when using Polylang's copy post function (and not the post-new.php where ACF filters are applied).
|
||||
* (e.g. using bulk translate, creating a synchronized post).
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $tr_post_id ID of the target post.
|
||||
* @param string $lang Language of the target post.
|
||||
* @param string $sync `sync` if doing synchro, `copy` otherwise.
|
||||
* @return void
|
||||
*
|
||||
* @phpstan-param 'sync'|'copy' $sync
|
||||
*/
|
||||
public function on_post_synchronized( $tr_post_id, $lang, $sync ) {
|
||||
$lang = PLL()->model->get_language( $lang );
|
||||
if ( empty( $lang ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->maybe_reset_fields_store( $lang );
|
||||
|
||||
if ( PLL_Sync_Post_Model::COPY === $sync ) {
|
||||
$this->apply_to_all_fields( new Copy(), $tr_post_id, array( 'target_language' => $lang ) );
|
||||
return;
|
||||
}
|
||||
|
||||
// Sync all custom fields between synchronized posts.
|
||||
$post_id = $this->get_id();
|
||||
foreach ( pll_get_post_translations( $post_id ) as $tr_lang => $tr_id ) {
|
||||
if ( $tr_id === $post_id || ! PLL()->sync_post_model->are_synchronized( $post_id, $tr_id ) ) {
|
||||
continue;
|
||||
}
|
||||
/** @var PLL_Language */
|
||||
$tr_lang = PLL()->model->get_language( $tr_lang );
|
||||
|
||||
$this->apply_to_all_fields( new Copy_All(), $tr_id, array( 'target_language' => $tr_lang ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the `fields` store to translate the default values in the correct language.
|
||||
* Only if the current target language has been changed.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Language $lang Language of the target post.
|
||||
* @return void
|
||||
*/
|
||||
protected function maybe_reset_fields_store( PLL_Language $lang ) {
|
||||
if ( self::$previous_lang !== $lang->slug ) {
|
||||
$store = acf_get_store( 'fields' );
|
||||
$store->reset();
|
||||
self::$previous_lang = $lang->slug;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax response for changing the language in the post metabox.
|
||||
*
|
||||
* @since 2.0
|
||||
* @since 3.8 Renamed from `acf_post_lang_choice` and Moved from `Ajax_Lang_Choice` to `Post`.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function on_ajax_post_lang_choice(): void {
|
||||
check_ajax_referer( 'pll_language', '_pll_nonce' );
|
||||
|
||||
if ( ! isset( $_POST['fields'], $_POST['lang'], $_POST['post_id'] ) ) {
|
||||
wp_die( 0 );
|
||||
}
|
||||
|
||||
$post_id = (int) $_POST['post_id'];
|
||||
$post_type = get_post_type( $post_id );
|
||||
|
||||
if ( ! $post_type || ! PLL()->model->is_translated_post_type( $post_type ) ) {
|
||||
wp_die( 0 );
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'edit_post', $post_id ) ) {
|
||||
wp_die( -1 );
|
||||
}
|
||||
|
||||
$language = PLL()->model->languages->get( sanitize_key( $_POST['lang'] ) );
|
||||
if ( ! $language instanceof PLL_Language ) {
|
||||
wp_die( 0 );
|
||||
}
|
||||
|
||||
$response = ( new self( $post_id ) )->on_lang_choice(
|
||||
$language,
|
||||
sanitize_text_field( wp_unslash( $_POST['fields'] ) )
|
||||
);
|
||||
|
||||
wp_send_json( $response );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues Javascript to refresh fields on language change for post creation and editing pages.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function admin_enqueue_scripts() {
|
||||
global $pagenow, $typenow;
|
||||
|
||||
if ( in_array( $pagenow, array( 'post.php', 'post-new.php' ), true ) &&
|
||||
PLL()->model->is_translated_post_type( $typenow ) ) {
|
||||
self::enqueue_scripts();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Entity;
|
||||
|
||||
use PLL_Language;
|
||||
use WP_Term;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Handles terms.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Term extends Abstract_Object {
|
||||
/**
|
||||
* Returns the object ID.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Term $object The object.
|
||||
* @return int
|
||||
*/
|
||||
protected function get_object_id( $object ): int {
|
||||
return $object->term_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a term ID to the corresponding ACF post ID.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $id Term ID.
|
||||
* @return string ACF post ID.
|
||||
*/
|
||||
protected static function acf_id( $id ) {
|
||||
return 'term_' . $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns source object ID passed in the main request if exists.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function get_from_id_in_request(): int {
|
||||
if ( isset( $_GET['taxonomy'], $_GET['from_tag'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return (int) $_GET['from_tag']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns current object type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
public function get_type(): string {
|
||||
return 'term';
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the field with its wrapping element type and instruction render position (label|field).
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field The field to render.
|
||||
* @return string HTML rendered string of the field.
|
||||
*/
|
||||
protected function render_field( array $field ): string {
|
||||
/**
|
||||
* The wrapping element is not the same on term creation page as on term edition page.
|
||||
* If there's a term ID, we're on an editing page, otherwise we're on a creation page.
|
||||
*/
|
||||
$element = $this->get_id() > 0 ? 'tr' : 'div';
|
||||
|
||||
ob_start();
|
||||
acf_render_fields( array( $field ), static::acf_id( $this->get_id() ), $element, 'field' );
|
||||
return (string) ob_get_clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax response for changing the language in the term edit or creation page.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function on_ajax_term_lang_choice(): void {
|
||||
check_ajax_referer( 'pll_language', '_pll_nonce' );
|
||||
|
||||
if ( ! isset( $_POST['fields'], $_POST['lang'], $_POST['term_id'], $_POST['taxonomy'] ) ) {
|
||||
wp_die( 0 );
|
||||
}
|
||||
|
||||
$tax = get_taxonomy( sanitize_key( $_POST['taxonomy'] ) );
|
||||
if ( ! $tax || ! PLL()->model->is_translated_taxonomy( $tax->name ) ) {
|
||||
wp_die( 0 );
|
||||
}
|
||||
|
||||
$term_id = (int) $_POST['term_id'];
|
||||
if ( ( $term_id > 0 && ! current_user_can( 'edit_term', $term_id ) )
|
||||
|| ! current_user_can( $tax->cap->manage_terms ) ) {
|
||||
wp_die( -1 );
|
||||
}
|
||||
|
||||
$language = PLL()->model->languages->get( sanitize_key( $_POST['lang'] ) );
|
||||
if ( ! $language instanceof PLL_Language ) {
|
||||
wp_die( 0 );
|
||||
}
|
||||
|
||||
$response = ( new self( $term_id ) )->on_lang_choice(
|
||||
$language,
|
||||
sanitize_text_field( wp_unslash( $_POST['fields'] ) )
|
||||
);
|
||||
|
||||
wp_send_json( $response );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues Javascript to refresh fields on language change for term creation and editing pages.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function admin_enqueue_scripts() {
|
||||
global $pagenow, $taxnow;
|
||||
|
||||
if ( ! in_array( $pagenow, array( 'edit-tags.php', 'term.php' ), true ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! PLL()->model->is_translated_taxonomy( $taxnow ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::enqueue_scripts();
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Entity;
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Abstract_Strategy;
|
||||
|
||||
/**
|
||||
* Interface for applying a strategy to all fields of the current object.
|
||||
*/
|
||||
interface Translatable_Entity_Interface {
|
||||
/**
|
||||
* Applies a strategy to all fields of the current object.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Strategy $strategy Strategy to execute.
|
||||
* @param int $to ID of the target object.
|
||||
* @param array $args Array of arguments.
|
||||
* @return void
|
||||
*/
|
||||
public function apply_to_all_fields( Abstract_Strategy $strategy, int $to = 0, array $args = array() );
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF;
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Location_Language;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Adds a field setting to decide if the field must be copied, translated or synchronized.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Field_Settings {
|
||||
|
||||
/**
|
||||
* Setups actions.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_acf_init() {
|
||||
// Adds the field setting, except for fields of type layout.
|
||||
foreach ( acf_get_field_types() as $type ) { // Since ACF 5.6.0.
|
||||
if ( 'layout' !== $type->category ) {
|
||||
add_action( "acf/render_field_settings/type={$type->name}", array( $this, 'render_field_settings' ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given fields group was created with Polylang Pro < 3.7 and had been translated.
|
||||
*
|
||||
* @since 3.7.3
|
||||
*
|
||||
* @param int $id The fields group ID to check.
|
||||
* @return bool True if the fields group is from Polylang Pro < 3.7 and had been translated, false otherwise.
|
||||
*/
|
||||
public static function is_legacy_translated_field_group( int $id ) {
|
||||
return ! empty(
|
||||
get_terms(
|
||||
array(
|
||||
'taxonomy' => 'language',
|
||||
'fields' => 'ids',
|
||||
'object_ids' => $id,
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders translations setting and its default value according to the field type.
|
||||
*
|
||||
* @since 2.7
|
||||
* @since 3.3.1 Renamed and merged two methods.
|
||||
* @since 3.7 Added `translate_once` option.
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return void
|
||||
*/
|
||||
public function render_field_settings( $field ) {
|
||||
$field_group = Location_Language::get_field_group_from_field( $field );
|
||||
if ( ! empty( $field_group ) && Location_Language::has_language_location_rule( $field_group ) && ! $this::is_legacy_translated_field_group( (int) $field_group['ID'] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$choices = array(
|
||||
'ignore' => __( 'Ignore', 'polylang-pro' ),
|
||||
'copy_once' => __( 'Copy once', 'polylang-pro' ),
|
||||
'sync' => __( 'Synchronize', 'polylang-pro' ),
|
||||
);
|
||||
$default = in_array( 'post_meta', PLL()->options['sync'], true ) ? 'sync' : 'copy_once';
|
||||
|
||||
switch ( $field['type'] ) {
|
||||
case 'text':
|
||||
case 'textarea':
|
||||
case 'wysiwyg':
|
||||
if ( empty( $field['ID'] ) ) { // Workaround a bug in ACF which doesn't save options added after a field has been created.
|
||||
$default = 'translate';
|
||||
}
|
||||
// Intentional fall-through to add the translate options below.
|
||||
|
||||
case 'email':
|
||||
case 'oembed':
|
||||
case 'url':
|
||||
// Add translate and translate_once option from the 3rd position.
|
||||
$choices = array_merge(
|
||||
array_slice( $choices, 0, 2 ),
|
||||
array(
|
||||
'translate' => __( 'Translate', 'polylang-pro' ),
|
||||
'translate_once' => __( 'Translate once', 'polylang-pro' ),
|
||||
),
|
||||
array_slice( $choices, -1 )
|
||||
);
|
||||
break;
|
||||
}
|
||||
$this->render_field_setting( $field, $choices, $default );
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the translations setting.
|
||||
*
|
||||
* @since 2.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $choices An array of choices for the select (value as key and label as value).
|
||||
* @param string $default Default value for the select.
|
||||
* @return void
|
||||
*/
|
||||
protected function render_field_setting( $field, $choices, $default ) {
|
||||
acf_render_field_setting( // Since ACF 5.7.10.
|
||||
$field,
|
||||
array(
|
||||
'label' => __( 'Translations', 'polylang-pro' ),
|
||||
'instructions' => '',
|
||||
'name' => 'translations',
|
||||
'type' => 'select',
|
||||
'choices' => $choices,
|
||||
'default_value' => $default,
|
||||
),
|
||||
false // The setting is depending on the type of field.
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Fields;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Class that allows to copy the values of repeater fields (mostly useful if the repeater is with paginated).
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Repeater {
|
||||
/**
|
||||
* Changes some HTML attributes of a repeater sub-field to make it look like a newly added field. This is required
|
||||
* when the repeater's pagination is enabled, otherwise the sub-fields won't be saved.
|
||||
* The `name` attribute of a saved sub-field value looks like `acf[field_682455496dc8e][row-0][field_6824563045bb9]`.
|
||||
* The `name` attribute of a new sub-field value looks like `acf[field_682455496dc8e][682704342a536][field_6824563045bb9]`.
|
||||
* If a sub-field doesn't contain `row`, ACF will discard it because it isn't actually in the database.
|
||||
*
|
||||
* @since 3.8
|
||||
* @see acf_field_repeater::update_value()
|
||||
* ACF_Repeater_Table::row()
|
||||
*
|
||||
* @param array $field Custom field definition. Only sub-fields of paginated repeaters are handled.
|
||||
* @return array
|
||||
*/
|
||||
public static function change_row_keys( $field ) {
|
||||
if ( empty( $field['parent_repeater'] ) || false === strpos( $field['name'], '[row-' ) ) {
|
||||
return $field;
|
||||
}
|
||||
|
||||
$parent_field = acf_get_field( $field['parent_repeater'] );
|
||||
|
||||
if ( empty( $parent_field ) || ! self::is_paginated( $parent_field ) ) {
|
||||
return $field;
|
||||
}
|
||||
|
||||
/*
|
||||
* Instead of a random hash like ACF does for new rows, provide a key that contains the original row number, but
|
||||
* not `row`. This key will be reverted in `reset_row_keys()`.
|
||||
*/
|
||||
$field['name'] = preg_replace( '/\[row-(\d+)\]/', '[pll-$1]', $field['name'] );
|
||||
$field['prefix'] = preg_replace( '/\[row-(\d+)\]/', '[pll-$1]', $field['prefix'] );
|
||||
$field['id'] = preg_replace( '/-row-(\d+)-/', '-pll-$1-', $field['id'] );
|
||||
|
||||
return $field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the array keys that look like `pll-0`: they correspond to sub-fields of a repeater with pagination.
|
||||
* They are used when creating a post translation. Those custom keys are changed back to their original value
|
||||
* to prevent creating new rows in the original post (reverse sync).
|
||||
* See `self::change_row_keys()`.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param mixed $value A field value.
|
||||
* @param array $field Custom field definition. Only sub-fields of paginated repeaters are handled.
|
||||
* @return mixed
|
||||
*/
|
||||
public static function reset_row_keys( $value, array $field ) {
|
||||
if ( ! is_array( $value ) || empty( $value ) || ! self::is_paginated( $field ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$new_value = array();
|
||||
|
||||
foreach ( $value as $k => $v ) {
|
||||
if ( is_string( $k ) && preg_match( '/^pll-(?<i>\d+)$/', $k, $matches ) ) {
|
||||
$k = "row-{$matches['i']}";
|
||||
}
|
||||
|
||||
if ( is_array( $v ) ) {
|
||||
if ( isset( $new_value[ $k ] ) && is_array( $new_value[ $k ] ) ) {
|
||||
// In case `$value` has `row-0` and `pll-0` at the same time (it happened, don't ask how).
|
||||
$v = array_merge( $new_value[ $k ], $v );
|
||||
}
|
||||
}
|
||||
|
||||
$new_value[ $k ] = $v;
|
||||
}
|
||||
|
||||
return $new_value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given field is a paginated repeater.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_paginated( array $field ): bool {
|
||||
return 'repeater' === $field['type'] && ! empty( $field['pagination'] ) && ! empty( $field['sub_fields'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the field value.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param int|string $acf_id ACF post ID.
|
||||
* @param array $field Custom field definition.
|
||||
* @return mixed
|
||||
*/
|
||||
public static function get_value( $acf_id, array $field ) {
|
||||
if ( ! self::is_paginated( $field ) ) {
|
||||
return acf_get_value( $acf_id, $field );
|
||||
}
|
||||
|
||||
$repeater = acf_get_field_type( 'repeater' );
|
||||
|
||||
if ( ! $repeater ) {
|
||||
// The active plugin is ACF while a repeater was previously created with ACF Pro
|
||||
return acf_get_value( $acf_id, $field );
|
||||
}
|
||||
|
||||
// Disable pagination to get all values.
|
||||
$is_rendering = $repeater->is_rendering;
|
||||
$repeater->is_rendering = false;
|
||||
|
||||
$value = acf_get_value( $acf_id, $field );
|
||||
|
||||
$repeater->is_rendering = $is_rendering;
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Labels;
|
||||
|
||||
use stdClass;
|
||||
use ACF_Internal_Post_Type;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Registers and translates the labels of custom post types or taxonomies created within ACF's UI.
|
||||
* Translation is supposed to happen only on frontend (for the archive page title for example).
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
abstract class Abstract_Object_Type {
|
||||
/**
|
||||
* Setups actions and filters.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_acf_init(): void {
|
||||
if ( ! defined( 'ACF_VERSION' ) || version_compare( ACF_VERSION, '6.1.0', '<' ) ) {
|
||||
// Backward compatibility with ACF < 6.1.
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! acf_get_setting( 'enable_post_types' ) ) {
|
||||
// The feature is deactivated.
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* After `ACF::init()` (prio 5).
|
||||
* Otherwise the classes `ACF_Post_Type` and `ACF_Taxonomy` won't exist (their file is included there).
|
||||
*/
|
||||
$this->register_strings();
|
||||
|
||||
if ( did_action( 'pll_language_defined' ) ) {
|
||||
$this->translate_registered_strings();
|
||||
} else {
|
||||
// Special case when the language is set from the content as CPT and taxonomies are registered before the language is defined.
|
||||
add_action( 'pll_language_defined', array( $this, 'translate_registered_strings' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers strings for custom post types or taxonomies labels.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_strings(): void {
|
||||
foreach ( $this->get_acf_type_instance()->get_posts( array( 'active' => true ) ) as $acf_object ) {
|
||||
$label_start = sprintf( 'ACF %s, %s,', $this->get_type_label(), $acf_object[ $this->get_type() ] );
|
||||
|
||||
pll_register_string( "{$label_start} title", $acf_object['title'], 'ACF' );
|
||||
pll_register_string( "{$label_start} description", $acf_object['description'], 'ACF', true );
|
||||
|
||||
foreach ( $acf_object['labels'] as $key => $label ) {
|
||||
pll_register_string( "{$label_start} {$key}", $label, 'ACF' );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates custom post type and taxonomy labels when the language is ready.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function translate_registered_strings(): void {
|
||||
$acf_objects = $this->get_acf_type_instance()->get_posts( array( 'active' => true ) );
|
||||
$acf_objects = array_column( $acf_objects, $this->get_type(), $this->get_type() );
|
||||
$acf_objects = array_intersect_key( $this->get_type_objects(), $acf_objects );
|
||||
|
||||
foreach ( $acf_objects as $type ) {
|
||||
$type->label = pll__( $type->label );
|
||||
$type->description = pll__( $type->description );
|
||||
|
||||
foreach ( array_keys( get_object_vars( $type->labels ) ) as $key ) {
|
||||
$type->labels->$key = pll__( $type->labels->$key );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
abstract protected function get_type(): string;
|
||||
|
||||
/**
|
||||
* Returns the instance of the related "ACF type".
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return ACF_Internal_Post_Type
|
||||
*/
|
||||
abstract protected function get_acf_type_instance(): ACF_Internal_Post_Type;
|
||||
|
||||
/**
|
||||
* Returns the list of type objects containing labels.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return object[]
|
||||
*
|
||||
* @phpstan-return array<
|
||||
* non-falsy-string,
|
||||
* object{label: string, description: string, labels: object}&stdClass
|
||||
* >
|
||||
*/
|
||||
abstract protected function get_type_objects(): array;
|
||||
|
||||
/**
|
||||
* Returns the label of the type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-empty-string
|
||||
*/
|
||||
abstract protected function get_type_label(): string;
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Labels;
|
||||
|
||||
use PLL_Import_Action;
|
||||
use PLL_Admin_Base;
|
||||
use PLL_Settings;
|
||||
use PLL_Format_Util;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Registers and translates ACF's fields labels.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @phpstan-type ToRegister array{
|
||||
* name: string,
|
||||
* string: string,
|
||||
* multiline?: bool
|
||||
* }
|
||||
* @phpstan-type LabelsMap array<
|
||||
* non-empty-string,
|
||||
* string|array<non-empty-string, string|array<non-empty-string, string>>
|
||||
* >
|
||||
* @phpstan-type LabelsByType array<non-empty-string, LabelsMap>
|
||||
*/
|
||||
class Field_Groups {
|
||||
public const CACHE_KEY = 'pll_acf_field_labels';
|
||||
|
||||
/**
|
||||
* @var array|null
|
||||
*
|
||||
* @phpstan-var LabelsByType|null
|
||||
*/
|
||||
private $labels;
|
||||
|
||||
/**
|
||||
* Setups actions and filters.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_acf_init(): void {
|
||||
add_action( 'acf/updated_field', array( self::class, 'clear_cache' ) );
|
||||
add_action( 'acf/delete_field', array( self::class, 'clear_cache' ) );
|
||||
add_action( 'acf/update_field_group', array( self::class, 'clear_cache' ) );
|
||||
add_action( 'acf/delete_field_group', array( self::class, 'clear_cache' ) );
|
||||
|
||||
if ( PLL() instanceof PLL_Admin_Base ) {
|
||||
// `pll_register_string()` does nothing outside `PLL_Admin_Base`. No need to loop the fields then.
|
||||
$this->register_field_groups();
|
||||
}
|
||||
|
||||
if ( ! $this->can_translate_labels() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( PLL() instanceof PLL_Admin_Base ) {
|
||||
// Clear the fields cache (filled by `$this->register_field_groups()`) to be able to translate the field labels via the filters.
|
||||
acf_get_store( 'fields' )->reset();
|
||||
}
|
||||
|
||||
add_filter( 'acf/load_field', array( $this, 'translate_field_labels' ), 20 ); // After `child_of_acf_field::load_field()` (prio 10).
|
||||
add_filter( 'acf/load_field_groups', array( $this, 'translate_field_groups_labels' ), 25 ); // After `_acf_apply_get_local_internal_posts()` (prio 20).
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears label translations cache.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function clear_cache(): void {
|
||||
delete_transient( self::CACHE_KEY );
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the labels of all field groups.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_field_groups() {
|
||||
$to_register = get_transient( self::CACHE_KEY );
|
||||
|
||||
if ( ! is_array( $to_register ) ) {
|
||||
$to_register = array();
|
||||
acf_disable_filter( 'clone' ); // To allow seamless clone fields to appear in acf_get_fields().
|
||||
|
||||
foreach ( acf_get_field_groups() as $field_group ) {
|
||||
$to_register[] = array(
|
||||
'name' => 'Title',
|
||||
'string' => $field_group['title'],
|
||||
);
|
||||
$to_register = $this->register_fields( $to_register, acf_get_fields( $field_group ) );
|
||||
}
|
||||
|
||||
acf_enable_filter( 'clone' );
|
||||
set_transient( self::CACHE_KEY, $to_register );
|
||||
}
|
||||
|
||||
foreach ( $to_register as $register_string ) {
|
||||
pll_register_string( $register_string['name'], $register_string['string'], 'ACF', $register_string['multiline'] ?? false );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively translates labels that are not originally translated by ACF for the given field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field The field array.
|
||||
* @return array
|
||||
*/
|
||||
public function translate_field_labels( $field ) {
|
||||
if ( ! is_array( $field ) || ! isset( $field['type'] ) ) {
|
||||
return $field;
|
||||
}
|
||||
|
||||
$matcher = new PLL_Format_Util();
|
||||
|
||||
foreach ( $this->get_field_labels_to_translate() as $field_type => $field_labels ) {
|
||||
if ( ! $matcher->matches( $field['type'], $field_type ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$field = $this->translate_field_labels_recursive( $field_labels, $field );
|
||||
}
|
||||
|
||||
return $field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the labels should be translated in the current context.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function can_translate_labels(): bool {
|
||||
global $pagenow;
|
||||
|
||||
if ( 'admin.php' === $pagenow && isset( $_POST['pll_action'], $_POST[ PLL_Import_Action::NONCE_NAME ] )
|
||||
&& PLL_Import_Action::ACTION_VALUE === $_POST['pll_action']
|
||||
&& wp_verify_nonce( $_POST[ PLL_Import_Action::NONCE_NAME ], PLL_Import_Action::ACTION_NAME ) ) {
|
||||
// Need to translate the labels during import to compare the default values.
|
||||
return true;
|
||||
}
|
||||
|
||||
// Polylang's settings pages.
|
||||
if ( PLL() instanceof PLL_Settings ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ACF's settings pages.
|
||||
$acf_post_types = array( 'acf-field-group', 'acf-post-type', 'acf-taxonomy', 'acf-ui-options-page' );
|
||||
|
||||
if ( 'edit.php' === $pagenow && isset( $_GET['post_type'] ) && in_array( $_GET['post_type'], $acf_post_types, true ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( 'post.php' === $pagenow && isset( $_GET['post'] ) && in_array( get_post_type( (int) $_GET['post'] ), $acf_post_types, true ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively translates the given labels for the given field or subset of a field (e.g subfields or layouts).
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $labels An array of labels to translate with label keys as array keys and label names as array values.
|
||||
* @param array $field A custom field definition.
|
||||
* @return array The translated labels.
|
||||
*
|
||||
* @phpstan-param LabelsMap $labels
|
||||
*/
|
||||
private function translate_field_labels_recursive( array $labels, array $field ) {
|
||||
$matcher = new PLL_Format_Util();
|
||||
|
||||
if ( isset( $field['default_value'] ) ) {
|
||||
// Stores the untranslated default value for later use.
|
||||
$field['pll_default_value'] = $field['default_value'];
|
||||
}
|
||||
|
||||
foreach ( $labels as $field_key => $sub_labels ) {
|
||||
$field_filtered = $matcher->filter_list( $field, $field_key );
|
||||
|
||||
foreach ( $field_filtered as $key => $field_value ) {
|
||||
if ( is_array( $sub_labels ) ) {
|
||||
/**
|
||||
* `$sub_labels` is like:
|
||||
* array(
|
||||
* 'default_value' => _x( 'Default value', 'ACF field setting label', 'polylang-pro' ),
|
||||
* 'placeholder' => _x( 'Placeholder', 'ACF field setting label', 'polylang-pro' ),
|
||||
* )
|
||||
*/
|
||||
if ( is_array( $field_value ) ) {
|
||||
$field[ $key ] = $this->translate_field_labels_recursive( $sub_labels, $field_value );
|
||||
}
|
||||
} elseif ( '' !== $field_value ) {
|
||||
$field[ $key ] = pll__( $field_value );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates all the ACF field groups labels.
|
||||
*
|
||||
* We hook to 'acf/load_field_groups' instead 'acf/translate_field_group',
|
||||
* not to be overridden by ACF when its local store is enabled.
|
||||
*
|
||||
* @see _acf_apply_get_local_internal_posts()
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array[] $posts An array of ACF posts.
|
||||
* @return array[] The array of ACF posts with the translated post title.
|
||||
*/
|
||||
public function translate_field_groups_labels( $posts ) {
|
||||
foreach ( $posts as $key => $post ) {
|
||||
$posts[ $key ]['title'] = pll__( $post['title'] );
|
||||
}
|
||||
return $posts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the labels of fields.
|
||||
* The method is recursive for layout fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $to_register List of strings to register.
|
||||
* @param array $fields An array of Custom field definitions.
|
||||
* @return array
|
||||
*
|
||||
* @phpstan-return list<ToRegister>
|
||||
*/
|
||||
private function register_fields( array $to_register, array $fields ): array {
|
||||
foreach ( $fields as $field ) {
|
||||
if ( ! acf_is_field_type( $field['type'] ) ) {
|
||||
// Avoid error if, for example, a repeater is created in ACF Pro and used later in ACF.
|
||||
continue;
|
||||
}
|
||||
|
||||
switch ( $field['type'] ) {
|
||||
case 'group':
|
||||
case 'repeater':
|
||||
$to_register = $this->register_fields( $to_register, $field['sub_fields'] );
|
||||
break;
|
||||
case 'flexible_content':
|
||||
foreach ( $field['layouts'] as $layout ) {
|
||||
$to_register = $this->register_fields( $to_register, $layout['sub_fields'] );
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
$matcher = new PLL_Format_Util();
|
||||
foreach ( $this->get_field_labels_to_translate() as $field_type => $field_labels ) {
|
||||
if ( ! is_string( $field['type'] ) || ! $matcher->matches( $field['type'], (string) $field_type ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$to_register = $this->register_field( $to_register, $field_labels, $field );
|
||||
}
|
||||
}
|
||||
|
||||
return $to_register;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the labels of a field recursively.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $to_register List of strings to register.
|
||||
* @param array $labels An array of labels to register with label keys as array keys and label names as array values.
|
||||
* @param array $field A custom field definition.
|
||||
* @return array
|
||||
*
|
||||
* @phpstan-param LabelsMap $labels
|
||||
* @phpstan-return list<ToRegister>
|
||||
*/
|
||||
private function register_field( array $to_register, array $labels, array $field ): array {
|
||||
$matcher = new PLL_Format_Util();
|
||||
|
||||
foreach ( $labels as $field_key => $label ) {
|
||||
$field_filtered = $matcher->filter_list( $field, $field_key );
|
||||
|
||||
foreach ( $field_filtered as $field_value ) {
|
||||
if ( is_array( $label ) ) {
|
||||
/**
|
||||
* `$label` is like:
|
||||
* array(
|
||||
* 'default_value' => _x( 'Default value', 'ACF field setting label', 'polylang-pro' ),
|
||||
* 'placeholder' => _x( 'Placeholder', 'ACF field setting label', 'polylang-pro' ),
|
||||
* )
|
||||
*/
|
||||
if ( is_array( $field_value ) ) {
|
||||
$to_register = $this->register_field( $to_register, $label, $field_value );
|
||||
}
|
||||
} else {
|
||||
$to_register[] = array(
|
||||
'name' => $label,
|
||||
'string' => $field_value,
|
||||
'multiline' => true,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $to_register;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of field labels to translate, by field type and label key.
|
||||
* Wildcards are supported for the field types and label keys.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return array {
|
||||
* An array with field types as array keys, and recursive sub-arrays as array values.
|
||||
* These sub-arrays have label keys as array keys, and label names as array values.
|
||||
*
|
||||
* Ex:
|
||||
* array(
|
||||
* 'custom_field_type' => array(
|
||||
* 'custom_field_key' => 'Custom field key',
|
||||
* 'another_field_key' => array(
|
||||
* 'first_choice' => 'First choice',
|
||||
* 'second_choice' => 'Second choice',
|
||||
* ),
|
||||
* ),
|
||||
* )
|
||||
* }
|
||||
*
|
||||
* @phpstan-return LabelsByType
|
||||
*/
|
||||
private function get_field_labels_to_translate(): array {
|
||||
if ( is_array( $this->labels ) ) {
|
||||
return $this->labels;
|
||||
}
|
||||
|
||||
$labels = array(
|
||||
'default_value' => _x( 'Default value', 'ACF field setting label', 'polylang-pro' ),
|
||||
'placeholder' => _x( 'Placeholder', 'ACF field setting label', 'polylang-pro' ),
|
||||
'prepend' => _x( 'Prefix', 'ACF field setting label', 'polylang-pro' ),
|
||||
'append' => _x( 'Suffix', 'ACF field setting label', 'polylang-pro' ),
|
||||
'message' => _x( 'Message', 'ACF field setting label', 'polylang-pro' ),
|
||||
'ui_on_text' => _x( 'ON text', 'ACF field setting label', 'polylang-pro' ),
|
||||
'ui_off_text' => _x( 'OFF text', 'ACF field setting label', 'polylang-pro' ),
|
||||
'choice' => _x( 'Choice', 'ACF field setting label', 'polylang-pro' ),
|
||||
'label' => _x( 'Label', 'ACF field setting label', 'polylang-pro' ),
|
||||
);
|
||||
|
||||
$this->labels = array(
|
||||
'*' => array(
|
||||
'label' => $labels['label'],
|
||||
'instructions' => _x( 'Instructions', 'ACF field setting label', 'polylang-pro' ),
|
||||
),
|
||||
'button_group' => array(
|
||||
'choices' => array(
|
||||
'*' => $labels['choice'],
|
||||
),
|
||||
),
|
||||
'checkbox' => array(
|
||||
'choices' => array(
|
||||
'*' => $labels['choice'],
|
||||
),
|
||||
),
|
||||
'email' => array(
|
||||
'default_value' => $labels['default_value'],
|
||||
'placeholder' => $labels['placeholder'],
|
||||
'prepend' => $labels['prepend'],
|
||||
'append' => $labels['append'],
|
||||
),
|
||||
'flexible_content' => array(
|
||||
'layouts' => array(
|
||||
'*' => array(
|
||||
'label' => $labels['label'],
|
||||
),
|
||||
),
|
||||
),
|
||||
'number' => array(
|
||||
'placeholder' => $labels['placeholder'],
|
||||
'prepend' => $labels['prepend'],
|
||||
'append' => $labels['append'],
|
||||
),
|
||||
'message' => array(
|
||||
'message' => $labels['message'],
|
||||
),
|
||||
'password' => array(
|
||||
'placeholder' => $labels['placeholder'],
|
||||
'prepend' => $labels['prepend'],
|
||||
'append' => $labels['append'],
|
||||
),
|
||||
'radio' => array(
|
||||
'choices' => array(
|
||||
'*' => $labels['choice'],
|
||||
),
|
||||
),
|
||||
'range' => array(
|
||||
'prepend' => $labels['prepend'],
|
||||
'append' => $labels['append'],
|
||||
),
|
||||
'select' => array(
|
||||
'choices' => array(
|
||||
'*' => $labels['choice'],
|
||||
),
|
||||
),
|
||||
'text' => array(
|
||||
'default_value' => $labels['default_value'],
|
||||
'placeholder' => $labels['placeholder'],
|
||||
'prepend' => $labels['prepend'],
|
||||
'append' => $labels['append'],
|
||||
),
|
||||
'textarea' => array(
|
||||
'default_value' => $labels['default_value'],
|
||||
'placeholder' => $labels['placeholder'],
|
||||
),
|
||||
'true_false' => array(
|
||||
'message' => $labels['message'],
|
||||
'ui_on_text' => $labels['ui_on_text'],
|
||||
'ui_off_text' => $labels['ui_off_text'],
|
||||
),
|
||||
'url' => array(
|
||||
'default_value' => $labels['default_value'],
|
||||
'placeholder' => $labels['placeholder'],
|
||||
),
|
||||
'wysiwyg' => array(
|
||||
'default_value' => $labels['default_value'],
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Filters the list of field keys to translate, by field type.
|
||||
* Wildcards are supported for the field types.
|
||||
*
|
||||
* @var array $labels array {
|
||||
* An array with field types as array keys, and recursive sub-arrays as array values.
|
||||
* These sub-arrays have label keys as array keys, and label names as array values.
|
||||
*
|
||||
* Ex:
|
||||
* array(
|
||||
* 'custom_field_type' => array(
|
||||
* 'custom_field_key' => 'Custom field key',
|
||||
* 'another_field_key' => array(
|
||||
* 'first_choice' => 'First choice',
|
||||
* 'second_choice' => 'Second choice',
|
||||
* ),
|
||||
* ),
|
||||
* )
|
||||
* }
|
||||
*/
|
||||
$labels = apply_filters( 'pll_acf_field_labels_to_translate', $this->labels );
|
||||
|
||||
if ( is_array( $labels ) ) {
|
||||
$this->labels = $labels;
|
||||
}
|
||||
|
||||
return $this->labels;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Labels;
|
||||
|
||||
use stdClass;
|
||||
use ACF_Internal_Post_Type;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Registers and translates the labels of custom post types created within ACF's UI.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Post_Type extends Abstract_Object_Type {
|
||||
/**
|
||||
* Returns the type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
protected function get_type(): string {
|
||||
return 'post_type';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instance of the related "ACF type".
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return ACF_Internal_Post_Type
|
||||
*/
|
||||
protected function get_acf_type_instance(): ACF_Internal_Post_Type {
|
||||
return acf_get_instance( 'ACF_Post_Type' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of type objects containing labels.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return object[]
|
||||
*
|
||||
* @phpstan-return array<
|
||||
* non-falsy-string,
|
||||
* object{label: string, description: string, labels: object}&stdClass
|
||||
* >
|
||||
*/
|
||||
protected function get_type_objects(): array {
|
||||
return $GLOBALS['wp_post_types'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the label of the type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-empty-string
|
||||
*/
|
||||
protected function get_type_label(): string {
|
||||
return 'Post Type';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Labels;
|
||||
|
||||
use stdClass;
|
||||
use ACF_Internal_Post_Type;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Registers and translates the labels of custom taxonomies created within ACF's UI.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Taxonomy extends Abstract_Object_Type {
|
||||
/**
|
||||
* Returns the type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
protected function get_type(): string {
|
||||
return 'taxonomy';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instance of the related "ACF type".
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return ACF_Internal_Post_Type
|
||||
*/
|
||||
protected function get_acf_type_instance(): ACF_Internal_Post_Type {
|
||||
return acf_get_instance( 'ACF_Taxonomy' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of type objects containing labels.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return object[]
|
||||
*
|
||||
* @phpstan-return array<
|
||||
* non-falsy-string,
|
||||
* object{label: string, description: string, labels: object}&stdClass
|
||||
* >
|
||||
*/
|
||||
protected function get_type_objects(): array {
|
||||
return $GLOBALS['wp_taxonomies'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the label of the type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-empty-string
|
||||
*/
|
||||
protected function get_type_label(): string {
|
||||
return 'Taxonomy';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF;
|
||||
|
||||
use ACF_Location;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Adds a Language ACF location allowing to display a field group only for one language.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Location_Language extends ACF_Location {
|
||||
|
||||
/**
|
||||
* Initializes props.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize() {
|
||||
$this->name = 'language';
|
||||
$this->label = __( 'Language', 'polylang-pro' );
|
||||
$this->category = $this->label; // Create a new category with the same name.
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches the provided rule against the screen args returning a bool result.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $rule The location rule.
|
||||
* @param array $screen The screen args.
|
||||
* @param array $field_group The field group settings.
|
||||
* @return bool
|
||||
*/
|
||||
public function match( $rule, $screen, $field_group ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
|
||||
$language = pll_current_language();
|
||||
return empty( $language ) || $this->compare_to_rule( $language, $rule );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of possible values for this rule type.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $rule A location rule.
|
||||
* @return array
|
||||
*/
|
||||
public function get_values( $rule ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
|
||||
return array_combine( pll_languages_list(), pll_languages_list( array( 'fields' => 'name' ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the field group has a language location rule.
|
||||
*
|
||||
* @since 3.7.1
|
||||
*
|
||||
* @param array $field_group Field group definition.
|
||||
* @return bool True if the field group has a language location rule, false otherwise.
|
||||
*/
|
||||
public static function has_language_location_rule( array $field_group ): bool {
|
||||
if ( empty( $field_group ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( empty( $field_group['location'] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ( $field_group['location'] as $location ) {
|
||||
foreach ( $location as $rule ) {
|
||||
if ( 'language' === $rule['param'] ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the ACF field group of a field (including nested fields within repeaters, flexible content, or other complex field types).
|
||||
*
|
||||
* @since 3.7.3
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
*
|
||||
* @return array The field group array on success, an empty array on failure.
|
||||
*/
|
||||
public static function get_field_group_from_field( array $field ): array {
|
||||
if ( 0 === $field['ID'] ) {
|
||||
// New field.
|
||||
$field_group = acf_get_field_group( 0 );
|
||||
return ! empty( $field_group ) ? $field_group : array();
|
||||
}
|
||||
|
||||
if ( empty( $field['parent'] ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$field_group = acf_get_field_group( $field['parent'] );
|
||||
if ( ! empty( $field_group ) ) {
|
||||
return $field_group;
|
||||
}
|
||||
|
||||
// If not a field group, get parent field and continue.
|
||||
$parent_field = acf_get_field( $field['parent'] );
|
||||
return $parent_field ? self::get_field_group_from_field( $parent_field ) : array();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF;
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Labels\Field_Groups;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Labels\Post_Type;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Labels\Taxonomy;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Translation_Instructions;
|
||||
|
||||
/**
|
||||
* Manages compatibility with Advanced Custom Fields Pro.
|
||||
*
|
||||
* @since 2.0
|
||||
*/
|
||||
class Main {
|
||||
|
||||
/**
|
||||
* @var Field_Settings
|
||||
*/
|
||||
public $field_settings;
|
||||
|
||||
/**
|
||||
* @var Field_Groups
|
||||
*/
|
||||
public $field_groups_labels;
|
||||
|
||||
/**
|
||||
* @var Post_Type
|
||||
*/
|
||||
public $post_types_labels;
|
||||
|
||||
/**
|
||||
* @var Taxonomy
|
||||
*/
|
||||
public $taxonomies_labels;
|
||||
|
||||
/**
|
||||
* @var Translation_Instructions
|
||||
*/
|
||||
public $translation_instructions;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->field_settings = new Field_Settings();
|
||||
$this->field_groups_labels = new Field_Groups();
|
||||
$this->post_types_labels = new Post_Type();
|
||||
$this->taxonomies_labels = new Taxonomy();
|
||||
$this->translation_instructions = new Translation_Instructions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes filters for ACF.
|
||||
*
|
||||
* @since 2.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_acf_init(): void {
|
||||
$this->field_settings->on_acf_init();
|
||||
$this->translation_instructions->on_acf_init();
|
||||
|
||||
/**
|
||||
* Filters whether ACF labels translation should be enabled.
|
||||
* This allows users to completely disable ACF labels translation (fields, post types, taxonomies) if they don't need it.
|
||||
*
|
||||
* @since 3.7.5
|
||||
*
|
||||
* @param bool $enabled Whether ACF labels translation is enabled. Default true.
|
||||
*/
|
||||
$labels_translation_enabled = apply_filters( 'pll_enable_acf_labels_translation', true );
|
||||
if ( $labels_translation_enabled ) {
|
||||
$this->field_groups_labels->on_acf_init();
|
||||
$this->post_types_labels->on_acf_init();
|
||||
$this->taxonomies_labels->on_acf_init();
|
||||
}
|
||||
|
||||
Dispatcher::on_acf_init();
|
||||
|
||||
acf_register_location_type( Location_Language::class );
|
||||
|
||||
add_filter( 'acf/get_taxonomies', array( $this, 'get_taxonomies' ) );
|
||||
add_filter( 'pll_get_post_types', array( $this, 'get_post_types' ) );
|
||||
add_action( 'init', array( Dispatcher::class, 'on_blocks_registered' ), 999 ); // Late so blocks have a chance to register, usually done on `init`.
|
||||
|
||||
PLL()->model->cache->clean( 'post_types' ); // A bit hacky.
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells whether or not ACF integration can be used.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return bool True if the integration can be used, false otherwise.
|
||||
*/
|
||||
public static function can_use(): bool {
|
||||
return defined( 'ACF_VERSION' ) && version_compare( ACF_VERSION, '6.0.0', '>=' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevents ACF to display our private taxonomies.
|
||||
*
|
||||
* @since 2.8
|
||||
*
|
||||
* @param string[] $taxonomies Taxonomy names.
|
||||
* @return string[]
|
||||
*/
|
||||
public function get_taxonomies( $taxonomies ) {
|
||||
return array_diff( $taxonomies, get_taxonomies( array( '_pll' => true ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure not to translate the Field Groups post type.
|
||||
*
|
||||
* @since 2.0
|
||||
* @since 3.7 Removed second param and disallow to translate the field groups.
|
||||
*
|
||||
* @param string[] $post_types List of post types.
|
||||
* @return string[]
|
||||
*/
|
||||
public function get_post_types( $post_types ) {
|
||||
unset( $post_types['acf-field-group'] );
|
||||
return $post_types;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
# ACF Integration
|
||||
|
||||
Integration with Advanced Custom Fields Pro, bootstrapped in `acf/load.php` with `Main` main object.
|
||||
All names take place in `WP_Syntex\Polylang_Pro\Integrations\ACF` namespace.
|
||||
|
||||
## How field translation works
|
||||
|
||||
### For standard custom fields
|
||||
|
||||
`Dispatcher` applies strategies to custom fields of `Entity\Abstract_Object` objects (posts or terms) as well as ACF blocks.
|
||||
These strategies follow the Strategy Pattern to make fields benefit from Polylang Pro core features such as:
|
||||
|
||||
| Feature | Strategy |
|
||||
| --- | --- |
|
||||
| New post translation creation | `Strategy\Copy` |
|
||||
| Synchronization on post/term update | `Strategy\Synchronize` |
|
||||
| Bulk translate | `Strategy\Copy` or `Strategy\Copy_All` |
|
||||
| Export, import and machine translation | `Strategy\Export`, `Strategy\Import` and `Strategy\Abstract_Collect_Ids` |
|
||||
|
||||
### For block fields
|
||||
|
||||
Import, export, machine translation and smart synchronization for fields containing IDs are supported thanks to `Entity\Blocks` class. This class is able to apply any strategy to a list of blocks thanks to `Entity\Blocks::apply_on_blocks()`.
|
||||
|
||||
### Note on language location
|
||||
|
||||
To provide end users a way to have field groups displayed only for specific language, a custom location is provided with `Location\Language`.
|
||||
|
||||
## Translated labels
|
||||
|
||||
Now that field groups are not translatable anymore, the only way to have them displayed in several languages is using strings translations.
|
||||
This new feature lays in `Labels\Field_Groups`.
|
||||
Note that the integration offers the same feature for ACF post types and taxonomies (`Labels\Abstract_Object_Type`).
|
||||
|
||||
## Editor
|
||||
|
||||
Integration with editors UI can be found in `Post` and `Term` (see `admin_enqueue_scripts()` and `on_ajax_post/term_lang_choice()`), as well as in `Dispatcher` (see `add_language_to_query()`) and `acf/js/index.js`.
|
||||
|
||||
## Migration from Polylang Pro prior to 3.7
|
||||
|
||||
Field groups are not translated at all now. For sites having translated field groups with Polylang Pro < 3.7, a migration will occur on update.
|
||||
This migration will update each field groups with a location corresponding to the formerly assigned language.
|
||||
The related code can be found in `WP_Syntex\Polylang_Pro\Upgrade::upgrade_3_7()`.
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Abstract_Object;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Translatable_Entity_Interface;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* The collect IDs strategy.
|
||||
* Gathers the IDs of the linked entities prior to export.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
abstract class Abstract_Collect_Ids extends Abstract_Strategy {
|
||||
|
||||
/**
|
||||
* @var int[] Entities IDs linked to an object.
|
||||
*/
|
||||
protected $linked_ids = array();
|
||||
|
||||
/**
|
||||
* Executes the strategy on a given field.
|
||||
* Depending on the type of fields, this will add the collected IDs to the relevant property.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args Optional arguments, none here.
|
||||
* @return mixed Untouched custom field value.
|
||||
*/
|
||||
protected function apply( Abstract_Object $object, $value, array $field, array $args = array() ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
|
||||
$this->linked_ids = array_merge(
|
||||
$this->linked_ids,
|
||||
$this->get_ids_from_field( $value, $field )
|
||||
);
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively checks if a field can be collected.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return bool
|
||||
*/
|
||||
protected function can_execute_recursive( array $field ): bool {
|
||||
if ( isset( $field['translations'] ) && 'ignore' !== $field['translations'] ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return parent::can_execute_recursive( $field );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the collected entities IDs.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Translatable_Entity_Interface $object Object holding the logic to apply the strategy.
|
||||
* @return int[]
|
||||
*/
|
||||
public function get( Translatable_Entity_Interface $object ): array {
|
||||
$object->apply_to_all_fields( $this );
|
||||
|
||||
return $this->linked_ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the object IDs of a field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @return int[] Custom field value.
|
||||
*/
|
||||
abstract protected function get_ids_from_field( $value, array $field );
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Abstract_Object;
|
||||
use PLL_Language;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Abstract class for the translation strategies.
|
||||
* Holds logic common to all strategies, mostly related to field structure.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
abstract class Abstract_Strategy {
|
||||
/**
|
||||
* @var bool[]
|
||||
*/
|
||||
private $can_execute = array();
|
||||
|
||||
/**
|
||||
* Checks if the translation strategy can be applied.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return bool
|
||||
*/
|
||||
public function can_execute( array $field ): bool {
|
||||
$key = $field['key'];
|
||||
|
||||
if ( ! isset( $this->can_execute[ $key ] ) ) {
|
||||
$this->can_execute[ $key ] = $this->can_execute_recursive( $field );
|
||||
}
|
||||
|
||||
return $this->can_execute[ $key ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the translation strategy.
|
||||
*
|
||||
* Depending on the type of fields, this will copy / synchronize a layout or
|
||||
* auto-translate object ids.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type mixed $original_value Optional. The translated value of the field, if any.
|
||||
* }
|
||||
* @return mixed Custom field value of the target object.
|
||||
*/
|
||||
public function execute( Abstract_Object $object, $value, array $field, array $args = array() ) {
|
||||
$args = wp_parse_args( $args, array( 'original_value' => null ) );
|
||||
|
||||
if ( ! $this->can_execute( $field ) ) {
|
||||
return $args['original_value'];
|
||||
}
|
||||
|
||||
if ( ! acf_is_field_type( $field['type'] ) ) {
|
||||
// Avoid error if, for example, a repeater is created in ACF Pro and used later in ACF.
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( empty( $value ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
switch ( $field['type'] ) {
|
||||
/*
|
||||
* For ACF `flexible_content`, `repeater`, `clone` and `group` fields, ACF gets their real value (null) as their original value
|
||||
* and not an array of their subfields. So, in this case, we force this original value to an empty array to be able to call
|
||||
* `apply_on_rows()` method to copy subfields and make their translation.
|
||||
*/
|
||||
case 'flexible_content':
|
||||
if ( is_array( $value ) ) {
|
||||
$args['original_value'] = is_array( $args['original_value'] ) ? $args['original_value'] : array();
|
||||
$value = $this->apply_on_layouts( $object, $value, $field, $args );
|
||||
}
|
||||
break;
|
||||
case 'repeater':
|
||||
if ( is_array( $value ) ) {
|
||||
$args['original_value'] = is_array( $args['original_value'] ) ? $args['original_value'] : array();
|
||||
$value = $this->apply_on_rows( $object, $value, $field, $args );
|
||||
}
|
||||
break;
|
||||
case 'clone':
|
||||
case 'group':
|
||||
if ( is_array( $value ) ) {
|
||||
$args['original_value'] = is_array( $args['original_value'] ) ? $args['original_value'] : array();
|
||||
$value = $this->apply_on_group( $object, $value, $field, $args );
|
||||
}
|
||||
break;
|
||||
default:
|
||||
$value = $this->apply( $object, $value, $field, $args );
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively checks if the translation strategy can be applied.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return bool
|
||||
*/
|
||||
protected function can_execute_recursive( array $field ): bool {
|
||||
if ( ! acf_is_field_type( $field['type'] ) ) {
|
||||
// Avoid error if, for example, a repeater is created in ACF Pro and used later in ACF.
|
||||
return false;
|
||||
}
|
||||
|
||||
switch ( $field['type'] ) {
|
||||
case 'flexible_content':
|
||||
foreach ( $field['layouts'] as $layout ) {
|
||||
foreach ( $layout['sub_fields'] as $sub_field ) {
|
||||
if ( $this->can_execute( $sub_field ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'clone':
|
||||
case 'group':
|
||||
case 'repeater':
|
||||
foreach ( $field['sub_fields'] as $sub_field ) {
|
||||
if ( $this->can_execute( $sub_field ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the strategy on a given field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args Array of arguments.
|
||||
* @return mixed Custom field value of the target object.
|
||||
*/
|
||||
abstract protected function apply( Abstract_Object $object, $value, array $field, array $args = array() );
|
||||
|
||||
/**
|
||||
* Copies or synchronizes subfields in a repeater or flexible content field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param array $values Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type mixed $original_value The translated value of the field, if any.
|
||||
* }
|
||||
* @return array Custom field value of the target object.
|
||||
*/
|
||||
protected function apply_on_rows( Abstract_Object $object, array $values, array $field, array $args = array() ): array {
|
||||
if ( empty( $field['sub_fields'] ) ) {
|
||||
return $values;
|
||||
}
|
||||
|
||||
$original_value = $args['original_value'];
|
||||
|
||||
foreach ( $field['sub_fields'] as $subfield ) {
|
||||
foreach ( $values as $row => $subvalues ) {
|
||||
if ( ! is_array( $subvalues ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
$subfield['pll_key'] = $this->get_field_key( $field ) . '_' . $row . '_' . $subfield['key']; // Adds an entry in `subfield` with the full path of the field.
|
||||
$args['original_value'] = $original_value[ $row ] ?? null;
|
||||
$values[ $row ] = $this->apply_on_subfield(
|
||||
$object,
|
||||
$subvalues,
|
||||
$subfield,
|
||||
$args
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks through layouts and apply the strategy to their subfields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param array $values Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args Array of arguments.
|
||||
* @return array Custom field value of the target object.
|
||||
*/
|
||||
protected function apply_on_layouts( Abstract_Object $object, array $values, array $field, array $args = array() ): array {
|
||||
if ( empty( $field['layouts'] ) ) {
|
||||
return $values;
|
||||
}
|
||||
|
||||
foreach ( $field['layouts'] as $layout ) {
|
||||
if ( empty( $layout['sub_fields'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$values = $this->apply_on_rows( $object, $values, $layout, $args );
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies or synchronizes sub fields in a group or clone field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param array $values Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args Array of arguments.
|
||||
* @return array Custom field value of the target object.
|
||||
*/
|
||||
protected function apply_on_group( Abstract_Object $object, array $values, array $field, array $args = array() ): array {
|
||||
foreach ( $field['sub_fields'] as $subfield ) {
|
||||
$subfield['pll_key'] = $this->get_field_key( $subfield ) . '_' . $subfield['key']; // Adds an entry in `subfield` with the full path of the field.
|
||||
$values = $this->apply_on_subfield(
|
||||
$object,
|
||||
$values,
|
||||
$subfield,
|
||||
$args
|
||||
);
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies or synchronizes subfield values.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param array $subvalues Custom field values of the source object.
|
||||
* @param array $subfield Custom subfield definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type mixed $original_value The translated value of the field, if any.
|
||||
* }
|
||||
* @return array Custom field value of the target object.
|
||||
*/
|
||||
protected function apply_on_subfield( Abstract_Object $object, array $subvalues, array $subfield, array $args = array() ): array {
|
||||
if ( empty( $subfield['parent'] ) ) {
|
||||
// Not a subfield.
|
||||
return $subvalues;
|
||||
}
|
||||
|
||||
if ( ! $this->can_execute( $subfield ) ) {
|
||||
if ( isset( $args['original_value'][ $subfield['key'] ] ) ) {
|
||||
// If original values are hold with field key.
|
||||
$subvalues[ $subfield['key'] ] = $args['original_value'][ $subfield['key'] ];
|
||||
} elseif ( isset( $args['original_value'][ $subfield['name'] ] ) ) {
|
||||
// If original values are hold with field name.
|
||||
$subvalues[ $subfield['name'] ] = $args['original_value'][ $subfield['name'] ];
|
||||
} else {
|
||||
// Strip out the subfield if it can't be executed so the value won't be processed.
|
||||
unset( $subvalues[ $subfield['name'] ], $subvalues[ $subfield['key'] ] );
|
||||
}
|
||||
return $subvalues;
|
||||
}
|
||||
|
||||
if ( isset( $subvalues[ $subfield['name'] ] ) ) {
|
||||
// Is the group value update with field name as key?
|
||||
$selector = $subfield['name'];
|
||||
} elseif ( isset( $subvalues[ $subfield['key'] ] ) ) {
|
||||
// Is the group value update with field key as key?
|
||||
$selector = $subfield['key'];
|
||||
}
|
||||
|
||||
if ( empty( $selector ) ) {
|
||||
return $subvalues;
|
||||
}
|
||||
|
||||
$args['original_value'] = $args['original_value'][ $selector ] ?? null;
|
||||
|
||||
$subvalues[ $selector ] = $this->execute(
|
||||
$object,
|
||||
$subvalues[ $selector ],
|
||||
$subfield,
|
||||
$args
|
||||
);
|
||||
|
||||
return $subvalues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the field key to use.
|
||||
* Used to have a steady way of finding nested fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Field definition.
|
||||
* @return string Field key.
|
||||
*/
|
||||
protected function get_field_key( array $field ): string {
|
||||
/*
|
||||
* Why look for these keys in this order?
|
||||
* #1: `pll_key` should be defined most of the time, it's used to prepend parent key
|
||||
* to keep track of fields hierarchy and identify them easily during export/import.
|
||||
* #2: `_key` ensures to look for the original key in case the field is a seamless clone for instance.
|
||||
* #3: `key` the standard field key.
|
||||
*/
|
||||
return $field['pll_key'] ?? $field['__key'] ?? $field['key'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a field's value is the default value.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type PLL_Language $source_language Optional. The language object of the source object.
|
||||
* @type mixed $original_value Optional. The translated value of the field, if any.
|
||||
* }
|
||||
*
|
||||
* @return bool True if it's the default value, false otherwise.
|
||||
*/
|
||||
protected function is_field_default_value( $value, array $field, array $args = array() ): bool {
|
||||
if ( ! isset( $field['pll_default_value'], $args['source_language'] ) || ! $args['source_language'] instanceof PLL_Language ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$default_value_in_source_language = $this->get_translated_default_value( $field, $args['source_language'] );
|
||||
|
||||
return $default_value_in_source_language === $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the field default value if applicable.
|
||||
*
|
||||
* @since 3.7.2
|
||||
*
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args Array of arguments.
|
||||
* @return mixed Custom field value of the target object.
|
||||
*/
|
||||
protected function maybe_translate_field_default_value( $value, array $field, array $args = array() ) {
|
||||
return $this->is_field_default_value( $value, $field, $args ) ? $args['original_value'] : $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the translated default value for a field in the specified language.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @param PLL_Language $language The specified language object.
|
||||
* @return mixed The translated default value, or the original if no translation exists.
|
||||
*/
|
||||
protected function get_translated_default_value( array $field, PLL_Language $language ) {
|
||||
return ! is_string( $field['pll_default_value'] ) ? $field['pll_default_value'] : pll_translate_string( $field['pll_default_value'], $language->slug );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* The collect post IDs strategy.
|
||||
* Gathers the IDs of the linked posts prior to export.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Collect_Post_Ids extends Abstract_Collect_Ids {
|
||||
|
||||
/**
|
||||
* Collects the post IDs of a field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @return int[] Custom field value.
|
||||
*/
|
||||
protected function get_ids_from_field( $value, array $field ) {
|
||||
switch ( $field['type'] ) {
|
||||
case 'image':
|
||||
case 'file':
|
||||
if ( PLL()->options['media_support'] && is_numeric( $value ) ) {
|
||||
return array( (int) $value );
|
||||
}
|
||||
break;
|
||||
case 'gallery':
|
||||
if ( PLL()->options['media_support'] && is_array( $value ) ) {
|
||||
return array_map( 'intval', $value );
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* The collect term IDs strategy.
|
||||
* Gathers the IDs of the linked terms prior to export.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Collect_Term_Ids extends Abstract_Collect_Ids {
|
||||
|
||||
/**
|
||||
* Collects the term IDs of a field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @return int[] Custom field value.
|
||||
*/
|
||||
protected function get_ids_from_field( $value, array $field ) {
|
||||
if ( 'taxonomy' !== $field['type'] || ! pll_is_translated_taxonomy( $field['taxonomy'] ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
if ( is_numeric( $value ) ) {
|
||||
return array( (int) $value );
|
||||
}
|
||||
|
||||
if ( is_array( $value ) ) {
|
||||
return array_map( 'intval', $value );
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Abstract_Object;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Copy strategy.
|
||||
* Copies the custom field value from the source object to the target object.
|
||||
* Honors translations settings.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Copy extends Abstract_Strategy {
|
||||
/**
|
||||
* Executes the strategy on a given field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type PLL_Language $target_language Optional. The language object of the target object.
|
||||
* @type PLL_Language $source_language Optional. The language object of the source object.
|
||||
* }
|
||||
* @return mixed Custom field value of the target object.
|
||||
*/
|
||||
protected function apply( Abstract_Object $object, $value, array $field, array $args = array() ) {
|
||||
if ( ! isset( $args['target_language'] ) || ! $args['target_language'] instanceof PLL_Language ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
switch ( $field['type'] ) {
|
||||
case 'image':
|
||||
case 'file':
|
||||
if ( PLL()->options['media_support'] && is_numeric( $value ) ) {
|
||||
$value = $this->translate_media( (int) $value, $args['target_language'] );
|
||||
}
|
||||
break;
|
||||
case 'gallery':
|
||||
if ( PLL()->options['media_support'] && is_array( $value ) ) {
|
||||
$value = $this->translate_gallery( $value, $args['target_language'] );
|
||||
}
|
||||
break;
|
||||
case 'post_object':
|
||||
case 'relationship':
|
||||
$value = $this->translate_post( $value, $args['target_language'] );
|
||||
break;
|
||||
case 'taxonomy':
|
||||
if ( pll_is_translated_taxonomy( $field['taxonomy'] ) ) {
|
||||
$value = $this->translate_term( $value, $args['target_language'] );
|
||||
}
|
||||
break;
|
||||
case 'page_link':
|
||||
if ( is_array( $value ) || is_int( $value ) || is_string( $value ) ) {
|
||||
$value = $this->translate_page_link( $value, $args['target_language'] );
|
||||
}
|
||||
break;
|
||||
case 'wysiwyg':
|
||||
if ( is_string( $value ) ) {
|
||||
$value = PLL()->sync_content->translate_content(
|
||||
$value,
|
||||
null,
|
||||
$args['target_language']
|
||||
);
|
||||
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return $this->maybe_translate_field_default_value( $value, $field, $args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively checks if a field can be copied.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return bool
|
||||
*/
|
||||
protected function can_execute_recursive( array $field ): bool {
|
||||
if ( isset( $field['translations'] ) && 'ignore' !== $field['translations'] ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return parent::can_execute_recursive( $field );
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates a media field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int $value Custom field value of the source object.
|
||||
* @param PLL_Language $lang Language object of the target object.
|
||||
* @return int Custom field value of the target object.
|
||||
*/
|
||||
protected function translate_media( int $value, PLL_Language $lang ): int {
|
||||
$tr_id = pll_get_post( $value, $lang );
|
||||
|
||||
if ( $tr_id ) {
|
||||
return $tr_id;
|
||||
}
|
||||
|
||||
return PLL()->model->post->create_media_translation( $value, $lang );
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates media ids in a gallery field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int[] $values Custom field value of the source object.
|
||||
* @param PLL_Language $lang Language object of the target object.
|
||||
* @return string[] Custom field value of the target object.
|
||||
*
|
||||
* @phpstan-param array<int|numeric-string> $values
|
||||
* @phpstan-return list<numeric-string>
|
||||
*/
|
||||
protected function translate_gallery( array $values, PLL_Language $lang ): array {
|
||||
$return = array();
|
||||
|
||||
foreach ( $values as $value ) {
|
||||
$return[] = $this->translate_media( (int) $value, $lang );
|
||||
}
|
||||
|
||||
/** @phpstan-var list<numeric-string> */
|
||||
return array_map( 'strval', $return ); // See `acf_field_gallery::update_value()`.
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates post IDs relationship and post object fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param PLL_Language $lang Language object of the target object.
|
||||
* @return int|string[] Custom field value of the target object.
|
||||
*
|
||||
* @phpstan-return (
|
||||
* $value is array ? list<numeric-string> : int
|
||||
* )
|
||||
*/
|
||||
protected function translate_post( $value, PLL_Language $lang ) {
|
||||
if ( is_numeric( $value ) ) {
|
||||
$value = (int) $value;
|
||||
$post_type = get_post_type( $value );
|
||||
|
||||
if ( ! $post_type || ! pll_is_translated_post_type( $post_type ) ) {
|
||||
// Same ID for not-translated languages.
|
||||
return $value;
|
||||
}
|
||||
|
||||
return (int) pll_get_post( $value, $lang );
|
||||
}
|
||||
|
||||
if ( is_array( $value ) ) {
|
||||
$return = array();
|
||||
foreach ( $value as $id ) {
|
||||
$return[] = (int) $this->translate_post( $id, $lang );
|
||||
}
|
||||
|
||||
/** @phpstan-var list<numeric-string> */
|
||||
return array_map( 'strval', $return ); // See the method update_value() for these fields.
|
||||
}
|
||||
|
||||
// Something went wrong.
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates term ids in a taxonomy field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param PLL_Language $lang Language object of the target object.
|
||||
* @return int|int[] Custom field value of the target object.
|
||||
*
|
||||
* @phpstan-return (
|
||||
* $value is array ? list<int> : int
|
||||
* )
|
||||
*/
|
||||
protected function translate_term( $value, PLL_Language $lang ) {
|
||||
if ( is_numeric( $value ) ) {
|
||||
return (int) pll_get_term( (int) $value, $lang );
|
||||
}
|
||||
|
||||
if ( is_array( $value ) ) {
|
||||
$return = array();
|
||||
foreach ( $value as $id ) {
|
||||
$return[] = (int) $this->translate_term( $id, $lang );
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
// Something went wrong.
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates a page link field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param int|string|(int|string)[] $value Custom field value of the source object.
|
||||
* @param PLL_Language $lang Language slug of the target object.
|
||||
* @return int|string|string[] Custom field value of the target object.
|
||||
*/
|
||||
protected function translate_page_link( $value, PLL_Language $lang ) {
|
||||
if ( is_numeric( $value ) ) {
|
||||
return (int) pll_get_post( (int) $value, $lang );
|
||||
}
|
||||
|
||||
if ( is_array( $value ) ) {
|
||||
// Multiple choices.
|
||||
$return = array();
|
||||
foreach ( $value as $p ) {
|
||||
if ( is_numeric( $p ) ) {
|
||||
$return[] = (int) pll_get_post( (int) $p, $lang );
|
||||
} elseif ( is_string( $p ) ) {
|
||||
$return[] = $this->translate_cpt_archive_link( $p, $lang ); // Archive.
|
||||
}
|
||||
}
|
||||
return array_map( 'strval', $return ); // See `acf_field_page_link::update_value()`.
|
||||
}
|
||||
|
||||
return $this->translate_cpt_archive_link( $value, $lang ); // Archive.
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates a CPT archive link in a page link field.
|
||||
*
|
||||
* @since 2.3.6
|
||||
* @since 3.7 `$lang` is a `PLL_Language` instead of a string.
|
||||
*
|
||||
* @param string $link CPT archive link.
|
||||
* @param PLL_Language $lang Language object of the target object.
|
||||
* @return string Modified link.
|
||||
*/
|
||||
protected function translate_cpt_archive_link( string $link, PLL_Language $lang ): string {
|
||||
/*
|
||||
* ACF doesn't use correctly `home_url()` function. It makes this URL not end with a trailing slash.
|
||||
* It makes our `PLL_Links_Model::switch_language_in_link()` not work correctly in this case.
|
||||
* @see https://github.com/AdvancedCustomFields/acf/blob/6.3.8/includes/fields/class-acf-field-page_link.php#L174
|
||||
*/
|
||||
if ( home_url() === $link ) {
|
||||
$link = home_url( '/' );
|
||||
}
|
||||
|
||||
$show_on_front = get_option( 'show_on_front' );
|
||||
$page_for_posts = get_option( 'page_for_posts' );
|
||||
|
||||
if ( 'page' === $show_on_front && is_numeric( $page_for_posts ) ) {
|
||||
// Gets `page_for_posts` URL of the target language.
|
||||
$post_archive_link = get_permalink( $lang->page_for_posts );
|
||||
return ! empty( $post_archive_link ) ? $post_archive_link : $link;
|
||||
}
|
||||
|
||||
$link = PLL()->links_model->switch_language_in_link( $link, $lang );
|
||||
|
||||
if ( ! isset( PLL()->translate_slugs ) ) {
|
||||
return $link;
|
||||
}
|
||||
|
||||
foreach ( PLL()->translate_slugs->slugs_model->get_translatable_slugs() as $type => $data ) {
|
||||
// Unfortunately ACF does not pass the post type, so let's try with all post type archives.
|
||||
if ( 0 === strpos( $type, 'archive_' ) ) {
|
||||
$link = PLL()->translate_slugs->slugs_model->switch_translated_slug( $link, $lang, $type );
|
||||
}
|
||||
}
|
||||
|
||||
return $link;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* This strategy copies all fields (even the ignored ones), for instance during duplication.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Copy_All extends Copy {
|
||||
|
||||
/**
|
||||
* Recursively checks if a field can be copied.
|
||||
* Always returns true to copy all fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return true
|
||||
*/
|
||||
protected function can_execute_recursive( array $field ): bool { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
use PLL_Export_Data;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Abstract_Object;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Export strategy.
|
||||
* Adds custom fields value to data export object.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Export extends Abstract_Strategy {
|
||||
|
||||
/**
|
||||
* @var PLL_Export_Data The export object.
|
||||
*/
|
||||
protected $export;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Export_Data $export The export object.
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( PLL_Export_Data $export ) {
|
||||
$this->export = $export;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the strategy on a given field.
|
||||
* Depending on the type of fields, this will add the fields with the translate option to the fields to export.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type mixed $original_value The translated or default value of the field, if any.
|
||||
* }
|
||||
* @return mixed The original value, so the strategy behaves like others.
|
||||
*/
|
||||
protected function apply( Abstract_Object $object, $value, array $field, array $args = array() ) {
|
||||
if ( 'translate_once' === $field['translations']
|
||||
&& 0 < PLL()->model->{$object->get_type()}->get( $object->get_id(), $args['target_language'] ) ) {
|
||||
// A translation exists and we're on a `translate_once` field, so return.
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( ! is_string( $value ) || empty( $value ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$original_value = is_string( $args['original_value'] ) ? $args['original_value'] : '';
|
||||
|
||||
if ( $this->is_field_default_value( $value, $field, $args ) ) {
|
||||
$translated = $this->get_translated_default_value( $field, $args['target_language'] );
|
||||
if ( $translated !== $field['pll_default_value'] ) {
|
||||
// This string has been translated in our Strings Translations, so DO NOT send it to the export.
|
||||
return $translated;
|
||||
}
|
||||
}
|
||||
|
||||
$this->export->add_translation_entry(
|
||||
array(
|
||||
'object_type' => $object->get_type(),
|
||||
'field_type' => 'acf',
|
||||
'field_id' => $this->get_field_key( $field ),
|
||||
'object_id' => $object->get_id(),
|
||||
),
|
||||
$value,
|
||||
$original_value === $field['default_value'] ? '' : $original_value // Do not export translated default values.
|
||||
);
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively checks if a field can be copied.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return bool
|
||||
*/
|
||||
protected function can_execute_recursive( array $field ): bool {
|
||||
if ( isset( $field['translations'] ) && in_array( $field['translations'], array( 'translate', 'translate_once' ), true ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return parent::can_execute_recursive( $field );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
use Translation_Entry;
|
||||
use Translations;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Import_Export\Services\Context;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Abstract_Object;
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Import strategy.
|
||||
* Saves the custom fields value from translated data objects (e.g. DeepL or XLIFF).
|
||||
|
||||
* @since 3.7
|
||||
*/
|
||||
class Import extends Copy {
|
||||
|
||||
/**
|
||||
* Translations set where to look for the post custom fields translations.
|
||||
*
|
||||
* @var Translations
|
||||
*/
|
||||
protected $translations;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Translations $translations A set of translations to search the custom fields translations in.
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( Translations $translations ) {
|
||||
$this->translations = $translations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the translation strategy.
|
||||
*
|
||||
* Depending on the type of fields, this will copy a layout and
|
||||
* auto-translate object ids and translated custom fields.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type mixed $original_value Optional. The translated or default value of the field, if any.
|
||||
* }
|
||||
* @return mixed Custom field value of the target object.
|
||||
*/
|
||||
public function execute( Abstract_Object $object, $value, array $field, array $args = array() ) {
|
||||
$args = wp_parse_args( $args, array( 'original_value' => null ) );
|
||||
|
||||
if ( ! $this->can_execute( $field ) ) {
|
||||
return $args['original_value'];
|
||||
}
|
||||
|
||||
if ( empty( $value ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( ! is_string( $value ) ) {
|
||||
return parent::execute( $object, $value, $field, $args );
|
||||
}
|
||||
|
||||
$args['original_value'] = is_string( $args['original_value'] ) ? $args['original_value'] : '';
|
||||
|
||||
$entry = new Translation_Entry(
|
||||
array(
|
||||
'singular' => $value,
|
||||
'context' => Context::to_string(
|
||||
array(
|
||||
Context::FIELD => 'acf',
|
||||
Context::ID => $this->get_field_key( $field ),
|
||||
)
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
/*
|
||||
* Use `translate_entry()` to know whether the entry is in the translation set or not.
|
||||
* Because `translate()` doesn't return false but the source string if the entry doesn't exist.
|
||||
*/
|
||||
if ( ! $this->translations->translate_entry( $entry ) ) {
|
||||
// The entry is not in the translation set.
|
||||
|
||||
if ( 'translate_once' === $field['translations'] && ! empty( $args['original_value'] ) ) {
|
||||
/*
|
||||
* If there is no entry in the translation set and the field is set to `translate_once`,
|
||||
* it means that it has already been translated.
|
||||
*/
|
||||
return $this->is_field_default_value( $value, $field, $args )
|
||||
? $this->get_translated_default_value( $field, $args['target_language'] )
|
||||
: $args['original_value'];
|
||||
}
|
||||
|
||||
if ( $this->is_field_default_value( $value, $field, $args ) ) {
|
||||
return $this->get_translated_default_value( $field, $args['target_language'] );
|
||||
}
|
||||
return parent::execute( $object, $value, $field, $args );
|
||||
}
|
||||
|
||||
$value = $this->translations->translate( $value, $entry->context );
|
||||
|
||||
return parent::execute(
|
||||
$object,
|
||||
$value,
|
||||
$field,
|
||||
$args
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy;
|
||||
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Entity\Abstract_Object;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Synchronization strategy.
|
||||
* Synchronizes the custom fields value from the source object to the target object.
|
||||
* Honors translations settings.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Synchronize extends Copy {
|
||||
/**
|
||||
* @var Copy
|
||||
*/
|
||||
protected $copy;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Copy $copy Copy Strategy.
|
||||
*/
|
||||
public function __construct( Copy $copy ) {
|
||||
$this->copy = $copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the translation strategy.
|
||||
*
|
||||
* Depending on the type of fields, this will copy / synchronize a layout or
|
||||
* auto-translate object ids.
|
||||
*
|
||||
* @since 3.7.1
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param mixed $value Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type mixed $original_value Optional. The translated value of the field, if any.
|
||||
* }
|
||||
* @return mixed Custom field value of the target object.
|
||||
*/
|
||||
public function execute( Abstract_Object $object, $value, array $field, array $args = array() ) {
|
||||
$args = wp_parse_args( $args, array( 'original_value' => null ) );
|
||||
|
||||
if ( ! $this->can_execute( $field ) ) {
|
||||
return $args['original_value'];
|
||||
}
|
||||
|
||||
if ( 'taxonomy' !== $field['type'] ) {
|
||||
return parent::execute( $object, $value, $field, $args );
|
||||
}
|
||||
|
||||
if ( ! isset( $args['target_language'] ) || ! $args['target_language'] instanceof PLL_Language ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if ( ! pll_is_translated_taxonomy( $field['taxonomy'] ) ) {
|
||||
// Do not go any further if a taxonomy is not translatable.
|
||||
return $value;
|
||||
}
|
||||
|
||||
$value = $this->translate_term( $value, $args['target_language'] );
|
||||
|
||||
if ( ! empty( $field['save_terms'] ) && isset( $args['target_id'] ) ) {
|
||||
/*
|
||||
* Save terms for the target object.
|
||||
*
|
||||
* The `acf_field_taxonomy::save_post()` method which assigns terms to the post fired
|
||||
* by the `'acf/save_post'`action, is only fired for the source post.
|
||||
* So we have to assign them to the target post ourselves.
|
||||
*/
|
||||
wp_set_object_terms( $args['target_id'], $value, $field['taxonomy'] );
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively checks if a field can be synchronized.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $field Custom field definition.
|
||||
* @return bool
|
||||
*/
|
||||
protected function can_execute_recursive( array $field ): bool {
|
||||
if ( isset( $field['translations'] ) && 'sync' === $field['translations'] ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( ! acf_is_field_type( $field['type'] ) ) {
|
||||
// Avoid error if, for example, a repeater is created in ACF Pro and used later in ACF.
|
||||
return false;
|
||||
}
|
||||
|
||||
switch ( $field['type'] ) {
|
||||
case 'clone':
|
||||
case 'group':
|
||||
case 'repeater':
|
||||
foreach ( $field['sub_fields'] as $sub_field ) {
|
||||
// A child field is synchronized or translatable. Let's synchronize the parent field.
|
||||
if ( isset( $sub_field['translations'] ) && 'translate' === $sub_field['translations'] ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( $this->can_execute( $sub_field ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'flexible_content':
|
||||
foreach ( $field['layouts'] as $layout ) {
|
||||
foreach ( $layout['sub_fields'] as $sub_field ) {
|
||||
// A child field is synchronized or translatable. Let's synchronize the parent field.
|
||||
if ( isset( $sub_field['translations'] ) && 'translate' === $sub_field['translations'] ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( $this->can_execute( $sub_field ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies subfields in a repeater or flexible content field.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param Abstract_Object $object ACF object.
|
||||
* @param array $values Custom field value of the source object.
|
||||
* @param array $field Custom field definition.
|
||||
* @param array $args {
|
||||
* Array of arguments.
|
||||
*
|
||||
* @type PLL_Language $target_language Language object of the target object.
|
||||
* @type array $original_value The value to return if the field must not be synced/copied. Basically it's
|
||||
* the field's original value.
|
||||
* }
|
||||
* @return array Custom field value of the target object.
|
||||
*/
|
||||
protected function apply_on_rows( Abstract_Object $object, array $values, array $field, array $args = array() ): array {
|
||||
if ( empty( $field['sub_fields'] ) ) {
|
||||
return $values;
|
||||
}
|
||||
|
||||
foreach ( $field['sub_fields'] as $subfield ) {
|
||||
foreach ( $values as $row => $subvalues ) {
|
||||
if ( preg_match( '/^row-(?<incr>.+)$/', (string) $row, $matches ) ) {
|
||||
// Row already exists, let's update it.
|
||||
if ( ! is_array( $subvalues ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$i = $matches['incr'];
|
||||
$parent = $this->get_field_key( $field );
|
||||
$subfield['pll_key'] = $parent . '_' . $i . '_' . $subfield['key']; // Adds an entry in `subfield` with the full path of the field.
|
||||
$values[ $row ] = $this->apply_on_subfield(
|
||||
$object,
|
||||
$subvalues,
|
||||
$subfield,
|
||||
array(
|
||||
'target_language' => $args['target_language'],
|
||||
'original_value' => $args['original_value'][ $i ] ?? null,
|
||||
)
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// New row added, let's copy it.
|
||||
$parent = $this->get_field_key( $field );
|
||||
$subfield['pll_key'] = $parent . '_' . $row . '_' . $subfield['key']; // Adds an entry in `subfield` with the full path of the field.
|
||||
$values[ $row ] = $this->copy->apply_on_subfield(
|
||||
$object,
|
||||
$subvalues,
|
||||
$subfield,
|
||||
array(
|
||||
'target_language' => $args['target_language'],
|
||||
'original_value' => null,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF;
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Copy;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Field_Settings;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Strategy\Synchronize;
|
||||
use WP_Syntex\Polylang_Pro\Integrations\ACF\Location_Language;
|
||||
|
||||
/**
|
||||
* This class is part of the ACF compatibility.
|
||||
* Manages the field translation instructions and their fields group settings.
|
||||
*
|
||||
* @since 3.7.2
|
||||
*/
|
||||
class Translation_Instructions {
|
||||
const TAB_NAME = 'pll-instructions';
|
||||
const SETTING_KEY = 'pll_display_field_instructions';
|
||||
|
||||
/**
|
||||
* Initializes the instructions and their settings.
|
||||
*
|
||||
* @since 3.7.2
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function on_acf_init() {
|
||||
add_filter( 'acf/field_group/additional_group_settings_tabs', array( $this, 'add_field_instructions_setting_tab' ) );
|
||||
add_action( 'acf/field_group/render_group_settings_tab/' . self::TAB_NAME, array( $this, 'add_field_instructions_setting' ) );
|
||||
add_filter( 'acf/pre_render_fields', array( static::class, 'append_translation_instructions' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the field instructions setting tab in fields group edit page.
|
||||
*
|
||||
* @since 3.7.2
|
||||
*
|
||||
* @param array $tabs The tabs.
|
||||
* @return array The tabs.
|
||||
*/
|
||||
public function add_field_instructions_setting_tab( $tabs ) {
|
||||
$tabs[ self::TAB_NAME ] = __( 'Translations Settings', 'polylang-pro' );
|
||||
|
||||
return $tabs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the field instructions setting in fields group edit page.
|
||||
*
|
||||
* @since 3.7.2
|
||||
*
|
||||
* @param array $field_group The field group.
|
||||
* @return void
|
||||
*/
|
||||
public function add_field_instructions_setting( $field_group ) {
|
||||
$is_legacy_translated_field_group = Field_Settings::is_legacy_translated_field_group( (int) $field_group['ID'] );
|
||||
|
||||
if ( Location_Language::has_language_location_rule( $field_group ) && ! $is_legacy_translated_field_group ) {
|
||||
$field_group[ self::SETTING_KEY ] = 0;
|
||||
|
||||
$no_translations_settings = array(
|
||||
'id' => 'no_translations_settings',
|
||||
'required' => 0,
|
||||
'label' => esc_html__( 'No translations settings', 'polylang-pro' ),
|
||||
'instructions' => esc_html__( 'No translations settings are available for field group with language location rules.', 'polylang-pro' ),
|
||||
);
|
||||
|
||||
acf_render_field_instructions( $no_translations_settings );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( $is_legacy_translated_field_group && ! isset( $field_group[ self::SETTING_KEY ] ) ) {
|
||||
$field_group[ self::SETTING_KEY ] = 1;
|
||||
}
|
||||
|
||||
acf_render_field_wrap(
|
||||
array(
|
||||
'label' => esc_html__( 'Display translation field instructions', 'polylang-pro' ),
|
||||
'instructions' => esc_html__( 'When enabled, the translation field instructions will be displayed below the field label.', 'polylang-pro' ),
|
||||
'type' => 'true_false',
|
||||
'name' => self::SETTING_KEY,
|
||||
'prefix' => 'acf_field_group',
|
||||
'value' => $field_group[ self::SETTING_KEY ] ?? 1,
|
||||
'ui' => 1,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the translation instructions to the field label using `acf/prepare_field` hook.
|
||||
* Hooked to `acf/pre_render_fields` only to ensure instructions are displayed in the editor fields metabox.
|
||||
*
|
||||
* @since 3.7
|
||||
* @since 3.7.2 Moved from Dispatcher.
|
||||
*
|
||||
* @param array $fields The fields being rendered.
|
||||
* @return array The fields.
|
||||
*/
|
||||
public static function append_translation_instructions( $fields ) {
|
||||
add_filter( 'acf/prepare_field', array( static::class, 'get_field_instructions' ) );
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instructions for the given field.
|
||||
*
|
||||
* @since 3.7
|
||||
* @since 3.7.2 Moved from Dispatcher.
|
||||
*
|
||||
* @param array|false $field The field array or false.
|
||||
* @return array|false The field array or false.
|
||||
*/
|
||||
public static function get_field_instructions( $field ) {
|
||||
if ( ! is_array( $field ) ) {
|
||||
return $field;
|
||||
}
|
||||
|
||||
$field_group = acf_get_field_group( $field['parent'] );
|
||||
if ( ! $field_group || ! isset( $field_group[ self::SETTING_KEY ] ) || ! $field_group[ self::SETTING_KEY ] ) {
|
||||
return $field;
|
||||
}
|
||||
|
||||
$instructions = '<span style="font-size: 1.2em; vertical-align: middle;" class="dashicons dashicons-translation"></span> '
|
||||
. self::get_field_instruction( $field );
|
||||
|
||||
$field['instructions'] = ! empty( $field['instructions'] ) ? $field['instructions'] . '<br>' . $instructions : $instructions;
|
||||
|
||||
return $field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instruction for the given field.
|
||||
*
|
||||
* @since 3.7
|
||||
* @since 3.7.2 Moved from Dispatcher.
|
||||
* @since 3.7.5 Changed visibility from private to public.
|
||||
*
|
||||
* @param array $field The field.
|
||||
* @return string The instruction.
|
||||
*/
|
||||
public static function get_field_instruction( array $field ): string {
|
||||
if ( empty( $field ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ( empty( $field['translations'] ) ) {
|
||||
if ( in_array( $field['type'], array( 'group', 'repeater', 'clone', 'flexible_content' ), true ) ) {
|
||||
$copy_strategy = new Copy();
|
||||
$sync_strategy = new Synchronize( $copy_strategy );
|
||||
|
||||
// Sync strategy first, otherwise the copy strategy will catch everything except `ignore`.
|
||||
if ( $sync_strategy->can_execute( $field ) ) {
|
||||
return __( 'This field is synchronized.', 'polylang-pro' );
|
||||
}
|
||||
|
||||
if ( $copy_strategy->can_execute( $field ) ) {
|
||||
return __( 'This field is copied.', 'polylang-pro' );
|
||||
}
|
||||
}
|
||||
} else {
|
||||
switch ( $field['translations'] ) {
|
||||
case 'copy_once':
|
||||
return __( 'This field is copied once.', 'polylang-pro' );
|
||||
case 'sync':
|
||||
return __( 'This field is synchronized.', 'polylang-pro' );
|
||||
case 'translate':
|
||||
return __( 'This field is translated.', 'polylang-pro' );
|
||||
case 'translate_once':
|
||||
return __( 'This field is translated once.', 'polylang-pro' );
|
||||
}
|
||||
}
|
||||
|
||||
return __( 'This field is ignored.', 'polylang-pro' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Integrations\ACF;
|
||||
|
||||
use PLL_Integrations;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
Deactivate::add_hooks();
|
||||
|
||||
add_action(
|
||||
'after_setup_theme',
|
||||
function () {
|
||||
/*
|
||||
* This must be checked only after the theme is loaded (not earlier than 'after_setup_theme') because some
|
||||
* themes include ACF.
|
||||
*/
|
||||
if ( ! Main::can_use() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! did_action( 'pll_init' ) || ! PLL()->model->has_languages() ) {
|
||||
// Run only if Polylang (and its API) is loaded, and if there is at least one language.
|
||||
return;
|
||||
}
|
||||
|
||||
PLL_Integrations::instance()->acf = new Main();
|
||||
|
||||
add_action( 'acf/init', array( PLL_Integrations::instance()->acf, 'on_acf_init' ) );
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
/**
|
||||
* Manages compatibility with Admin Columns.
|
||||
* Version tested: 3.2.3.
|
||||
*
|
||||
* @since 2.4
|
||||
*/
|
||||
class PLL_CPAC {
|
||||
|
||||
/**
|
||||
* Add filters.
|
||||
*
|
||||
* @since 2.4
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function init() {
|
||||
foreach ( PLL()->model->get_translated_post_types() as $type ) {
|
||||
if ( isset( $_REQUEST['list_screen'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
|
||||
$filter = 'manage_' . ( 'attachment' === $type ? 'upload' : 'edit-' . $type ) . '_columns';
|
||||
add_filter( $filter, array( $this, 'remove_filter_lang' ), 90 ); // Before Polylang.
|
||||
}
|
||||
|
||||
$filter = 'option_cpac_options_' . ( 'attachment' === $type ? 'wp-media' : $type ) . '__default';
|
||||
add_filter( $filter, array( $this, 'filter_default_columns' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deactivates the admin language filter on Admin Columns settings page.
|
||||
*
|
||||
* @since 2.4
|
||||
*
|
||||
* @param array $columns List of table columns.
|
||||
* @return array
|
||||
*/
|
||||
public function remove_filter_lang( $columns ) {
|
||||
PLL()->filters_columns->filter_lang = '';
|
||||
return $columns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixes the Polylang columns in default columns.
|
||||
*
|
||||
* @since 2.4
|
||||
*
|
||||
* @param array $columns List of table columns.
|
||||
* @return array
|
||||
*/
|
||||
public function filter_default_columns( $columns ) {
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( isset( $screen->base ) ) {
|
||||
$is_post_type = 'edit' === $screen->base && has_filter( 'manage_edit-' . $screen->post_type . '_columns', array( PLL()->filters_columns, 'add_post_column' ) );
|
||||
$is_media = 'upload' === $screen->base && has_filter( 'manage_upload_columns', array( PLL()->filters_columns, 'add_post_column' ) );
|
||||
|
||||
if ( $is_post_type || $is_media ) {
|
||||
foreach ( pll_languages_list() as $lang ) {
|
||||
unset( $columns[ 'language_' . $lang ] );
|
||||
}
|
||||
|
||||
$columns = PLL()->filters_columns->add_post_column( $columns );
|
||||
}
|
||||
}
|
||||
|
||||
return $columns;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
add_action(
|
||||
'after_setup_theme',
|
||||
function () {
|
||||
if ( ! defined( 'AC_FILE' ) && ! defined( 'ACP_FILE' ) ) {
|
||||
// Run only if Admin Columns is enabled.
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! did_action( 'pll_init' ) || ! PLL()->model->has_languages() ) {
|
||||
// Run only if Polylang (and its API) is loaded, and if there is at least one language.
|
||||
return;
|
||||
}
|
||||
|
||||
PLL_Integrations::instance()->cpac = new PLL_CPAC();
|
||||
|
||||
add_action( 'admin_init', array( PLL_Integrations::instance()->cpac, 'init' ) );
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
/**
|
||||
* Manages compatibility with Beaver Builder.
|
||||
*
|
||||
* @since 2.3
|
||||
*/
|
||||
class PLL_FLBuilder {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 2.3
|
||||
*/
|
||||
public function __construct() {
|
||||
add_filter( 'pll_copy_post_metas', array( $this, 'fl_builder_copy_post_metas' ), 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow to copy Beaver Builder data when creating a translation.
|
||||
*
|
||||
* @since 1.9.1
|
||||
*
|
||||
* @param array $metas List of custom fields names.
|
||||
* @param bool $sync True if it is synchronization, false if it is a copy.
|
||||
* @return array
|
||||
*/
|
||||
public function fl_builder_copy_post_metas( $metas, $sync ) {
|
||||
$bb_metas = array(
|
||||
'_fl_builder_draft',
|
||||
'_fl_builder_draft_settings',
|
||||
'_fl_builder_data',
|
||||
'_fl_builder_data_settings',
|
||||
'_fl_builder_enabled',
|
||||
);
|
||||
|
||||
return $sync ? $metas : array_merge( $metas, $bb_metas );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
add_action(
|
||||
'pll_init',
|
||||
function ( $polylang ) {
|
||||
if ( ! class_exists( 'FLBuilderLoader' ) ) {
|
||||
// Run only if Beaver Builder is enabled.
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $polylang->model->has_languages() ) {
|
||||
// Run only if there is at least one language.
|
||||
return;
|
||||
}
|
||||
|
||||
PLL_Integrations::instance()->flbuilder = new PLL_FLBuilder();
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
/**
|
||||
* A class to manage the integration with Content Blocks (Custom Post Widget).
|
||||
* Version tested: 3.0.4.
|
||||
*
|
||||
* @since 2.6
|
||||
*/
|
||||
class PLL_Content_Blocks {
|
||||
|
||||
/**
|
||||
* Initializes filters and actions.
|
||||
*
|
||||
* @since 2.6
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function init() {
|
||||
add_filter( 'pll_get_post_types', array( $this, 'get_post_types' ), 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the Content Blocks post type to the list of translatable post types.
|
||||
*
|
||||
* @since 2.6
|
||||
*
|
||||
* @param string[] $post_types List of post types.
|
||||
* @param bool $is_settings True when displaying the list of custom post types in Polylang settings.
|
||||
* @return string[]
|
||||
*/
|
||||
public function get_post_types( $post_types, $is_settings ) {
|
||||
if ( ! $is_settings ) {
|
||||
$post_types['content_block'] = 'content_block';
|
||||
}
|
||||
return $post_types;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
add_action(
|
||||
'pll_init',
|
||||
function () {
|
||||
if ( ! function_exists( 'custom_post_widget_plugin_init' ) ) {
|
||||
// Run only if Content Blocks is enabled.
|
||||
return;
|
||||
}
|
||||
|
||||
PLL_Integrations::instance()->content_blocks = new PLL_Content_Blocks();
|
||||
PLL_Integrations::instance()->content_blocks->init();
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
/**
|
||||
* Manages compatibility with Custom Post Type UI.
|
||||
* Version tested: 1.5.4.
|
||||
*
|
||||
* @since 2.1
|
||||
*/
|
||||
class PLL_CPTUI {
|
||||
|
||||
/**
|
||||
* Initializes filters and actions.
|
||||
*
|
||||
* @since 2.1
|
||||
*
|
||||
* @param PLL_Settings|PLL_Admin|PLL_REST_Request|PLL_Frontend $polylang The main Polylang object.
|
||||
* @return void
|
||||
*/
|
||||
public function init( $polylang ) {
|
||||
// Add CPT UI post types and taxonomies to Polylang settings.
|
||||
add_filter( 'pll_get_post_types', array( $this, 'pll_get_types' ), 10, 2 );
|
||||
add_filter( 'pll_get_taxonomies', array( $this, 'pll_get_types' ), 10, 2 );
|
||||
|
||||
if ( ! $polylang->model->has_languages() ) {
|
||||
// Run only if there is at least one language.
|
||||
return;
|
||||
}
|
||||
|
||||
$keys = array(
|
||||
'*' => array(
|
||||
'label' => 1,
|
||||
'singular_label' => 1,
|
||||
'description' => 1,
|
||||
'labels' => array(
|
||||
'*' => 1,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
new PLL_Translate_Option( 'cptui_post_types', $keys, array( 'context' => 'CPT UI' ) );
|
||||
new PLL_Translate_Option( 'cptui_taxonomies', $keys, array( 'context' => 'CPT UI' ) );
|
||||
|
||||
if ( $polylang instanceof PLL_Frontend && ! $polylang->options['force_lang'] ) {
|
||||
// Special case when the language is set from the content as CPT and taxonomies are registered before the language is defined.
|
||||
add_action( 'pll_language_defined', array( $this, 'pll_language_defined' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates custom post types and taxonomies labels when the language is set from the content.
|
||||
*
|
||||
* @since 2.1
|
||||
*
|
||||
* @param array $types Array of registered post types or taxonomies.
|
||||
* @param array $cptui_types Array of CPT UI post types or taxonomies.
|
||||
*/
|
||||
public function translate_registered_types( $types, $cptui_types ) {
|
||||
foreach ( $types as $name => $type ) {
|
||||
if ( ! in_array( $name, $cptui_types, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$type->label = pll__( $type->label );
|
||||
$type->description = pll__( $type->description );
|
||||
|
||||
foreach ( array_keys( get_object_vars( $type->labels ) ) as $key ) {
|
||||
$type->labels->$key = pll__( $type->labels->$key );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates custom post types and taxonomies labels when the language is set from the content.
|
||||
*
|
||||
* @since 2.1
|
||||
*/
|
||||
public function pll_language_defined() {
|
||||
$this->translate_registered_types( $GLOBALS['wp_post_types'], array_keys( get_option( 'cptui_post_types', array() ) ) );
|
||||
$this->translate_registered_types( $GLOBALS['wp_taxonomies'], array_keys( get_option( 'cptui_taxonomies', array() ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add CPT UI post types and taxonomies to Polylang settings.
|
||||
*
|
||||
* @since 2.1
|
||||
*
|
||||
* @param string[] $types List of post type or taxonomy names.
|
||||
* @param bool $is_settings True when displaying the list in Polylang settings.
|
||||
* @return string[]
|
||||
*/
|
||||
public function pll_get_types( $types, $is_settings ) {
|
||||
if ( $is_settings ) {
|
||||
$type = substr( current_filter(), 8 );
|
||||
$cptui_types = get_option( "cptui_{$type}" );
|
||||
|
||||
if ( is_array( $cptui_types ) ) {
|
||||
$types = array_merge( $types, array_keys( $cptui_types ) );
|
||||
}
|
||||
}
|
||||
return $types;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
add_action(
|
||||
'pll_init',
|
||||
function ( $polylang ) {
|
||||
if ( ! defined( 'CPTUI_VERSION' ) ) {
|
||||
// Run only if Custom Post Type UI is enabled.
|
||||
return;
|
||||
}
|
||||
|
||||
PLL_Integrations::instance()->cptui = new PLL_CPTUI();
|
||||
PLL_Integrations::instance()->cptui->init( $polylang );
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
/**
|
||||
* Manages compatibility with the Divi Builder.
|
||||
*
|
||||
* @since 2.3
|
||||
*/
|
||||
class PLL_Divi_Builder {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 2.3
|
||||
*/
|
||||
public function __construct() {
|
||||
add_filter( 'pll_copy_post_metas', array( $this, 'divi_builder_copy_post_metas' ), 10, 2 );
|
||||
add_filter( 'use_block_editor_for_post', array( $this, 'persist_draft_in_database' ), 4000 ); // After `PLL_Duplicate_Action::new_post_translation()`.
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow to copy Divi Builder data when creating a translation.
|
||||
*
|
||||
* @since 2.1
|
||||
*
|
||||
* @param array $metas List of custom fields names.
|
||||
* @param bool $sync True if it is synchronization, false if it is a copy.
|
||||
* @return array
|
||||
*/
|
||||
public function divi_builder_copy_post_metas( $metas, $sync ) {
|
||||
$divi_metas = array(
|
||||
'_et_pb_post_hide_nav',
|
||||
'_et_pb_page_layout',
|
||||
'_et_pb_side_nav',
|
||||
'_et_pb_use_builder',
|
||||
'_et_pb_ab_bounce_rate_limit',
|
||||
'_et_pb_ab_stats_refresh_interval',
|
||||
'_et_pb_old_content',
|
||||
'_et_pb_enable_shortcode_tracking',
|
||||
'_et_pb_custom_css',
|
||||
'_et_pb_light_text_color',
|
||||
'_et_pb_dark_text_color',
|
||||
'_et_pb_content_area_background_color',
|
||||
'_et_pb_section_background_color',
|
||||
);
|
||||
|
||||
return $sync ? $metas : array_merge( $metas, $divi_metas );
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists the draft in the database to allow duplication in Divi Builder.
|
||||
*
|
||||
* @since 3.7.5
|
||||
*
|
||||
* @global WP_Post $post The current post object.
|
||||
*
|
||||
* @param bool $is_block_editor Whether the post can be edited or not with the block editor.
|
||||
* @return bool
|
||||
*/
|
||||
public function persist_draft_in_database( $is_block_editor ) {
|
||||
global $post;
|
||||
|
||||
if ( empty( $post ) ) {
|
||||
return $is_block_editor;
|
||||
}
|
||||
|
||||
if ( ( new PLL_Toggle_User_Meta( PLL_Duplicate_Action::META_NAME ) )->is_active() ) {
|
||||
wp_update_post( $post );
|
||||
}
|
||||
|
||||
return $is_block_editor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
add_action(
|
||||
'pll_init',
|
||||
function ( $polylang ) {
|
||||
if ( 'Divi' !== get_template() && ! defined( 'ET_BUILDER_PLUGIN_VERSION' ) ) {
|
||||
// Run only if Divi Builder is enabled.
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! $polylang->model->has_languages() ) {
|
||||
// Run only if there is at least one language.
|
||||
return;
|
||||
}
|
||||
|
||||
PLL_Integrations::instance()->divi_builder = new PLL_Divi_Builder();
|
||||
}
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
add_action(
|
||||
'pll_init',
|
||||
function ( $polylang ) {
|
||||
if ( ! defined( 'TRIBE_EVENTS_FILE' ) ) {
|
||||
// Run only if The Event Calendar is enabled.
|
||||
return;
|
||||
}
|
||||
|
||||
PLL_Integrations::instance()->tec = new PLL_TEC();
|
||||
PLL_Integrations::instance()->tec->init( $polylang );
|
||||
}
|
||||
);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
/**
|
||||
* /!\ DO NOT DIRECTLY EDIT THIS FILE, THIS FILE IS AUTO-GENERATED AS PART OF THE BUILD PROCESS.
|
||||
*/
|
||||
|
||||
return array(
|
||||
'ACF',
|
||||
'admin-columns',
|
||||
'beaver-builder',
|
||||
'content-blocks',
|
||||
'cptui',
|
||||
'divi',
|
||||
'events-calendar',
|
||||
);
|
||||
@@ -0,0 +1,478 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\CLI\Command;
|
||||
|
||||
use WP_CLI;
|
||||
use WP_CLI\Utils;
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang\Model\Languages;
|
||||
use WP_Syntex\Polylang_Pro\Modules\CLI\Formatter;
|
||||
|
||||
/**
|
||||
* Manages languages.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @phpstan-import-type LanguageData from PLL_Language
|
||||
*/
|
||||
class Language {
|
||||
|
||||
/**
|
||||
* Languages model.
|
||||
*
|
||||
* @var Languages
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param Languages $model The languages model.
|
||||
*/
|
||||
public function __construct( Languages $model ) {
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a language.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <locale>
|
||||
* : WordPress locale or custom locale. If the locale is not found in the core languages list, it will be created but the name, slug, flag and direction will be mandatory.
|
||||
*
|
||||
* [--name=<name>]
|
||||
* : Language name (used only for display). If not provided, will fallback to Polylang core languages list.
|
||||
*
|
||||
* [--slug=<slug>]
|
||||
* : Language slug (ideally 2-letters ISO 639-1 language code). Must be unique. If not provided, will fallback to Polylang core languages list.
|
||||
*
|
||||
* [--flag=<flag>]
|
||||
* : Country code for the flag. If not provided, will fallback to Polylang core languages list.
|
||||
*
|
||||
* [--dir=<dir>]
|
||||
* : Text direction for the language.
|
||||
* ---
|
||||
* default: ltr
|
||||
* options:
|
||||
* - ltr
|
||||
* - rtl
|
||||
* ---
|
||||
*
|
||||
* [--order=<order>]
|
||||
* : Language order when displayed.
|
||||
* ---
|
||||
* default: 0
|
||||
* ---
|
||||
*
|
||||
* [--skip-default-cat]
|
||||
* : If set, no default category will be created for this language.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Create a language using locale only (fallback to core languages list)
|
||||
* wp pll language create en_US
|
||||
*
|
||||
* # Create a language with custom name and slug
|
||||
* wp pll language create en_US --name="English" --slug=en
|
||||
*
|
||||
* # Create a French language with custom flag
|
||||
* wp pll language create fr_FR --name="Français" --slug=fr --flag=fr --order=1
|
||||
*
|
||||
* # Create an Arabic language with RTL support
|
||||
* wp pll language create ar --dir=rtl --order=2
|
||||
*
|
||||
* # Create a language without default category
|
||||
* wp pll language create es_ES --name="Español" --slug=es --skip-default-cat
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
* @param string[] $assoc_args The command associative arguments.
|
||||
* @phpstan-param array{name?: string, slug?: string, flag?: string, dir?: string, order?: string, skip-default-cat?: bool} $assoc_args
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function create( $args, $assoc_args ): void {
|
||||
list( $locale ) = $args;
|
||||
|
||||
$language_args = $this->prepare_language_args( $assoc_args );
|
||||
$language_args['locale'] = $locale;
|
||||
|
||||
$language = $this->model->add( $language_args );
|
||||
|
||||
if ( is_wp_error( $language ) ) {
|
||||
WP_CLI::error( $language->get_error_message() );
|
||||
}
|
||||
|
||||
/** @var PLL_Language $language */
|
||||
WP_CLI::success( sprintf( 'Language "%1$s" (%2$s) created successfully.', $language->name, $language->slug ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a language.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <id-or-slug>
|
||||
* : The ID or slug of the language to update. Must be unique among all languages.
|
||||
*
|
||||
* [--name=<name>]
|
||||
* : Language name (used only for display).
|
||||
*
|
||||
* [--locale=<locale>]
|
||||
* : WordPress locale. If something wrong is used for the locale, the .mo files will not be loaded.
|
||||
*
|
||||
* [--slug=<slug>]
|
||||
* : New language slug (ideally 2-letters ISO 639-1 language code). Must be unique among all languages.
|
||||
*
|
||||
* [--dir=<dir>]
|
||||
* : Text direction for the language.
|
||||
* ---
|
||||
* options:
|
||||
* - ltr
|
||||
* - rtl
|
||||
* ---
|
||||
*
|
||||
* [--order=<order>]
|
||||
* : Language order when displayed.
|
||||
*
|
||||
* [--flag=<flag>]
|
||||
* : Country code for the flag.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Update language name only
|
||||
* wp pll language update en --name="English (US)"
|
||||
*
|
||||
* # Update multiple properties
|
||||
* wp pll language update fr --name="Français" --locale=fr_FR --flag=fr --order=1
|
||||
*
|
||||
* # Change language slug
|
||||
* wp pll language update en --new-slug=en_us
|
||||
*
|
||||
* # Update text direction
|
||||
* wp pll language update ar --dir=rtl
|
||||
*
|
||||
* # Update language order
|
||||
* wp pll language update es --order=3
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
* @param string[] $assoc_args The command associative arguments.
|
||||
* @phpstan-param array{name?: string, locale?: string, new-slug?: string, dir?: string, order?: string, flag?: string} $assoc_args
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function update( $args, $assoc_args ): void {
|
||||
list( $id_or_slug ) = $args;
|
||||
|
||||
$language = $this->model->get( $id_or_slug );
|
||||
|
||||
if ( empty( $language ) ) {
|
||||
WP_CLI::error( 'Language not found.' );
|
||||
}
|
||||
|
||||
/** @var PLL_Language $language */
|
||||
$update_args = $this->prepare_language_args( $assoc_args, $language );
|
||||
|
||||
$language = $this->model->update( $update_args );
|
||||
|
||||
if ( is_wp_error( $language ) ) {
|
||||
WP_CLI::error( $language->get_error_message() );
|
||||
}
|
||||
|
||||
/** @var PLL_Language $language */
|
||||
WP_CLI::success( sprintf( 'Language "%1$s" (%2$s) updated successfully.', $language->name, $language->slug ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a language.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <id-or-slug>
|
||||
* : The ID or slug of the language to delete.
|
||||
*
|
||||
* [--yes]
|
||||
* : Answer yes to the confirmation message.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Delete English language
|
||||
* wp pll language delete en
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
* @param string[] $assoc_args The command associative arguments.
|
||||
* @phpstan-param array{yes?: bool} $assoc_args
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function delete( $args, $assoc_args ): void {
|
||||
list( $id_or_slug ) = $args;
|
||||
|
||||
$language = $this->model->get( $id_or_slug );
|
||||
|
||||
if ( empty( $language ) ) {
|
||||
WP_CLI::error( 'Language not found.' );
|
||||
}
|
||||
|
||||
/** @var PLL_Language $language */
|
||||
WP_CLI::confirm(
|
||||
sprintf( 'Are you sure you want to delete the language "%1$s" (%2$s)?', $language->name, $language->slug ),
|
||||
$assoc_args
|
||||
);
|
||||
|
||||
$result = $this->model->delete( $language->term_id );
|
||||
|
||||
if ( ! $result ) {
|
||||
WP_CLI::error( sprintf( 'Failed to delete the language "%1$s" (%2$s).', $language->name, $language->slug ) );
|
||||
}
|
||||
|
||||
WP_CLI::success( sprintf( 'Language "%1$s" (%2$s) deleted successfully.', $language->name, $language->slug ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists languages.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* [--<field>=<value>]
|
||||
* : Filter by one or more fields.
|
||||
*
|
||||
* [--format=<format>]
|
||||
* : Render output in a particular format.
|
||||
* ---
|
||||
* default: table
|
||||
* options:
|
||||
* - table
|
||||
* - json
|
||||
* - yaml
|
||||
* - csv
|
||||
* ---
|
||||
*
|
||||
* [--field=<field>]
|
||||
* : Prints the value of a single field for each language.
|
||||
*
|
||||
* [--fields=<fields>]
|
||||
* : Comma-separated list of fields to display. Available fields are PLL_Language object properties.
|
||||
*
|
||||
* ## AVAILABLE FIELDS
|
||||
*
|
||||
* These fields will be displayed by default for each term:
|
||||
*
|
||||
* * name
|
||||
* * slug
|
||||
* * locale
|
||||
* * term_id
|
||||
* * order (term_group)
|
||||
* * direction (dir)
|
||||
* * active
|
||||
* * default
|
||||
*
|
||||
* These fields are optionally available:
|
||||
*
|
||||
* * w3c
|
||||
* * facebook
|
||||
* * host
|
||||
* * page_on_front
|
||||
* * page_for_posts
|
||||
* * flag_code
|
||||
* * fallbacks
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # List all languages
|
||||
* wp pll language list
|
||||
*
|
||||
* # List specific languages by slugs
|
||||
* wp pll language list --slug=en,fr,es
|
||||
*
|
||||
* # List languages with specific output fields only
|
||||
* wp pll language list --fields=name,slug,locale
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
* @param string[] $assoc_args The command associative arguments.
|
||||
* @phpstan-param array{field?: string, fields?: string, format?: string} $assoc_args
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function list( $args, $assoc_args ): void {
|
||||
$languages = $this->model->get_list();
|
||||
|
||||
$filters = $assoc_args;
|
||||
unset( $filters['fields'] );
|
||||
unset( $filters['format'] );
|
||||
unset( $filters['field'] );
|
||||
|
||||
if ( ! empty( $filters ) ) {
|
||||
foreach ( $filters as $field => $filter_values ) {
|
||||
if ( ! property_exists( PLL_Language::class, (string) $field ) ) {
|
||||
WP_CLI::warning( sprintf( 'Invalid filter: %s.', $field ) );
|
||||
continue;
|
||||
}
|
||||
|
||||
$filter_values = array_map( 'trim', explode( ',', (string) $filter_values ) );
|
||||
$languages = array_filter(
|
||||
$languages,
|
||||
function ( $language ) use ( $field, $filter_values ) {
|
||||
// Shallower comparison on purpose, to avoid numeric string issues.
|
||||
return in_array( $language->$field, $filter_values ); // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$this->get_formatter( $assoc_args )->display_items( $this->normalize_languages( $languages ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a language.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <id-or-slug>
|
||||
* : The ID or slug of the language to get.
|
||||
*
|
||||
* [--format=<format>]
|
||||
* : Render output in a particular format.
|
||||
* ---
|
||||
* default: table
|
||||
* options:
|
||||
* - table
|
||||
* - json
|
||||
* - yaml
|
||||
* - csv
|
||||
* ---
|
||||
*
|
||||
* [--field=<field>]
|
||||
* : Prints the value of a single field for each language.
|
||||
*
|
||||
* [--fields=<fields>]
|
||||
* : Comma-separated list of fields to display. Available fields are PLL_Language object properties.
|
||||
*
|
||||
* ## AVAILABLE FIELDS
|
||||
*
|
||||
* These fields will be displayed by default for each term:
|
||||
*
|
||||
* * name
|
||||
* * slug
|
||||
* * locale
|
||||
* * term_id
|
||||
* * order (term_group)
|
||||
* * direction (dir)
|
||||
* * active
|
||||
* * default
|
||||
*
|
||||
* These fields are optionally available:
|
||||
*
|
||||
* * w3c
|
||||
* * facebook
|
||||
* * host
|
||||
* * page_on_front
|
||||
* * page_for_posts
|
||||
* * flag_code
|
||||
* * fallbacks
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Get a language by slug
|
||||
* wp pll language get en
|
||||
*
|
||||
* # Get a language by ID
|
||||
* wp pll language get 1
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
* @param string[] $assoc_args The command associative arguments.
|
||||
* @phpstan-param array{field?: string, fields?: string, format?: string} $assoc_args
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function get( $args, $assoc_args ): void {
|
||||
if ( is_numeric( $args[0] ) ) {
|
||||
$assoc_args['term_id'] = $args[0];
|
||||
} else {
|
||||
$assoc_args['slug'] = $args[0];
|
||||
}
|
||||
$this->list( array(), $assoc_args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of normalized arrays from `PLL_Language` objects.
|
||||
* Maps the `PLL_Language` object properties to the command output fields.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Language[] $languages The language objects.
|
||||
* @return array<string, mixed> The normalized array.
|
||||
*/
|
||||
private function normalize_languages( array $languages ) {
|
||||
foreach ( $languages as &$language ) {
|
||||
$language = $language->to_array();
|
||||
|
||||
$language['order'] = $language['term_group'];
|
||||
$language['direction'] = $language['is_rtl'] ? 'rtl' : 'ltr';
|
||||
$language['default'] = $language['is_default'];
|
||||
unset( $language['term_group'], $language['is_rtl'], $language['is_default'] );
|
||||
}
|
||||
|
||||
return $languages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a formatter instance.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $assoc_args The command associative arguments.
|
||||
* @return Formatter The formatter instance.
|
||||
*/
|
||||
private function get_formatter( array $assoc_args ) {
|
||||
return new Formatter(
|
||||
$assoc_args,
|
||||
array(
|
||||
'name',
|
||||
'slug',
|
||||
'locale',
|
||||
'term_id',
|
||||
'order',
|
||||
'direction',
|
||||
'active',
|
||||
'default',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the language arguments.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array<string, bool|string> $assoc_args The command associative arguments.
|
||||
* @param PLL_Language $language The language object.
|
||||
*
|
||||
* @return array<string, mixed> The prepared language arguments.
|
||||
*
|
||||
* @phpstan-return array{lang_id: int, name: string, locale: string, slug: string, rtl: bool, term_group: int, flag: string}
|
||||
*/
|
||||
private function prepare_language_args( array $assoc_args, ?PLL_Language $language = null ): array {
|
||||
/** @var array{lang_id: int, name: string, locale: string, slug: string, rtl: bool, term_group: int, flag: string} */
|
||||
$parsed_args = array(
|
||||
'lang_id' => $language ? $language->get_tax_prop( 'language', 'term_id' ) : null,
|
||||
'name' => Utils\get_flag_value( $assoc_args, 'name', $language ? $language->name : null ),
|
||||
'locale' => Utils\get_flag_value( $assoc_args, 'locale', $language ? $language->locale : null ),
|
||||
'slug' => Utils\get_flag_value( $assoc_args, 'slug', $language ? $language->slug : null ),
|
||||
'rtl' => 'rtl' === Utils\get_flag_value( $assoc_args, 'dir', $language ? ( $language->is_rtl ? 'rtl' : 'ltr' ) : null ),
|
||||
'term_group' => (int) Utils\get_flag_value( $assoc_args, 'order', $language ? $language->term_group : null ), // @phpstan-ignore cast.int
|
||||
'flag' => Utils\get_flag_value( $assoc_args, 'flag', $language ? $language->flag_code : null ),
|
||||
);
|
||||
|
||||
if ( Utils\get_flag_value( $assoc_args, 'skip-default-cat' ) ) {
|
||||
$parsed_args['no_default_cat'] = true;
|
||||
}
|
||||
|
||||
return $parsed_args;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\CLI\Command;
|
||||
|
||||
use WP_CLI;
|
||||
use WP_CLI\Utils;
|
||||
use WP_Syntex\Polylang\Options\Options;
|
||||
use WP_Syntex\Polylang_Pro\Modules\CLI\Formatter;
|
||||
|
||||
/**
|
||||
* Manages Polylang settings.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Setting {
|
||||
/**
|
||||
* Error mode constant for exiting the script.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const ERROR_MODE_EXIT = 'error';
|
||||
|
||||
/**
|
||||
* Error mode constant for non-exiting errors.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const ERROR_MODE_WARNING = 'warning';
|
||||
|
||||
/**
|
||||
* Options instance.
|
||||
*
|
||||
* @var Options
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Adapter instance.
|
||||
*
|
||||
* @var Setting_Adapter
|
||||
*/
|
||||
private $adapter;
|
||||
|
||||
/**
|
||||
* List of settings keys that are not supported yet.
|
||||
* Typically, these are settings that are nested objects.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $unsupported = array(
|
||||
'nav_menus',
|
||||
'machine_translation_services',
|
||||
);
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param Options $options Options instance.
|
||||
*/
|
||||
public function __construct( Options $options ) {
|
||||
$this->options = $options;
|
||||
$this->adapter = new Setting_Adapter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a scalar Polylang setting.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <key>
|
||||
* : The key of the setting to set.
|
||||
*
|
||||
* <value>
|
||||
* : The value of the setting to set.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Activate media translation setting
|
||||
* wp pll setting set media_support true
|
||||
*
|
||||
* # Activate media duplication setting
|
||||
* wp pll setting set media_duplicate true
|
||||
*
|
||||
* # Set domains using JSON
|
||||
* wp pll setting set domains '{"fr":"example.fr"}'
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function set( $args ): void {
|
||||
list( $input_key, $input_value ) = $args;
|
||||
list( $key, $value ) = $this->adapter->get_args( $args );
|
||||
|
||||
$this->is_supported( $key, self::ERROR_MODE_EXIT );
|
||||
$this->is_mutable( $key, self::ERROR_MODE_EXIT );
|
||||
|
||||
$decoded_value = Utils\is_json( $value ) ? json_decode( $value, true ) : $value;
|
||||
if ( ! $this->is_scalar( $key ) && ! is_array( $decoded_value ) ) {
|
||||
WP_CLI::error( sprintf( 'Setting "%s" is not a scalar. Use a JSON string for list or map settings instead.', $key ) );
|
||||
}
|
||||
|
||||
$property = $this->options->get_schema()['properties'][ $key ];
|
||||
|
||||
if ( null === $decoded_value ) {
|
||||
WP_CLI::error( sprintf( 'Invalid value "%1$s" for type "%2$s".', $value, $property['type'] ) );
|
||||
}
|
||||
|
||||
$errors = $this->options->set( $key, $decoded_value );
|
||||
|
||||
if ( $errors->has_errors() ) {
|
||||
WP_CLI::error( $errors->get_error_message() );
|
||||
}
|
||||
|
||||
$this->save( self::ERROR_MODE_EXIT );
|
||||
|
||||
WP_CLI::success( sprintf( 'Setting "%1$s" set to "%2$s".', $input_key, $input_value ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns one or more Polylang setting(s) if given key(s), or lists all settings if no key is provided.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* [--keys=<keys>]
|
||||
* : Comma-separated list of keys to get. Default is all.
|
||||
* ---
|
||||
* default: all
|
||||
* ---
|
||||
*
|
||||
* [--format=<format>]
|
||||
* : Render output in a particular format.
|
||||
* ---
|
||||
* default: table
|
||||
* options:
|
||||
* - table
|
||||
* - json
|
||||
* - yaml
|
||||
* - csv
|
||||
* ---
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Get specific settings
|
||||
* wp pll setting get --keys=media_support,force_lang
|
||||
*
|
||||
* # List all settings
|
||||
* wp pll setting get
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
* @param string[] $assoc_args The command associative arguments.
|
||||
* @phpstan-param array{keys?: string, format?: string} $assoc_args
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function get( $args, $assoc_args ): void {
|
||||
$assoc_args = $this->adapter->get_assoc_args( $assoc_args );
|
||||
$settings = $this->options->get_all();
|
||||
$schema = $this->options->get_schema();
|
||||
/** @var string $keys_filter */
|
||||
$keys_filter = Utils\get_flag_value( $assoc_args, 'keys', 'all' );
|
||||
|
||||
if ( 'all' !== $keys_filter ) {
|
||||
$requested_keys = array_map( 'trim', explode( ',', $keys_filter ) );
|
||||
$filtered_settings = array();
|
||||
|
||||
foreach ( $requested_keys as $key ) {
|
||||
if ( ! $this->is_supported( $key, self::ERROR_MODE_WARNING ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filtered_settings[ $key ] = $settings[ $key ];
|
||||
}
|
||||
|
||||
$settings = $filtered_settings;
|
||||
} else {
|
||||
foreach ( $this->unsupported as $unsupported_key ) {
|
||||
unset( $settings[ $unsupported_key ] );
|
||||
}
|
||||
}
|
||||
|
||||
if ( empty( $settings ) ) {
|
||||
WP_CLI::warning( 'No settings found.' );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->get_formatter( $assoc_args )->display_items( $this->normalize_settings( $settings, $schema['properties'] ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a value to a list type Polylang setting.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <key>
|
||||
* : The key of the setting to add a value to.
|
||||
*
|
||||
* <value>
|
||||
* : The value to add to the setting. For map type settings, this is the subkey to add a value to.
|
||||
*
|
||||
* [<subvalue>]
|
||||
* : The subvalue to add to the setting. For map type settings, this is the value of the subkey. Not applicable for list type settings.
|
||||
* ---
|
||||
* default: ''
|
||||
* ---
|
||||
*
|
||||
* [--yes]
|
||||
* : Answer yes to the confirmation message.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Add a custom post type to the list of translatable post types
|
||||
* wp pll setting add post_types custom_post_type
|
||||
*
|
||||
* # Add an English domain to the map of domains
|
||||
* wp pll setting add domains en example.com
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
* @param string[] $assoc_args The command associative arguments.
|
||||
* @phpstan-param array{yes?: bool} $assoc_args
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function add( $args, $assoc_args ): void {
|
||||
list( $key, $value ) = $args;
|
||||
$subvalue = $args[2] ?? '';
|
||||
|
||||
$this->is_supported( $key, self::ERROR_MODE_EXIT );
|
||||
|
||||
$this->is_mutable( $key, self::ERROR_MODE_EXIT );
|
||||
|
||||
$this->is_array_like( $key, self::ERROR_MODE_EXIT );
|
||||
|
||||
if ( $this->is_list( $key ) ) {
|
||||
$success_message = sprintf( 'Value "%1$s" added to setting "%2$s".', $value, $key );
|
||||
|
||||
$errors = $this->options->add( $key, $value );
|
||||
|
||||
WP_CLI::log( $errors->get_error_message() );
|
||||
} else {
|
||||
if ( '' === $subvalue ) {
|
||||
WP_CLI::error( sprintf( 'Subvalue is required for map type setting "%s".', $key ) );
|
||||
}
|
||||
|
||||
/** @var array $prev_map */
|
||||
$prev_map = $this->options->get( $key );
|
||||
if ( isset( $prev_map[ $value ] ) ) {
|
||||
WP_CLI::confirm(
|
||||
sprintf( 'Key "%1$s" already exists in setting "%2$s". Do you want to override it?', $value, $key ),
|
||||
$assoc_args
|
||||
);
|
||||
}
|
||||
|
||||
$success_message = sprintf( 'Key "%1$s" with value "%2$s" added to setting "%3$s".', $value, $subvalue, $key );
|
||||
|
||||
$errors = $this->options->add( $key, array( $value => $subvalue ) );
|
||||
}
|
||||
|
||||
if ( $errors->has_errors() ) {
|
||||
WP_CLI::error( $errors->get_error_message() );
|
||||
}
|
||||
|
||||
$this->save( self::ERROR_MODE_EXIT );
|
||||
|
||||
WP_CLI::success( $success_message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a value from a list type Polylang setting.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* <key>
|
||||
* : The key of the setting to remove a value from.
|
||||
*
|
||||
* <value>
|
||||
* : The value to remove from the setting. For map type settings, this is the subkey to remove a value from.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Remove a custom post type from the list of translatable post types
|
||||
* wp pll setting remove post_types custom_post_type
|
||||
*
|
||||
* # Remove an English domain from the map of domains
|
||||
* wp pll setting remove domains en
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function remove( $args ): void {
|
||||
list( $key, $value ) = $args;
|
||||
|
||||
$this->is_supported( $key, self::ERROR_MODE_EXIT );
|
||||
|
||||
$this->is_mutable( $key, self::ERROR_MODE_EXIT );
|
||||
|
||||
$this->is_array_like( $key, self::ERROR_MODE_EXIT );
|
||||
|
||||
/** @var array $current_value Array like options. */
|
||||
$current_value = $this->options->get( $key );
|
||||
|
||||
if ( $this->is_list( $key ) ) {
|
||||
if ( ! in_array( $value, $current_value, true ) ) {
|
||||
WP_CLI::error( sprintf( 'Value "%1$s" does not exist in setting "%2$s".', $value, $key ) );
|
||||
}
|
||||
|
||||
$success_message = sprintf( 'Value "%1$s" removed from setting "%2$s".', $value, $key );
|
||||
} else {
|
||||
if ( ! isset( $current_value[ $value ] ) ) {
|
||||
WP_CLI::error( sprintf( 'Key "%1$s" does not exist in setting "%2$s".', $value, $key ) );
|
||||
}
|
||||
|
||||
$success_message = sprintf( 'Key "%1$s" removed from setting "%2$s".', $value, $key );
|
||||
}
|
||||
|
||||
$errors = $this->options->remove( $key, $value );
|
||||
if ( $errors->has_errors() ) {
|
||||
WP_CLI::error( $errors->get_error_message() );
|
||||
}
|
||||
|
||||
$this->save( self::ERROR_MODE_EXIT );
|
||||
|
||||
WP_CLI::success( $success_message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets a Polylang setting to its default value, or all settings if no key is provided.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* [--keys=<keys>]
|
||||
* : Comma-separated list of keys to reset. If not provided, all settings will be reset.
|
||||
*
|
||||
* [--yes]
|
||||
* : Answer yes to the confirmation message.
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Reset specific settings
|
||||
* wp pll setting reset --keys=media_support,force_lang
|
||||
*
|
||||
* # Reset all settings
|
||||
* wp pll setting reset
|
||||
*
|
||||
* @param string[] $args The command arguments.
|
||||
* @param string[] $assoc_args The command associative arguments.
|
||||
* @phpstan-param array{keys?: string, yes?: bool} $assoc_args
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
public function reset( $args, $assoc_args ): void {
|
||||
$assoc_args = $this->adapter->get_assoc_args( $assoc_args );
|
||||
/** @var string $keys_filter */
|
||||
$keys_filter = Utils\get_flag_value( $assoc_args, 'keys' );
|
||||
$current_settings = $this->options->get_all();
|
||||
|
||||
if ( $keys_filter ) {
|
||||
$keys_to_reset = array_map( 'trim', explode( ',', $keys_filter ) );
|
||||
|
||||
foreach ( $keys_to_reset as $key ) {
|
||||
if ( ! $this->is_supported( $key, self::ERROR_MODE_WARNING ) || ! $this->is_mutable( $key, self::ERROR_MODE_WARNING ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->options->reset( $key );
|
||||
}
|
||||
|
||||
$this->save( self::ERROR_MODE_EXIT );
|
||||
|
||||
WP_CLI::success( sprintf( 'Settings "%s" reset to default values.', $keys_filter ) );
|
||||
} else {
|
||||
WP_CLI::confirm(
|
||||
'Are you sure you want to reset all Polylang settings to their default values?',
|
||||
$assoc_args
|
||||
);
|
||||
|
||||
foreach ( $current_settings as $key => $value ) {
|
||||
if ( $this->is_read_only( $key ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->options->reset( $key );
|
||||
}
|
||||
|
||||
$this->save( self::ERROR_MODE_EXIT );
|
||||
|
||||
WP_CLI::success( 'All Polylang settings reset to default values.' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves options or exits with error if save fails.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $error_mode The error mode. Use `ERROR_MODE_EXIT` or `ERROR_MODE_WARNING` constants.
|
||||
* @return bool|never True if the settings were saved successfully, false otherwise. Never returns if $error_mode is `ERROR_MODE_EXIT`.
|
||||
*/
|
||||
private function save( string $error_mode ): bool {
|
||||
$result = $this->options->save();
|
||||
|
||||
return $result || WP_CLI::$error_mode( 'Failed to save the settings.' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails if the given setting is not supported.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $key The setting key.
|
||||
* @param string $error_mode The error mode. Use `ERROR_MODE_EXIT` or `ERROR_MODE_WARNING` constants.
|
||||
* @return bool|never True if the setting is supported, false otherwise. Never returns if $error_mode is `ERROR_MODE_EXIT`.
|
||||
*/
|
||||
private function is_supported( string $key, string $error_mode ) {
|
||||
if ( ! in_array( $key, $this->unsupported, true ) && isset( $this->options->get_schema()['properties'][ $key ] ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
WP_CLI::$error_mode( sprintf( 'Setting "%s" is not supported.', $key ) );
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails if the given setting is read-only.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $key The setting key.
|
||||
* @param string $error_mode The error mode. Use `ERROR_MODE_EXIT` or `ERROR_MODE_WARNING` constants.
|
||||
* @return bool|never True if the setting is mutable, false otherwise. Never returns if $error_mode is `ERROR_MODE_EXIT`.
|
||||
*/
|
||||
private function is_mutable( string $key, string $error_mode ) {
|
||||
if ( $this->is_read_only( $key ) ) {
|
||||
WP_CLI::$error_mode( sprintf( 'Setting "%s" is read-only and cannot be modified.', $key ) );
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails if the given setting is not a list or map setting.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $key The setting key.
|
||||
* @param string $error_mode The error mode. Use `ERROR_MODE_EXIT` or `ERROR_MODE_WARNING` constants.
|
||||
* @return bool|never True if the setting is a list or map setting, false otherwise. Never returns if $error_mode is `ERROR_MODE_EXIT`.
|
||||
*/
|
||||
private function is_array_like( string $key, string $error_mode ) {
|
||||
if ( ! $this->is_list( $key ) && ! $this->is_map( $key ) ) {
|
||||
WP_CLI::$error_mode( sprintf( 'Setting "%s" is not a list or map setting. Use "set" command for scalar settings.', $key ) );
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a formatter instance.
|
||||
*
|
||||
* @param array $assoc_args The command associative arguments.
|
||||
* @return Formatter The formatter instance.
|
||||
*/
|
||||
private function get_formatter( array $assoc_args ) {
|
||||
return new Formatter(
|
||||
$assoc_args,
|
||||
array(
|
||||
'key',
|
||||
'value',
|
||||
'type',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given option is read-only.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $key The option key.
|
||||
* @return boolean True if the option is read-only, false otherwise.
|
||||
*/
|
||||
private function is_read_only( string $key ): bool {
|
||||
$schema = $this->options->get_schema();
|
||||
|
||||
if ( ! isset( $schema['properties'][ $key ] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! empty( $schema['properties'][ $key ]['readonly'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given option key is for a scalar setting.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $key The option key.
|
||||
* @return bool True if the option is a scalar, false otherwise.
|
||||
*/
|
||||
private function is_scalar( string $key ): bool {
|
||||
$schema = $this->options->get_schema();
|
||||
|
||||
return isset( $schema['properties'][ $key ]['type'] ) && in_array( $schema['properties'][ $key ]['type'], array( 'string', 'boolean', 'integer' ), true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given option key is for a list setting.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $key The option key.
|
||||
* @return bool True if the option is a list, false otherwise.
|
||||
*/
|
||||
private function is_list( string $key ): bool {
|
||||
$schema = $this->options->get_schema();
|
||||
|
||||
return isset( $schema['properties'][ $key ]['type'] ) && 'array' === $schema['properties'][ $key ]['type'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given option key is for a map setting.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $key The option key.
|
||||
* @return bool True if the option is a map, false otherwise.
|
||||
*/
|
||||
private function is_map( string $key ): bool {
|
||||
$schema = $this->options->get_schema();
|
||||
return isset( $schema['properties'][ $key ]['type'] ) && 'object' === $schema['properties'][ $key ]['type'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of normalized settings.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $settings The settings.
|
||||
* @param array $properties List of properties.
|
||||
* @return array[] The normalized array.
|
||||
*
|
||||
* @phpstan-return list<array<string, mixed>>
|
||||
*/
|
||||
private function normalize_settings( array $settings, array $properties ) {
|
||||
$items = array();
|
||||
foreach ( $settings as $key => $value ) {
|
||||
$items[] = $this->adapter->get_item( $key, $value, $properties[ $key ] );
|
||||
}
|
||||
return $items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\CLI\Command;
|
||||
|
||||
/**
|
||||
* Adapter for setting transformations.
|
||||
*
|
||||
* Adapts between user-facing CLI interface and internal settings structure.
|
||||
* Allows to simplify the interface for the user changing key names or rendering prettier values.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Setting_Adapter {
|
||||
|
||||
/**
|
||||
* Returns the arguments adapted from user-facing interface to internal structure.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $args The arguments.
|
||||
* @return array The adapted arguments.
|
||||
*/
|
||||
public function get_args( array $args ): array {
|
||||
if ( 'media_duplicate' === $args[0] ) {
|
||||
return array(
|
||||
'media',
|
||||
array(
|
||||
'duplicate' => $args[1],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the associative arguments adapted from user-facing interface to internal structure.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $assoc_args The associative arguments.
|
||||
* @return array The adapted associative arguments.
|
||||
*/
|
||||
public function get_assoc_args( array $assoc_args ): array {
|
||||
if ( ! isset( $assoc_args['keys'] ) ) {
|
||||
return $assoc_args;
|
||||
}
|
||||
|
||||
$assoc_args['keys'] = preg_replace( '/\bmedia_duplicate\b/', 'media', $assoc_args['keys'] );
|
||||
|
||||
return $assoc_args;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the setting item adapted from internal structure to user-facing interface.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $key The key of the item.
|
||||
* @param mixed $value The value of the item.
|
||||
* @param array $property The property of the item.
|
||||
* @return array The adapted item.
|
||||
*/
|
||||
public function get_item( string $key, $value, array $property ): array {
|
||||
if ( 'media' !== $key ) {
|
||||
return array(
|
||||
'key' => $key,
|
||||
'value' => $value,
|
||||
'type' => $property['type'],
|
||||
);
|
||||
}
|
||||
|
||||
/** @var array{duplicate: bool} $value */
|
||||
return array(
|
||||
'key' => 'media_duplicate',
|
||||
'value' => $value['duplicate'],
|
||||
'type' => 'boolean',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\CLI;
|
||||
|
||||
use WP_CLI;
|
||||
use PLL_Model;
|
||||
use WP_Syntex\Polylang_Pro\Modules\CLI\Command\Language;
|
||||
use WP_Syntex\Polylang_Pro\Modules\CLI\Command\Setting;
|
||||
|
||||
/**
|
||||
* Registers Polylang CLI Commands.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Commands {
|
||||
|
||||
/**
|
||||
* Polylang model.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Base command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $base = 'pll';
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Model $model The Polylang model.
|
||||
*/
|
||||
public function __construct( PLL_Model $model ) {
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers Polylang CLI Commands.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register(): void {
|
||||
WP_CLI::add_command( "$this->base setting", new Setting( $this->model->options ) );
|
||||
WP_CLI::add_command( "$this->base language", new Language( $this->model->languages ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\CLI;
|
||||
|
||||
use WP_CLI\Formatter as WP_CLI_Formatter;
|
||||
|
||||
/**
|
||||
* Adapts the WP CLI formatter to handle booleans correctly.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Formatter {
|
||||
|
||||
/**
|
||||
* Output format arguments.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $assoc_args;
|
||||
|
||||
/**
|
||||
* WP CLI formatter.
|
||||
*
|
||||
* @var WP_CLI_Formatter
|
||||
*/
|
||||
private $wp_cli_formatter;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $assoc_args Output format arguments.
|
||||
* @param array $fields Fields to display of each item.
|
||||
*/
|
||||
public function __construct( $assoc_args, $fields = null ) {
|
||||
$this->assoc_args = $assoc_args;
|
||||
$this->wp_cli_formatter = new WP_CLI_Formatter( $assoc_args, $fields );
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays multiple items according to the output arguments.
|
||||
* This displays true/false strings when using formats that don't display booleans nicely (table, csv).
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $items The items to display.
|
||||
* @return void
|
||||
*/
|
||||
public function display_items( $items ) {
|
||||
if ( ! empty( $this->assoc_args['format'] ) && in_array( $this->assoc_args['format'], array( 'json', 'yaml' ), true ) ) {
|
||||
$this->wp_cli_formatter->display_items( $items );
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ( $items as &$item ) {
|
||||
foreach ( $item as &$prop ) {
|
||||
if ( is_bool( $prop ) ) {
|
||||
$prop = $prop ? 'true' : 'false';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->wp_cli_formatter->display_items( $items );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\CLI;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
use PLL_Admin;
|
||||
use WP_Syntex\Polylang_Pro\Modules\CLI\Commands;
|
||||
|
||||
if ( defined( 'WP_CLI' ) && \WP_CLI && $polylang instanceof PLL_Admin ) {
|
||||
( new Commands( $polylang->model ) )->register();
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities;
|
||||
|
||||
use WP_User;
|
||||
use PLL_Base;
|
||||
use PLL_Model;
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang\Capabilities\Capabilities;
|
||||
use WP_Syntex\Polylang\Capabilities\User\NOOP;
|
||||
use WP_Syntex\Polylang\Capabilities\User\User_Interface;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper\Term;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper\Post;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper\Internal;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\User\Translator;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper\Do_Not_Allow;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper\Abstract_Mapper;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper\Machine_Translation;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Create\Post as Create_Post;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Create\Term as Create_Term;
|
||||
|
||||
/**
|
||||
* Class to orchestrate the capabilities mappers.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Advanced_Capabilities {
|
||||
/**
|
||||
* @var Abstract_Mapper
|
||||
*/
|
||||
private $mapper_chain;
|
||||
|
||||
/**
|
||||
* @var Create_Post
|
||||
*/
|
||||
public $create_post;
|
||||
|
||||
/**
|
||||
* @var Create_Term
|
||||
*/
|
||||
public $create_term;
|
||||
|
||||
/**
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Base $polylang Polylang instance.
|
||||
*/
|
||||
public function __construct( PLL_Base $polylang ) {
|
||||
$this->model = $polylang->model;
|
||||
$this->create_post = (
|
||||
new Create_Post(
|
||||
$polylang->model,
|
||||
$polylang->request,
|
||||
property_exists( $polylang, 'pref_lang' ) ? $polylang->pref_lang : null,
|
||||
property_exists( $polylang, 'curlang' ) ? $polylang->curlang : null
|
||||
)
|
||||
)->init();
|
||||
$this->create_term = (
|
||||
new Create_Term(
|
||||
$polylang->model,
|
||||
$polylang->request,
|
||||
property_exists( $polylang, 'pref_lang' ) ? $polylang->pref_lang : null,
|
||||
property_exists( $polylang, 'curlang' ) ? $polylang->curlang : null
|
||||
)
|
||||
)->init();
|
||||
|
||||
$this->mapper_chain = new Do_Not_Allow();
|
||||
$this->mapper_chain
|
||||
->set_next( new Post( $polylang->model, $polylang->sync_post_model ) )
|
||||
->set_next( new Term( $polylang->model ) )
|
||||
->set_next( new Machine_Translation() )
|
||||
->set_next( new Internal( Capabilities::LANGUAGES ) )
|
||||
->set_next( new Internal( Capabilities::TRANSLATIONS ) );
|
||||
|
||||
add_filter( 'map_meta_cap', array( $this, 'map' ), 10, 4 );
|
||||
add_filter( 'pll_admin_preferred_language', array( $this, 'filter_preferred_language' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a capability to the primitive capabilities required of the given user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string[] $caps Primitive capabilities required of the user.
|
||||
* @param string $cap Capability being checked.
|
||||
* @param int $user_id The user ID.
|
||||
* @param array $args Adds context to the capability check, typically
|
||||
* starting with an object ID.
|
||||
* @return string[] Updated primitive capabilities required of the user.
|
||||
*/
|
||||
public function map( $caps, $cap, $user_id, $args ) {
|
||||
if ( ! is_array( $caps ) || ! is_string( $cap ) || ! is_numeric( $user_id ) || ! is_array( $args ) ) {
|
||||
// Type safety.
|
||||
return $caps;
|
||||
}
|
||||
|
||||
return $this->mapper_chain->map(
|
||||
$caps,
|
||||
$cap,
|
||||
Capabilities::get_user( new WP_User( $user_id ) ),
|
||||
$args
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the preferred language to ensure it's authorized for translators.
|
||||
* - If the preferred language is authorized, keeps it.
|
||||
* - Otherwise, returns the first authorized language.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Language|false $pref_lang The preferred language.
|
||||
* @return PLL_Language|false The authorized preferred language, or false if none available.
|
||||
*/
|
||||
public function filter_preferred_language( $pref_lang ) {
|
||||
if ( $pref_lang instanceof PLL_Language ) {
|
||||
$user = Capabilities::get_user();
|
||||
if ( $user->can_translate( $pref_lang ) ) {
|
||||
return $pref_lang;
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, return the first authorized language.
|
||||
$authorized_languages = $this->model->languages->filter( 'translator' )->get_list();
|
||||
// If no language can be found, return false as `PLL_Model::get_default_language()` or `PLL_Model::get_language()`.
|
||||
return ! empty( $authorized_languages ) ? reset( $authorized_languages ) : false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\Create;
|
||||
|
||||
use PLL_Model;
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang\REST\Request;
|
||||
use WP_Syntex\Polylang\Capabilities\Capabilities;
|
||||
use WP_Syntex\Polylang\Capabilities\Create\Post as Create_Post;
|
||||
|
||||
/**
|
||||
* Class to check if the user has the capabilities to create a post in the contextual language.
|
||||
*/
|
||||
class Post {
|
||||
/**
|
||||
* Create_Post instance.
|
||||
*
|
||||
* @var Create_Post
|
||||
*/
|
||||
private $create_post;
|
||||
|
||||
/**
|
||||
* PLL_Model instance.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Model $model The model instance.
|
||||
* @param Request $request The request instance.
|
||||
* @param PLL_Language|null $pref_lang The preferred language.
|
||||
* @param PLL_Language|null $curlang The current language.
|
||||
*/
|
||||
public function __construct( PLL_Model $model, Request $request, ?PLL_Language $pref_lang, ?PLL_Language $curlang ) {
|
||||
$this->create_post = new Create_Post( $model, $request, $pref_lang, $curlang );
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the capabilities checker.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function init(): self {
|
||||
add_filter( 'wp_insert_post_empty_content', array( $this, 'check_capabilities' ), 0, 2 );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user has the capabilities to create a post in the contextual language.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param bool $maybe_empty Whether the post should be considered "empty". Unused.
|
||||
* @param array $postarr Array of post data.
|
||||
*
|
||||
* @return bool|never Untouched `$maybe_empty` parameter value. Die if the user does not have the capabilities.
|
||||
*/
|
||||
public function check_capabilities( $maybe_empty, $postarr ) {
|
||||
if ( ! empty( $postarr['ID'] ) || ! $this->model->post->is_translated_object_type( $postarr['post_type'] ) ) {
|
||||
return $maybe_empty;
|
||||
}
|
||||
|
||||
Capabilities::get_user()->can_translate_or_die(
|
||||
$this->create_post->get_language()
|
||||
);
|
||||
|
||||
return $maybe_empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\Create;
|
||||
|
||||
use PLL_Model;
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang\REST\Request;
|
||||
use WP_Syntex\Polylang\Capabilities\Capabilities;
|
||||
use WP_Syntex\Polylang\Capabilities\Create\Term as Create_Term;
|
||||
|
||||
/**
|
||||
* Class to check if the user has the capabilities to create a term in the contextual language.
|
||||
*/
|
||||
class Term {
|
||||
/**
|
||||
* Create_Term instance.
|
||||
*
|
||||
* @var Create_Term
|
||||
*/
|
||||
private $create_term;
|
||||
|
||||
/**
|
||||
* PLL_Model instance.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Model $model The model instance.
|
||||
* @param Request $request The request instance.
|
||||
* @param PLL_Language|null $pref_lang The preferred language.
|
||||
* @param PLL_Language|null $curlang The current language.
|
||||
*/
|
||||
public function __construct( PLL_Model $model, Request $request, ?PLL_Language $pref_lang, ?PLL_Language $curlang ) {
|
||||
$this->create_term = new Create_Term( $model, $request, $pref_lang, $curlang );
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the capabilities checker.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function init(): self {
|
||||
add_filter( 'pre_insert_term', array( $this, 'check_capabilities' ), 0, 2 );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the user has the capabilities to create a term in the contextual language.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string|\WP_Error $term The term name to add, or a `WP_Error` object if there's an error. Unused.
|
||||
* @param string $taxonomy Taxonomy slug.
|
||||
*
|
||||
* @return string|\WP_Error|never The term name to add, or a `WP_Error` object if there's an error. Die if the user does not have the capabilities.
|
||||
*/
|
||||
public function check_capabilities( $term, $taxonomy ) {
|
||||
if ( is_int( $term ) || ! $this->model->term->is_translated_object_type( $taxonomy ) ) {
|
||||
return $term;
|
||||
}
|
||||
|
||||
Capabilities::get_user()->can_translate_or_die(
|
||||
$this->create_term->get_language()
|
||||
);
|
||||
|
||||
return $term;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities;
|
||||
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang\Capabilities\Capabilities;
|
||||
use WP_Syntex\Polylang\Model\Languages_Proxy_Interface;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Class allowing to filter the list of languages, depending on the current user's capabilities.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Languages_Proxy implements Languages_Proxy_Interface {
|
||||
/**
|
||||
* Returns the proxy's key.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
public function key(): string {
|
||||
return 'translator';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of available languages after passing it through this proxy.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Language[] $languages List of languages to filter.
|
||||
* @return PLL_Language[]
|
||||
*/
|
||||
public function filter( array $languages ): array {
|
||||
$user = Capabilities::get_user();
|
||||
|
||||
if ( ! $user->is_translator() ) {
|
||||
return $languages;
|
||||
}
|
||||
|
||||
return array_filter( $languages, array( $user, 'can_translate' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper;
|
||||
|
||||
use WP_Syntex\Polylang\Capabilities\User\User_Interface;
|
||||
|
||||
/**
|
||||
* Abstract class for capabilities mappers implementing the Chain of Responsibility pattern.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
abstract class Abstract_Mapper {
|
||||
/**
|
||||
* @var Abstract_Mapper|null
|
||||
*/
|
||||
protected $next;
|
||||
|
||||
/**
|
||||
* Maps a capability to the primitive capabilities required of the given user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string[] $caps Primitive capabilities required of the user.
|
||||
* @param string $cap Capability being checked.
|
||||
* @param User_Interface $user The user object.
|
||||
* @param array $args Adds context to the capability check, typically starting with an object ID.
|
||||
* @return string[] Updated primitive capabilities required of the user.
|
||||
*/
|
||||
public function map( array $caps, string $cap, User_Interface $user, array $args ): array {
|
||||
if ( in_array( 'do_not_allow', $caps, true ) ) {
|
||||
return $caps;
|
||||
}
|
||||
|
||||
if ( $this->next ) {
|
||||
return $this->next->map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
return $caps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the next mapper to be used.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param Abstract_Mapper $next_mapper The next mapper to be used.
|
||||
* @return Abstract_Mapper The next mapper to be used.
|
||||
*/
|
||||
public function set_next( Abstract_Mapper $next_mapper ): Abstract_Mapper {
|
||||
$this->next = $next_mapper;
|
||||
|
||||
return $next_mapper;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper;
|
||||
|
||||
/**
|
||||
* Concrete implementation of the `Abstract_Mapper` class.
|
||||
* It is used to break early the chain of mappers when a `do_not_allow` capability is present.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Do_Not_Allow extends Abstract_Mapper {}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper;
|
||||
|
||||
use WP_Syntex\Polylang\Capabilities\User\User_Interface;
|
||||
|
||||
/**
|
||||
* Class to manage our custom capabilities that are mapped to `manage_options`.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Internal extends Abstract_Mapper {
|
||||
/**
|
||||
* The capability mapped to `manage_options`.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $capability;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $capability The capability mapped to `manage_options`.
|
||||
*/
|
||||
public function __construct( string $capability ) {
|
||||
$this->capability = $capability;
|
||||
}
|
||||
/**
|
||||
* Maps a capability to the primitive capabilities required of the given user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string[] $caps Primitive capabilities required of the user.
|
||||
* @param string $cap Capability being checked.
|
||||
* @param User_Interface $user The user object.
|
||||
* @param array $args Adds context to the capability check, typically starting with an object ID.
|
||||
* @return string[] Updated primitive capabilities required of the user.
|
||||
*/
|
||||
public function map( array $caps, string $cap, User_Interface $user, array $args ): array {
|
||||
if ( $this->capability !== $cap ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
if ( $user->has_cap( 'manage_options' ) ) {
|
||||
// Polylang already replaced the custom capability by `manage_options`.
|
||||
return $caps;
|
||||
}
|
||||
|
||||
// Non-administrators must have the custom capability.
|
||||
$caps = array_diff( $caps, array( 'manage_options', $this->capability ) );
|
||||
$caps[] = $this->capability;
|
||||
|
||||
return $caps;
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper;
|
||||
|
||||
use WP_Syntex\Polylang\Capabilities\User\User_Interface;
|
||||
|
||||
/**
|
||||
* Class to map machine translation capabilities.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Machine_Translation extends Abstract_Mapper {
|
||||
/**
|
||||
* The capability allowing to use machine translation.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const CAPABILITY = 'machine_translate';
|
||||
|
||||
/**
|
||||
* Maps a capability to the primitive capabilities required of the given user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string[] $caps Primitive capabilities required of the user.
|
||||
* @param string $cap Capability being checked.
|
||||
* @param User_Interface $user The user object.
|
||||
* @param array $args Adds context to the capability check, typically starting with an object ID.
|
||||
* @return string[] Updated primitive capabilities required of the user.
|
||||
*/
|
||||
public function map( array $caps, string $cap, User_Interface $user, array $args ): array {
|
||||
if ( self::CAPABILITY !== $cap ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
if ( ! pll_get_constant( 'PLL_ENABLE_MACHINE_TRANSLATION_CAPABILITIES' ) ) {
|
||||
// Not enabled: remove `machine_translate`. The list should be empty.
|
||||
return array_diff( $caps, array( self::CAPABILITY ) );
|
||||
}
|
||||
|
||||
if ( $user->has_cap( 'manage_options' ) ) {
|
||||
// Enabled, but administrators are not required to have this capability.
|
||||
return array_diff( $caps, array( self::CAPABILITY ) );
|
||||
}
|
||||
|
||||
return $caps;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper;
|
||||
|
||||
use Closure;
|
||||
use WP_Post;
|
||||
use PLL_Model;
|
||||
use WP_Post_Type;
|
||||
use PLL_Sync_Post_Model;
|
||||
use WP_Syntex\Polylang\Capabilities\User\User_Interface;
|
||||
|
||||
/**
|
||||
* Class to map edit and delete post type capabilities.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Post extends Abstract_Mapper {
|
||||
/**
|
||||
* List of all post type capabilities with predefined primitive capabilities.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private $capabilities = array(
|
||||
'edit_post',
|
||||
'delete_post',
|
||||
'edit_post_meta',
|
||||
'delete_post_meta',
|
||||
'add_post_meta',
|
||||
);
|
||||
|
||||
/**
|
||||
* List of "delete" post type capabilities with predefined primitive capabilities.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private $delete_post_capabilities = array(
|
||||
'delete_post',
|
||||
);
|
||||
|
||||
/**
|
||||
* PLL_Model instance.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
protected $model;
|
||||
|
||||
/**
|
||||
* Sync post model instance.
|
||||
*
|
||||
* @var PLL_Sync_Post_Model
|
||||
*/
|
||||
private $sync_post_model;
|
||||
|
||||
/**
|
||||
* Used to prevent an infinite loop in `map()`, and improve performance.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $processing_sync = array();
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Model $model Model instance.
|
||||
* @param PLL_Sync_Post_Model $sync_post_model Sync post model instance.
|
||||
*/
|
||||
public function __construct( PLL_Model $model, PLL_Sync_Post_Model $sync_post_model ) {
|
||||
$this->model = $model;
|
||||
$this->sync_post_model = $sync_post_model;
|
||||
|
||||
array_map(
|
||||
array( $this, 'add_capabilities' ),
|
||||
get_post_types( array(), 'objects' ),
|
||||
);
|
||||
|
||||
add_action( 'registered_post_type', Closure::fromCallable( array( $this, 'load_capabilities' ) ), 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a capability to the primitive capabilities required of the given user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string[] $caps Primitive capabilities required of the user.
|
||||
* @param string $cap Capability being checked.
|
||||
* @param User_Interface $user The user object.
|
||||
* @param array $args Adds context to the capability check, typically starting with an object ID.
|
||||
* @return string[] Updated primitive capabilities required of the user.
|
||||
*/
|
||||
public function map( array $caps, string $cap, User_Interface $user, array $args ): array {
|
||||
if ( empty( $args[0] ) ) {
|
||||
// No additional arguments.
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
if ( ! $user->is_translator() ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
if ( ! in_array( $cap, $this->capabilities, true ) ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
// Accepts a post ID or a WP_Post as WordPress does, the latter being undocumented.
|
||||
$post = get_post( $args[0] );
|
||||
|
||||
if ( ! $post instanceof WP_Post ) {
|
||||
// Wrong type of argument, or the post doesn't exist.
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
$key_suffix = sprintf( '|%d|%s', $user->get_id(), $cap );
|
||||
|
||||
if ( ! empty( $this->processing_sync[ $post->ID . $key_suffix ] ) ) {
|
||||
// Already processing this post in the `foreach` loop at the end of this method.
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
if ( ! $this->model->post->is_translated_object_type( $post->post_type ) ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
$language = $this->model->post->get_language( $post->ID );
|
||||
|
||||
if ( ! $language || ! $user->can_translate( $language ) ) {
|
||||
$caps[] = 'do_not_allow';
|
||||
return $caps;
|
||||
}
|
||||
|
||||
if ( in_array( $cap, $this->delete_post_capabilities, true ) ) {
|
||||
// No need to deal with synchronization.
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
$synchros = $this->sync_post_model->get( $post->ID );
|
||||
|
||||
if ( empty( $synchros ) ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
/*
|
||||
* Check all languages at once:
|
||||
* - Much faster here than in the `foreach` loop below.
|
||||
* - This allows to stop here if the user doesn't have all the required language capabilities (no need to check
|
||||
* anything else in this case).
|
||||
*/
|
||||
if ( ! $user->can_translate_all( array_keys( $synchros ) ) ) {
|
||||
$caps[] = 'do_not_allow';
|
||||
return $caps;
|
||||
}
|
||||
|
||||
/*
|
||||
* Make sure this post is not synchronized with one that the user can't edit (for whatever reason that is not
|
||||
* related to language capabilities).
|
||||
*/
|
||||
foreach ( $synchros as $tr_id ) {
|
||||
if ( (int) $tr_id === $post->ID ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tr_key = $tr_id . $key_suffix;
|
||||
|
||||
$this->processing_sync[ $tr_key ] = true;
|
||||
|
||||
if ( ! $user->has_cap( $cap, (int) $tr_id ) ) {
|
||||
unset( $this->processing_sync[ $tr_key ] );
|
||||
$caps[] = 'do_not_allow';
|
||||
return $caps;
|
||||
}
|
||||
|
||||
unset( $this->processing_sync[ $tr_key ] );
|
||||
}
|
||||
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the post type capabilities.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $post_type Post type. Unused.
|
||||
* @param WP_Post_Type $post_type_object Post type object.
|
||||
* @return void
|
||||
*/
|
||||
private function load_capabilities( $post_type, $post_type_object ): void {
|
||||
$post_type_object instanceof WP_Post_Type && $this->add_capabilities( $post_type_object );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the capabilities for a post type.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param WP_Post_Type $post_type_object Post type object.
|
||||
* @return void
|
||||
*/
|
||||
private function add_capabilities( WP_Post_Type $post_type_object ): void {
|
||||
if ( ! $this->model->post->is_translated_object_type( $post_type_object->name ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->delete_post_capabilities = array_merge(
|
||||
$this->delete_post_capabilities,
|
||||
array( $post_type_object->cap->delete_post )
|
||||
);
|
||||
$this->capabilities = array_merge(
|
||||
$this->capabilities,
|
||||
$this->delete_post_capabilities,
|
||||
array( $post_type_object->cap->edit_post )
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper;
|
||||
|
||||
use Closure;
|
||||
use WP_Term;
|
||||
use PLL_Model;
|
||||
use WP_Taxonomy;
|
||||
use WP_Syntex\Polylang\Capabilities\User\User_Interface;
|
||||
|
||||
/**
|
||||
* Class to map taxonomy capabilities.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Term extends Abstract_Mapper {
|
||||
/**
|
||||
* List of taxonomy capabilities with predefined primitive capabilities.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private $capabilities = array(
|
||||
'edit_term',
|
||||
'delete_term',
|
||||
'edit_term_meta',
|
||||
'delete_term_meta',
|
||||
'add_term_meta',
|
||||
);
|
||||
|
||||
/**
|
||||
* PLL_Model instance.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Model $model Model instance.
|
||||
*/
|
||||
public function __construct( PLL_Model $model ) {
|
||||
$this->model = $model;
|
||||
|
||||
array_map(
|
||||
array( $this, 'add_capabilities' ),
|
||||
get_taxonomies( array(), 'objects' ),
|
||||
);
|
||||
|
||||
add_action( 'registered_taxonomy', Closure::fromCallable( array( $this, 'load_capabilities' ) ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a capability to the primitive capabilities required of the given user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string[] $caps Primitive capabilities required of the user.
|
||||
* @param string $cap Capability being checked.
|
||||
* @param User_Interface $user The user object.
|
||||
* @param array $args Adds context to the capability check, typically starting with an object ID.
|
||||
* @return string[] Updated primitive capabilities required of the user.
|
||||
*/
|
||||
public function map( array $caps, string $cap, User_Interface $user, array $args ): array {
|
||||
if ( empty( $args[0] ) || ! is_numeric( $args[0] ) ) {
|
||||
// No additional arguments or non-numeric.
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
if ( ! $user->is_translator() ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
if ( ! in_array( $cap, $this->capabilities, true ) ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
$term = get_term( (int) $args[0] );
|
||||
if ( ! $term instanceof WP_Term || ! $this->model->term->is_translated_object_type( $term->taxonomy ) ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
$language = $this->model->term->get_language( $term->term_id );
|
||||
if ( $language && $user->can_translate( $language ) ) {
|
||||
return parent::map( $caps, $cap, $user, $args );
|
||||
}
|
||||
|
||||
$caps[] = 'do_not_allow';
|
||||
|
||||
return $caps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the taxonomy capabilities.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $taxonomy Taxonomy name.
|
||||
* @return void
|
||||
*/
|
||||
private function load_capabilities( $taxonomy ): void {
|
||||
$taxonomy_object = get_taxonomy( $taxonomy );
|
||||
if ( ! $taxonomy_object ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->add_capabilities( $taxonomy_object );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the capabilities for a taxonomy.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param WP_Taxonomy $taxonomy_object Taxonomy object.
|
||||
* @return void
|
||||
*/
|
||||
private function add_capabilities( WP_Taxonomy $taxonomy_object ): void {
|
||||
if ( ! $this->model->term->is_translated_object_type( $taxonomy_object->name ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->capabilities = array_merge(
|
||||
$this->capabilities,
|
||||
array( $taxonomy_object->cap->edit_terms, $taxonomy_object->cap->delete_terms )
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\User;
|
||||
|
||||
use WP_User;
|
||||
use WP_Syntex\Polylang\Capabilities\User\NOOP;
|
||||
use WP_Syntex\Polylang\Capabilities\User\User_Interface;
|
||||
use WP_Syntex\Polylang\Capabilities\User\Creator_Interface;
|
||||
|
||||
/**
|
||||
* A class that returns the correct user instance based on the user capabilities.
|
||||
* Completely disables the user decoration.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Creator implements Creator_Interface {
|
||||
/**
|
||||
* @var User_Interface
|
||||
*/
|
||||
private ?User_Interface $instance = null;
|
||||
|
||||
/**
|
||||
* Creates and returns the user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param WP_User $user The user to decorate.
|
||||
* @return User_Interface The user instance.
|
||||
*/
|
||||
public function get( WP_User $user ): User_Interface {
|
||||
if ( $this->instance && $user->ID === $this->instance->get_id() ) {
|
||||
return $this->instance;
|
||||
}
|
||||
|
||||
/*
|
||||
* Voluntarily checking `WP_user::$allcaps` instead of `WP_user::has_cap()` to avoid infinite loop with the `map_meta_cap` filter.
|
||||
* Checking `manage_options` is appropriate because it allows both super admins and admins.
|
||||
*/
|
||||
if ( ! empty( $user->allcaps['manage_options'] ) ) {
|
||||
$this->instance = new NOOP( $user );
|
||||
|
||||
return $this->instance;
|
||||
}
|
||||
|
||||
$this->instance = new Translator( $user );
|
||||
|
||||
return $this->instance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities\User;
|
||||
|
||||
use WP_User;
|
||||
use PLL_Language;
|
||||
use WP_Syntex\Polylang\Model\Languages;
|
||||
use WP_Syntex\Polylang\Capabilities\User\User_Interface;
|
||||
|
||||
/**
|
||||
* A decorator for `WP_User` that adds translation management capabilities.
|
||||
*
|
||||
* @since 3.8
|
||||
*/
|
||||
class Translator implements User_Interface {
|
||||
/**
|
||||
* @var WP_User
|
||||
*/
|
||||
private $user;
|
||||
|
||||
/**
|
||||
* @var string[]|null
|
||||
*/
|
||||
private $language_caps;
|
||||
|
||||
/**
|
||||
* @var bool[]
|
||||
*/
|
||||
private $can_translate = array();
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param WP_User $user An instance of `WP_User`.
|
||||
*/
|
||||
public function __construct( WP_User $user ) {
|
||||
$this->user = $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the user ID.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_id(): int {
|
||||
return $this->user->ID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the user is a translator (has a translator capability).
|
||||
* Note: returns `true` if the user has a capability for a language that doesn't exist anymore. This is intentional,
|
||||
* to prevent the user to suddenly have the rights to translate in all languages while it wasn't allowed until then.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_translator(): bool {
|
||||
return ! empty( $this->get_language_caps() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the user can translate to the given language.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Language $language A language object.
|
||||
* @return bool
|
||||
*/
|
||||
public function can_translate( PLL_Language $language ): bool {
|
||||
if ( isset( $this->can_translate[ $language->slug ] ) ) {
|
||||
return $this->can_translate[ $language->slug ];
|
||||
}
|
||||
|
||||
if ( ! $this->is_translator() ) {
|
||||
$this->can_translate[ $language->slug ] = true;
|
||||
} else {
|
||||
$this->can_translate[ $language->slug ] = $this->user->has_cap( "translate_{$language->slug}" );
|
||||
}
|
||||
|
||||
return $this->can_translate[ $language->slug ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the user can translate to all the given languages.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $languages List of language slugs.
|
||||
* @return bool
|
||||
*
|
||||
* @phpstan-param array<non-empty-string> $languages
|
||||
*/
|
||||
public function can_translate_all( array $languages ): bool {
|
||||
if ( ! $this->is_translator() ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $languages as $language_slug ) {
|
||||
if ( ! isset( $this->can_translate[ $language_slug ] ) ) {
|
||||
$this->can_translate[ $language_slug ] = $this->user->has_cap( "translate_{$language_slug}" );
|
||||
}
|
||||
if ( ! $this->can_translate[ $language_slug ] ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the user has the specified capability.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $capability Capability name.
|
||||
* @param mixed ...$args Optional further parameters, typically starting with an object ID.
|
||||
* @return bool
|
||||
*/
|
||||
public function has_cap( $capability, ...$args ): bool {
|
||||
return $this->user->has_cap( $capability, ...$args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the preferred language of the user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return string The preferred language slug, empty string if no preferred language is found.
|
||||
*/
|
||||
public function get_preferred_language_slug(): string {
|
||||
$language_caps = $this->get_language_caps();
|
||||
|
||||
if ( empty( $language_caps ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Arbitrarily use the first language cap.
|
||||
$language_cap = reset( $language_caps );
|
||||
|
||||
return str_replace( 'translate_', '', $language_cap );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the language capabilities of the user.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_language_caps(): array {
|
||||
if ( isset( $this->language_caps ) ) {
|
||||
return $this->language_caps;
|
||||
}
|
||||
|
||||
$this->language_caps = (array) preg_grep( '/^translate_' . Languages::INNER_SLUG_PATTERN . '$/', array_keys( $this->user->allcaps ) );
|
||||
|
||||
return $this->language_caps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current user has the rights to assign a language to an object and dies if not.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param PLL_Language $language The language to assign.
|
||||
* @return void|never Dies if the user does not have the rights, does nothing otherwise.
|
||||
*/
|
||||
public function can_translate_or_die( PLL_Language $language ): void {
|
||||
if ( ! $this->can_translate( $language ) ) {
|
||||
/* translators: %s is a language name */
|
||||
wp_die( esc_html( sprintf( __( 'Sorry, you are not allowed to edit content in %s.', 'polylang-pro' ), $language->name ) ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Capabilities;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( $polylang->model->has_languages() ) {
|
||||
require_once POLYLANG_PRO_DIR . '/src/modules/sync-post/load.php'; // Make sure `$polylang->sync_post_model` is set.
|
||||
|
||||
$polylang->model->languages->register_proxy( new Languages_Proxy() );
|
||||
$polylang->advanced_capabilities = new Advanced_Capabilities( $polylang );
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Editors;
|
||||
|
||||
use WP_Post;
|
||||
use PLL_Base;
|
||||
use PLL_Model;
|
||||
use PLL_Language;
|
||||
use PLL_Admin_Block_Editor;
|
||||
use WP_Block_Editor_Context;
|
||||
|
||||
/**
|
||||
* Class to filter REST preload paths.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Filter_Preload_Paths {
|
||||
/**
|
||||
* @var PLL_Model
|
||||
*/
|
||||
protected $model;
|
||||
|
||||
/**
|
||||
* @var PLL_Language|false|null
|
||||
*/
|
||||
protected $curlang;
|
||||
|
||||
/**
|
||||
* @var PLL_Admin_Block_Editor|null
|
||||
*/
|
||||
protected $block_editor;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @since 2.6
|
||||
*
|
||||
* @param PLL_Base $polylang Polylang object.
|
||||
*/
|
||||
public function __construct( PLL_Base &$polylang ) {
|
||||
$this->model = &$polylang->model;
|
||||
$this->curlang = &$polylang->curlang;
|
||||
$this->block_editor = &$polylang->block_editor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds required hooks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function init(): self {
|
||||
add_filter( 'block_editor_rest_api_preload_paths', array( $this, 'filter_preload_paths' ), 50, 2 );
|
||||
add_filter( 'pll_filtered_rest_routes', array( $this, 'filter_navigation_fallback_route' ) );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters preload paths based on the context (block editor for posts, site editor or widget editor for instance).
|
||||
*
|
||||
* @since 3.4
|
||||
*
|
||||
* @param (string|string[])[] $preload_paths Preload paths.
|
||||
* @param WP_Block_Editor_Context $context Editor context.
|
||||
* @return array Filtered preload paths.
|
||||
*/
|
||||
public function filter_preload_paths( $preload_paths, $context ) {
|
||||
if ( ! $context instanceof WP_Block_Editor_Context || empty( $this->block_editor ) ) {
|
||||
return $preload_paths;
|
||||
}
|
||||
|
||||
if ( $context->post instanceof WP_Post && ! $this->model->is_translated_post_type( $context->post->post_type ) ) {
|
||||
return $preload_paths;
|
||||
}
|
||||
|
||||
$preload_paths = (array) $preload_paths;
|
||||
|
||||
// Do nothing if in post editor since `PLL_Admin_Block_Editor` has already filtered.
|
||||
if ( 'core/edit-post' !== $context->name ) {
|
||||
$lang = ! empty( $this->curlang ) ? $this->curlang->slug : null;
|
||||
|
||||
if ( empty( $lang ) || 'core/edit-widgets' === $context->name ) {
|
||||
// WP 6.0+: widget screen filtered by default language. See `WP_Syntex\Polylang_Pro\Editors\Screens\Widget::get_language()`.
|
||||
$lang = $this->model->options['default_lang'];
|
||||
}
|
||||
|
||||
$preload_paths = $this->block_editor->filter_rest_routes->add_query_parameters(
|
||||
$preload_paths,
|
||||
array(
|
||||
'lang' => $lang,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$preload_paths[] = '/pll/v1/languages';
|
||||
|
||||
return $preload_paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds navigation fallback REST route to the filterable ones.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param string[] $routes Filterable REST routes.
|
||||
* @return string[] Filtered filterable REST routes.
|
||||
*/
|
||||
public function filter_navigation_fallback_route( $routes ) {
|
||||
$routes['navigation-fallback'] = 'wp-block-editor/v1/navigation-fallback';
|
||||
|
||||
return $routes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Editors\Screens;
|
||||
|
||||
use PLL_Model;
|
||||
use PLL_Base;
|
||||
use WP_Screen;
|
||||
use PLL_Language;
|
||||
use PLL_Admin_Block_Editor;
|
||||
|
||||
/**
|
||||
* Template class to manage editors scripts.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
abstract class Abstract_Screen {
|
||||
/**
|
||||
* The script suffix, default empty.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $suffix = '';
|
||||
|
||||
/**
|
||||
* @var PLL_Admin_Block_Editor|null
|
||||
*/
|
||||
protected $block_editor;
|
||||
|
||||
/**
|
||||
* @var PLL_Model
|
||||
*/
|
||||
protected $model;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Base $polylang Polylang main object.
|
||||
*/
|
||||
public function __construct( &$polylang ) {
|
||||
if ( ! defined( 'SCRIPT_DEBUG' ) || ! SCRIPT_DEBUG ) {
|
||||
$this->suffix = '.min';
|
||||
}
|
||||
|
||||
$this->model = &$polylang->model;
|
||||
$this->block_editor = &$polylang->block_editor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds required hooks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function init() {
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues script for the editors.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function enqueue(): void {
|
||||
$screen = get_current_screen();
|
||||
if ( empty( $screen ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( $this->can_enqueue_style( $screen ) ) {
|
||||
$this->enqueue_style();
|
||||
}
|
||||
|
||||
if ( ! $this->screen_matches( $screen ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_enqueue_script(
|
||||
static::get_handle(),
|
||||
plugins_url( $this->get_script_path(), POLYLANG_ROOT_FILE ),
|
||||
array(
|
||||
'wp-api-fetch',
|
||||
'wp-data',
|
||||
'wp-i18n',
|
||||
'wp-sanitize',
|
||||
'lodash',
|
||||
),
|
||||
POLYLANG_VERSION,
|
||||
true
|
||||
);
|
||||
|
||||
$editor_lang = $this->get_language();
|
||||
if ( ! empty( $editor_lang ) ) {
|
||||
$editor_lang = $editor_lang->to_array();
|
||||
}
|
||||
$pll_settings_script = 'let pll_block_editor_plugin_settings = ' . wp_json_encode(
|
||||
/**
|
||||
* Filters settings required by the UI.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $settings.
|
||||
*/
|
||||
(array) apply_filters(
|
||||
'pll_block_editor_plugin_settings',
|
||||
array(
|
||||
'lang' => $editor_lang,
|
||||
'nonce' => wp_create_nonce( 'pll_language' ),
|
||||
'authorizedLanguagesSlugs' => $this->model->languages
|
||||
->filter( 'translator' )
|
||||
->get_list( array( 'fields' => 'slug' ) ),
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
wp_add_inline_script( static::get_handle(), $pll_settings_script, 'before' );
|
||||
wp_set_script_translations( static::get_handle(), 'polylang-pro' );
|
||||
|
||||
if ( ! empty( $this->block_editor ) ) {
|
||||
$this->block_editor->filter_rest_routes->add_inline_script( static::get_handle() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given screen matches the type of the current object.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Screen $screen The WordPress screen object.
|
||||
* @return bool True is the screen is a match, false otherwise.
|
||||
*/
|
||||
abstract protected function screen_matches( WP_Screen $screen ): bool;
|
||||
|
||||
/**
|
||||
* Returns the current editor language.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return PLL_Language|null The language object if found, `null` otherwise.
|
||||
*/
|
||||
abstract protected function get_language(): ?PLL_Language;
|
||||
|
||||
/**
|
||||
* Returns the screen name to use across all process.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
abstract protected function get_screen_name(): string;
|
||||
|
||||
/**
|
||||
* Tells if the given screen is suitable for stylesheet enqueueing.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Screen $screen The WordPress screen object.
|
||||
* @return bool
|
||||
*/
|
||||
protected function can_enqueue_style( WP_Screen $screen ): bool {
|
||||
return $this->screen_matches( $screen );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the main script handle for the editor.
|
||||
* Useful to add inline scripts or to register translations for instance.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string The handle.
|
||||
*/
|
||||
protected function get_handle(): string {
|
||||
return "pll_{$this->get_screen_name()}_sidebar";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path to the main script for the editor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string The full path.
|
||||
*/
|
||||
protected function get_script_path(): string {
|
||||
return "/js/build/editors/{$this->get_screen_name()}{$this->suffix}.js";
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues stylesheet commonly used in all editors.
|
||||
* Override to your taste.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function enqueue_style(): void {
|
||||
wp_enqueue_style(
|
||||
'polylang-block-widget-editor-css',
|
||||
plugins_url( '/css/build/style' . $this->suffix . '.css', POLYLANG_ROOT_FILE ),
|
||||
array( 'wp-components' ),
|
||||
POLYLANG_VERSION
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Editors\Screens;
|
||||
|
||||
use PLL_Base;
|
||||
use WP_Screen;
|
||||
use PLL_Language;
|
||||
use PLL_CRUD_Posts;
|
||||
use PLL_Admin_Links;
|
||||
|
||||
/**
|
||||
* Class to manage Post editor scripts.
|
||||
*/
|
||||
class Post extends Abstract_Screen {
|
||||
/**
|
||||
* @var PLL_CRUD_Posts|null
|
||||
*/
|
||||
protected $posts;
|
||||
|
||||
/**
|
||||
* @var PLL_Admin_Links|null
|
||||
*/
|
||||
private $links;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Base $polylang Polylang object.
|
||||
*/
|
||||
public function __construct( PLL_Base &$polylang ) {
|
||||
parent::__construct( $polylang );
|
||||
|
||||
$this->posts = &$polylang->posts;
|
||||
$this->links = &$polylang->links;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds required hooks.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function init() {
|
||||
parent::init();
|
||||
|
||||
add_filter( 'pll_block_editor_plugin_settings', array( $this, 'add_new_post_translation_link' ) );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the nonce field for the new post translation
|
||||
* in the block editor plugin settings.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array $settings The settings array.
|
||||
* @return array The settings array.
|
||||
*/
|
||||
public function add_new_post_translation_link( $settings ) {
|
||||
global $post;
|
||||
|
||||
$screen = get_current_screen();
|
||||
if ( empty( $this->links ) || empty( $screen ) || ! $this->screen_matches( $screen ) || empty( $post ) ) {
|
||||
return $settings;
|
||||
}
|
||||
|
||||
foreach ( $this->model->get_languages_list() as $language ) {
|
||||
$settings['new_post_translation_links'][ $language->slug ] = $this->links->get_new_post_translation_link(
|
||||
$post,
|
||||
$language,
|
||||
'keep ampersand'
|
||||
);
|
||||
}
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells whether the given screen is the Post edtitor or not.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Screen $screen The current screen.
|
||||
* @return bool True if Post editor screen, false otherwise.
|
||||
*/
|
||||
protected function screen_matches( WP_Screen $screen ): bool {
|
||||
return (
|
||||
'post' === $screen->base
|
||||
&& $this->model->post_types->is_translated( $screen->post_type )
|
||||
&& $screen->is_block_editor()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the language to use in the Post editor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return PLL_Language|null
|
||||
*/
|
||||
protected function get_language(): ?PLL_Language {
|
||||
global $post;
|
||||
|
||||
if ( ! empty( $post ) && ! empty( $this->posts ) && $this->model->post_types->is_translated( $post->post_type ) ) {
|
||||
$this->posts->set_default_language( $post->ID );
|
||||
$post_lang = $this->model->post->get_language( $post->ID );
|
||||
return ! empty( $post_lang ) ? $post_lang : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the screen name for the Post editor to use across all process.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_screen_name(): string {
|
||||
return 'post';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Editors\Screens;
|
||||
|
||||
use PLL_Base;
|
||||
use PLL_Model;
|
||||
use WP_Screen;
|
||||
use PLL_Language;
|
||||
use PLL_FSE_Tools;
|
||||
|
||||
/**
|
||||
* Class to manage Site editor scripts.
|
||||
*/
|
||||
class Site extends Abstract_Screen {
|
||||
/**
|
||||
* @var PLL_Language|false|null
|
||||
*/
|
||||
protected $curlang;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Base $polylang Polylang object.
|
||||
*/
|
||||
public function __construct( PLL_Base &$polylang ) {
|
||||
parent::__construct( $polylang );
|
||||
|
||||
$this->curlang = &$polylang->curlang;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds required hooks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function init() {
|
||||
parent::init();
|
||||
add_filter( 'pll_admin_ajax_params', array( $this, 'ajax_filter' ) );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the language to the data added to all AJAX requests.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $params List of parameters to add to the admin ajax request.
|
||||
* @return array
|
||||
*/
|
||||
public function ajax_filter( $params ) {
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( empty( $screen ) ) {
|
||||
return $params;
|
||||
}
|
||||
|
||||
if ( ! $this->screen_matches( $screen ) ) {
|
||||
return $params;
|
||||
}
|
||||
|
||||
$editor_lang = $this->get_language();
|
||||
|
||||
if ( empty( $editor_lang ) ) {
|
||||
return $params;
|
||||
}
|
||||
|
||||
$params['lang'] = $editor_lang->slug;
|
||||
return $params;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Tells whether the given screen is the Site edtitor or not.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Screen $screen The current screen.
|
||||
* @return bool True if Site editor screen, false otherwise.
|
||||
*/
|
||||
protected function screen_matches( WP_Screen $screen ): bool {
|
||||
return (
|
||||
'site-editor' === $screen->base
|
||||
&& $this->model->post_types->is_translated( 'wp_template_part' )
|
||||
&& $screen->is_block_editor()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the language to use in the Site editor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return PLL_Language|null
|
||||
*/
|
||||
protected function get_language(): ?PLL_Language {
|
||||
if ( ! empty( $this->curlang ) && PLL_FSE_Tools::is_site_editor() ) {
|
||||
return $this->curlang;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the screen name for the Site editor to use across all process.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_screen_name(): string {
|
||||
return 'site';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Editors\Screens;
|
||||
|
||||
use WP_Screen;
|
||||
use PLL_Language;
|
||||
|
||||
/**
|
||||
* Class to manage Widget editor scripts.
|
||||
*/
|
||||
class Widget extends Abstract_Screen {
|
||||
/**
|
||||
* Adds required hooks.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function init() {
|
||||
add_filter( 'widget_types_to_hide_from_legacy_widget_block', array( $this, 'filter_legacy_widgets' ) );
|
||||
|
||||
return parent::init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given screen can enqueue stylesheet for the customizer.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Screen $screen The WordPress screen object.
|
||||
* @return bool
|
||||
*/
|
||||
protected function can_enqueue_style( WP_Screen $screen ): bool {
|
||||
return 'customize' === $screen->base || parent::can_enqueue_style( $screen );
|
||||
}
|
||||
|
||||
/**
|
||||
* Method that allows legacy widgets in widget block editor previously removed by WP and hide legacy Polylang widget.
|
||||
*
|
||||
* @since 3.2
|
||||
*
|
||||
* @param array $widget_ids An array of hidden widget ids.
|
||||
* @return array
|
||||
*/
|
||||
public function filter_legacy_widgets( $widget_ids ) {
|
||||
$widgets_to_show = array( 'custom_html' );
|
||||
$widget_ids = array_diff( $widget_ids, $widgets_to_show );
|
||||
|
||||
$widgets_to_hide = array( 'polylang' );
|
||||
$widget_ids = array_merge( $widget_ids, $widgets_to_hide );
|
||||
|
||||
return $widget_ids;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Tells whether the given screen is the Widget edtitor or not.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param WP_Screen $screen The current screen.
|
||||
* @return bool True if Widget editor screen, false otherwise.
|
||||
*/
|
||||
protected function screen_matches( WP_Screen $screen ): bool {
|
||||
return (
|
||||
'widgets' === $screen->base
|
||||
&& function_exists( 'wp_use_widgets_block_editor' )
|
||||
&& wp_use_widgets_block_editor()
|
||||
&& $screen->is_block_editor()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the language to use in the Widget editor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return PLL_Language|null
|
||||
*/
|
||||
protected function get_language(): ?PLL_Language {
|
||||
$language = $this->model->languages->get_default();
|
||||
|
||||
return $language instanceof PLL_Language ? $language : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the screen name for the Widget editor to use across all process.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_screen_name(): string {
|
||||
return 'widget';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Editors\Screens\Post;
|
||||
use WP_Syntex\Polylang_Pro\Editors\Screens\Site;
|
||||
use WP_Syntex\Polylang_Pro\Editors\Screens\Widget;
|
||||
use WP_Syntex\Polylang_Pro\Editors\Filter_Preload_Paths;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Don't access directly.
|
||||
}
|
||||
|
||||
add_action(
|
||||
'pll_init',
|
||||
function ( $polylang ) {
|
||||
if (
|
||||
$polylang->model->languages->has()
|
||||
&& $polylang instanceof PLL_Admin
|
||||
&& pll_use_block_editor_plugin()
|
||||
) {
|
||||
$polylang->site_editor = ( new Site( $polylang ) )->init();
|
||||
$polylang->post_editor = ( new Post( $polylang ) )->init();
|
||||
$polylang->widget_editor = ( new Widget( $polylang ) )->init();
|
||||
$polylang->filter_path = ( new Filter_Preload_Paths( $polylang ) )->init();
|
||||
}
|
||||
}
|
||||
);
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Clients;
|
||||
|
||||
use Translations;
|
||||
use PLL_Language;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Interface to use to define a machine translation client.
|
||||
*/
|
||||
interface Client_Interface {
|
||||
/**
|
||||
* Performs a request to machine translation service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param Translations $translations Translations object.
|
||||
* @param PLL_Language $target_language Target language.
|
||||
* @param PLL_Language|null $source_language Source language, leave empty for automatic detection.
|
||||
* @return Translations|WP_Error
|
||||
*/
|
||||
public function translate( Translations $translations, PLL_Language $target_language, $source_language = null );
|
||||
|
||||
/**
|
||||
* Tells whether API key is valid.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return WP_Error An empty WP_Error if valid, a filled WP_Error otherwise.
|
||||
*/
|
||||
public function is_api_key_valid(): WP_Error;
|
||||
|
||||
/**
|
||||
* Returns current machine translation usage.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
public function get_usage();
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Clients;
|
||||
|
||||
use WP_Error;
|
||||
use PLL_Language;
|
||||
use Translations;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Deepl as Service;
|
||||
|
||||
/**
|
||||
* Class for DeepL machine translation client.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @phpstan-import-type DeeplFormality from Service
|
||||
*/
|
||||
class Deepl implements Client_Interface {
|
||||
const ROUTE = 'https://api.deepl.com/';
|
||||
const ROUTE_FREE = 'https://api-free.deepl.com/';
|
||||
|
||||
/**
|
||||
* The authentication key to access the DeepL API.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $api_key;
|
||||
|
||||
/**
|
||||
* The DeepL formality option.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $formality;
|
||||
|
||||
/**
|
||||
* ID of the glossary to use.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $glossary_id;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
* @since 3.8 The option key `glossary_id` has been added.
|
||||
*
|
||||
* @param array $options {
|
||||
* The service options.
|
||||
*
|
||||
* @type string $api_key The API key.
|
||||
* @type string $formality Sets whether the translated text should lean towards formal or informal language.
|
||||
* Possible values are `'default'`, `'prefer_more'` (formal if available), and `'prefer_less'` (informal if available).
|
||||
* @type string $glossary_id Optional. ID of the glossary to use. Default is an empty string
|
||||
* }
|
||||
*
|
||||
* @phpstan-param array{
|
||||
* api_key: string,
|
||||
* formality?: DeeplFormality,
|
||||
* glossary_id?: string
|
||||
* } $options
|
||||
*/
|
||||
public function __construct( array $options ) {
|
||||
$this->api_key = $options['api_key'];
|
||||
$this->formality = $options['formality'] ?? 'default';
|
||||
$this->glossary_id = $options['glossary_id'] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a request to machine translation service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param Translations $translations Translations object.
|
||||
* @param PLL_Language $target_language Target language.
|
||||
* @param PLL_Language|null $source_language Source language, leave empty for automatic detection.
|
||||
* @return Translations|WP_Error
|
||||
*/
|
||||
public function translate( Translations $translations, PLL_Language $target_language, $source_language = null ) {
|
||||
$tr_strings = array();
|
||||
foreach ( $this->split( $translations ) as $batch ) {
|
||||
$result = $this->translate_batch( $batch, $target_language, $source_language );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
// Abort early.
|
||||
return $result;
|
||||
}
|
||||
|
||||
if ( count( $result ) !== count( $batch ) ) {
|
||||
return new WP_Error( 'pll_deepl_incomplete_response', __( 'The DeepL response is incomplete.', 'polylang-pro' ) );
|
||||
}
|
||||
|
||||
array_push( $tr_strings, ...$result );
|
||||
}
|
||||
|
||||
|
||||
foreach ( $translations->entries as &$entry ) {
|
||||
$entry->translations = (array) array_shift( $tr_strings );
|
||||
}
|
||||
|
||||
return $translations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits an array of strings into several batches manageable by DeepL API.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param Translations $translations Translations object with entries to split.
|
||||
* @return string[][] Array of arrays of strings, each ones suitable for DeepL.
|
||||
*/
|
||||
private function split( Translations $translations ): array {
|
||||
$count = 0;
|
||||
$size = 0;
|
||||
$chunk = array();
|
||||
$chunks = array();
|
||||
|
||||
foreach ( $translations->entries as $entry ) {
|
||||
$length = strlen( $entry->singular );
|
||||
|
||||
++$count;
|
||||
$size += $length;
|
||||
|
||||
/*
|
||||
* A DeepL translation request body must not exceed 128 * 1024 bytes according to the documentation.
|
||||
* {@see https://www.deepl.com/docs-api/translate-text}. We decrease this limit to 120 * 1024 bytes
|
||||
* to account for extra bytes added by the request params (100 bytes) + the JSON encoding of the array.
|
||||
*/
|
||||
if ( $count > 50 || $size > 120 * \KB_IN_BYTES ) {
|
||||
$chunks[] = $chunk;
|
||||
|
||||
$count = 0;
|
||||
$size = $length;
|
||||
$chunk = array();
|
||||
}
|
||||
|
||||
$chunk[] = $entry->singular;
|
||||
}
|
||||
|
||||
$chunks[] = $chunk; // Don't forget the last chunk.
|
||||
|
||||
return $chunks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a batch of strings to DeepL and returns their translations in the same order.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param string[] $batch Strings to translate.
|
||||
* @param PLL_Language $target_language Target language.
|
||||
* @param PLL_Language $source_language Source language, `null` for auto-detection.
|
||||
* @return string[]|WP_Error
|
||||
*/
|
||||
private function translate_batch( $batch, PLL_Language $target_language, $source_language = null ) {
|
||||
$target_code = Service::get_target_code( $target_language );
|
||||
if ( empty( $target_code ) ) {
|
||||
return new WP_Error(
|
||||
'pll_deepl_target_language_unavailable',
|
||||
sprintf(
|
||||
/* translators: %1$s is a language name, %2$s is a language locale. */
|
||||
__( '%1$s (%2$s) is not available as target language with DeepL.', 'polylang-pro' ),
|
||||
$target_language->name,
|
||||
sprintf(
|
||||
'<code>%s</code>',
|
||||
$target_language->locale
|
||||
)
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
|
||||
$body = array(
|
||||
'target_lang' => $target_code,
|
||||
'tag_handling' => 'html',
|
||||
'split_sentences' => '1',
|
||||
'formality' => $this->get_formality( $target_language ),
|
||||
'text' => $batch,
|
||||
);
|
||||
|
||||
if ( ! empty( $this->glossary_id ) ) {
|
||||
$body['glossary_id'] = $this->glossary_id;
|
||||
}
|
||||
|
||||
if ( ! empty( $source_language ) ) {
|
||||
$source_code = Service::get_source_code( $source_language );
|
||||
if ( empty( $source_code ) ) {
|
||||
return new WP_Error(
|
||||
'pll_deepl_source_language_unavailable',
|
||||
sprintf(
|
||||
/* translators: %1$s is a language name, %2$s is a language locale. */
|
||||
__( '%1$s (%2$s) is not available as source language with DeepL.', 'polylang-pro' ),
|
||||
$source_language->name,
|
||||
sprintf(
|
||||
'<code>%s</code>',
|
||||
$source_language->locale
|
||||
)
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
$body['source_lang'] = $source_code;
|
||||
}
|
||||
|
||||
$headers = array(
|
||||
'Content-Type' => 'application/json',
|
||||
);
|
||||
|
||||
$response = $this->request(
|
||||
'POST',
|
||||
'v2/translate',
|
||||
array(
|
||||
'headers' => $headers,
|
||||
'body' => wp_json_encode( $body ),
|
||||
)
|
||||
);
|
||||
|
||||
if ( $this->should_retry_with_empty_glossary( $response ) ) {
|
||||
$this->glossary_id = '';
|
||||
|
||||
return $this->translate_batch( $batch, $target_language, $source_language );
|
||||
}
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$body = json_decode( $response['body'], true );
|
||||
|
||||
if ( ! is_array( $body ) || empty( $body['translations'] ) ) {
|
||||
return new WP_Error( 'pll_deepl_no_translations', __( 'No translations have been returned by DeepL.', 'polylang-pro' ) );
|
||||
}
|
||||
|
||||
$tr_strings = array();
|
||||
foreach ( $body['translations'] as $translation ) {
|
||||
if ( isset( $translation['text'] ) ) {
|
||||
$tr_strings[] = $translation['text'];
|
||||
}
|
||||
}
|
||||
|
||||
return $tr_strings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the request to the client, and returns a response or a `WP_Error` in case of failure.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param string $method The HTTP method to use.
|
||||
* @param string $endpoint The API endpoint.
|
||||
* @param array $args {
|
||||
* The request arguments.
|
||||
*
|
||||
* @type array $headers Optional. Headers to send. Default is an empty array.
|
||||
* @type string $body Optional. A JSON-encoded string of data. Nothing is sent by default.
|
||||
* }
|
||||
* @return array|WP_Error
|
||||
*/
|
||||
private function request( string $method, string $endpoint, array $args = array() ) {
|
||||
if ( empty( $this->api_key ) ) {
|
||||
// No need to contact DeepL if the API key is empty.
|
||||
return $this->check_status_code( 403 );
|
||||
}
|
||||
|
||||
$args = array_merge_recursive(
|
||||
array(
|
||||
'headers' => array(
|
||||
'Authorization' => 'DeepL-Auth-Key ' . $this->api_key,
|
||||
),
|
||||
'method' => $method,
|
||||
),
|
||||
$args
|
||||
);
|
||||
|
||||
$response = wp_remote_request(
|
||||
$this->get_route( $endpoint ),
|
||||
$args
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$status_code_error = $this->check_status_code(
|
||||
$response['response']['code'],
|
||||
$response['body'] ?? ''
|
||||
);
|
||||
if ( $status_code_error->has_errors() ) {
|
||||
return $status_code_error;
|
||||
}
|
||||
|
||||
if ( empty( $response['body'] ) ) {
|
||||
return new WP_Error( 'pll_deepl_empty_response_body', __( 'No translations have been returned by DeepL.', 'polylang-pro' ) );
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the HTTP status code.
|
||||
*
|
||||
* @see https://github.com/DeepLcom/deepl-php/blob/v1.6.0/src/Translator.php#L691
|
||||
*
|
||||
* @since 3.6
|
||||
* @since 3.8 The parameter `body` has been added.
|
||||
*
|
||||
* @param int $code The HTTP response code.
|
||||
* @param string $body The response body.
|
||||
* @return WP_Error
|
||||
*/
|
||||
protected function check_status_code( int $code, string $body = '' ): WP_Error {
|
||||
if ( 200 === $code ) {
|
||||
return new WP_Error();
|
||||
}
|
||||
|
||||
switch ( $code ) {
|
||||
case 403:
|
||||
return new WP_Error( 'pll_deepl_authentication_failure', __( 'Authentication failure. Please check your DeepL authentication key.', 'polylang-pro' ) );
|
||||
case 456:
|
||||
return new WP_Error( 'pll_deepl_quota_exceeded', __( 'The DeepL quota for this billing period has been exceeded.', 'polylang-pro' ) );
|
||||
case 404:
|
||||
return new WP_Error( 'pll_deepl_not_found', __( 'The DeepL server cannot be reached.', 'polylang-pro' ) );
|
||||
case 400:
|
||||
if ( preg_match( '/No dictionary found for language pair [A-Za-z0-9-]+ in glossary [a-f0-9-]+/', $body ) ) {
|
||||
return new WP_Error( 'pll_deepl_no_language_pair_in_glossary', __( 'No language pair found in glossary.', 'polylang-pro' ) );
|
||||
}
|
||||
|
||||
return new WP_Error( 'pll_deepl_bad_request', __( 'Bad request.', 'polylang-pro' ) );
|
||||
case 429:
|
||||
return new WP_Error( 'pll_deepl_too_many_request', __( 'Too many requests, DeepL servers are currently experiencing high load.', 'polylang-pro' ) );
|
||||
case 500:
|
||||
case 502:
|
||||
case 503:
|
||||
return new WP_Error( 'pll_deepl_service_unavailable', __( 'DeepL service unavailable.', 'polylang-pro' ) );
|
||||
default:
|
||||
/* translators: %s is an HTTP status code */
|
||||
return new WP_Error( 'pll_deepl_unexpected_status_code', sprintf( __( 'The DeepL server sent an unexpected status code %d.', 'polylang-pro' ), $code ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells whether API key is valid.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return WP_Error An empty WP_Error if valid, a filled WP_Error otherwise.
|
||||
*/
|
||||
public function is_api_key_valid(): WP_Error {
|
||||
$response = $this->request( 'GET', 'v2/usage' );
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
if ( 200 === $response['response']['code'] ) {
|
||||
return new WP_Error();
|
||||
}
|
||||
|
||||
return $this->check_status_code( 403 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns current machine translation usage.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return array|WP_Error {
|
||||
* A `WP_Error` on error, or an array on success with the following keys.
|
||||
*
|
||||
* @type int $character_count Character count.
|
||||
* @type int $character_limit Character limiter.
|
||||
* }
|
||||
*
|
||||
* @phpstan-return array{
|
||||
* character_count: int<0, max>,
|
||||
* character_limit: int<0, max>
|
||||
* }|WP_Error
|
||||
*/
|
||||
public function get_usage() {
|
||||
$response = $this->request( 'GET', 'v2/usage' );
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
/** @var array{
|
||||
* character_count: int<0, max>,
|
||||
* character_limit: int<0, max>
|
||||
* }
|
||||
*/
|
||||
$usage = array_merge(
|
||||
array(
|
||||
'character_count' => 0,
|
||||
'character_limit' => 0,
|
||||
),
|
||||
(array) json_decode( $response['body'], true )
|
||||
);
|
||||
|
||||
if ( $usage['character_limit'] >= pow( 10, 12 ) ) {
|
||||
// Usage limit for the "unlimited" plan returns 10^12.
|
||||
$usage['character_limit'] = 0;
|
||||
}
|
||||
|
||||
return array(
|
||||
'character_count' => max( 0, (int) $usage['character_count'] ),
|
||||
'character_limit' => max( 0, (int) $usage['character_limit'] ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of glossaries.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return array|WP_Error A `WP_Error` on error, or an array on success with glossary IDs as array keys and glossary names as array values.
|
||||
*
|
||||
* @phpstan-return array<non-falsy-string, non-empty-string>|WP_Error
|
||||
*/
|
||||
public function get_glossaries() {
|
||||
$response = $this->request( 'GET', 'v3/glossaries' );
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
/** @var array{ glossaries: array<array{glossary_id: non-falsy-string, name: non-empty-string, dictionaries: list<array{source_lang: non-falsy-string, target_lang: non-falsy-string, entry_count: int<1, max>}>, creation_time: non-falsy-string}> } */
|
||||
$data = array_merge(
|
||||
array(
|
||||
'glossaries' => array(),
|
||||
),
|
||||
(array) json_decode( $response['body'], true )
|
||||
);
|
||||
|
||||
return array_column( $data['glossaries'], 'name', 'glossary_id' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the route to be used according to the DeepL plan.
|
||||
*
|
||||
* @since 3.6
|
||||
* @since 3.8 The API version (`v2` or `v3`) must be prepended to the endpoint.
|
||||
*
|
||||
* @param string $endpoint The API endpoint.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_route( string $endpoint ): string {
|
||||
return ( $this->is_free_plan() ? self::ROUTE_FREE : self::ROUTE ) . $endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the key comes from a free plan or not.
|
||||
*
|
||||
* @See https://www.deepl.com/fr/docs-api/api-access/authentication
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return bool True if the key is associated to a free plan, false otherwise.
|
||||
*/
|
||||
private function is_free_plan(): bool {
|
||||
return substr( $this->api_key, -3 ) === ':fx';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the formality according to the formality of the locale in priority.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Language $language The language object.
|
||||
* @return string
|
||||
*/
|
||||
private function get_formality( PLL_Language $language ): string {
|
||||
if ( str_ends_with( $language->locale, '_formal' ) ) {
|
||||
return 'prefer_more';
|
||||
}
|
||||
|
||||
if ( str_ends_with( $language->locale, '_informal' ) ) {
|
||||
return 'prefer_less';
|
||||
}
|
||||
|
||||
return $this->formality;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells whether to retry the request with an empty glossary.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param array|WP_Error $error The potential error. Array for valid responses.
|
||||
* @return bool
|
||||
*/
|
||||
private function should_retry_with_empty_glossary( $error ): bool {
|
||||
return is_wp_error( $error ) && 'pll_deepl_no_language_pair_in_glossary' === $error->get_error_code();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation;
|
||||
|
||||
use PLL_Export_Data;
|
||||
use Translations;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Import_Export\Services\Context;
|
||||
|
||||
/**
|
||||
* Class to store data to translation with machine translation,
|
||||
* organized by object type and object IDs respectively.
|
||||
*
|
||||
* @phpstan-import-type translationEntryRef from PLL_Export_Data
|
||||
*/
|
||||
class Data extends PLL_Export_Data {
|
||||
/**
|
||||
* Array of translated data, ordered by type and IDs.
|
||||
*
|
||||
* @var Translations[][]
|
||||
*
|
||||
* @phpstan-var array<non-falsy-string, array<int, Translations>>
|
||||
*/
|
||||
private $translations = array();
|
||||
|
||||
/**
|
||||
* Adds a source string to exported data and optionally a pre-existing translated one.
|
||||
* New types or objects are prepended to data arrays, assuming they are linked to previously added ones.
|
||||
* Once translated, this allows to import linked objects before the objects they are linked to.
|
||||
* For example, a category is imported before the post it is linked to.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $ref {
|
||||
* Array containing the content type and optionally the corresponding object ID.
|
||||
*
|
||||
* @type string $object_type Object type to be exported (e.g. `post` or `term`).
|
||||
* @type string $field_type Field type to be exported (e.g. `post_content`, `post_title`...).
|
||||
* @type int $object_id A unique identifier to retrieve the corresponding object from the database.
|
||||
* @type string $field_id Optional, a unique identifier to retrieve the corresponding field from the database.
|
||||
* @type string $encoding Optional, encoding format for the field group.
|
||||
* }
|
||||
* @param string $source The source to be translated.
|
||||
* @param string $target Optional, a preexisting translation, if any.
|
||||
* @return void
|
||||
*
|
||||
* @phpstan-param translationEntryRef $ref
|
||||
* @phpstan-param non-empty-string $source
|
||||
*/
|
||||
public function add_translation_entry( array $ref, string $source, string $target = '' ) {
|
||||
if ( ! $this->are_entry_parameters_valid( $ref, $source ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! isset( $this->translations[ $ref['object_type'] ] ) ) {
|
||||
$this->translations = array( $ref['object_type'] => array() ) + $this->translations;
|
||||
}
|
||||
|
||||
if ( ! isset( $this->translations[ $ref['object_type'] ][ $ref['object_id'] ] ) ) {
|
||||
$this->translations[ $ref['object_type'] ] = array( $ref['object_id'] => new Translations() ) + $this->translations[ $ref['object_type'] ];
|
||||
}
|
||||
|
||||
$context = Context::to_string(
|
||||
array(
|
||||
Context::FIELD => $ref['field_type'],
|
||||
Context::ID => isset( $ref['field_id'] ) ? $ref['field_id'] : '',
|
||||
Context::ENCODING => isset( $ref['encoding'] ) ? $ref['encoding'] : '',
|
||||
)
|
||||
);
|
||||
$this->translations[ $ref['object_type'] ][ $ref['object_id'] ]->add_entry(
|
||||
array(
|
||||
'singular' => $source,
|
||||
'translations' => array( $target ),
|
||||
'context' => $context,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns translated data.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @phpstan-return array<non-falsy-string, array<int, Translations>>
|
||||
*/
|
||||
public function get(): array {
|
||||
return $this->translations;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation;
|
||||
|
||||
use PLL_Model;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Deepl;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Service_Interface;
|
||||
|
||||
/**
|
||||
* Factory for machine translation services.
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
class Factory {
|
||||
/**
|
||||
* List of the service class names.
|
||||
*
|
||||
* @var string[]
|
||||
*
|
||||
* @phpstan-var non-empty-list<class-string<Service_Interface>>
|
||||
*/
|
||||
const SERVICES = array(
|
||||
Deepl::class,
|
||||
);
|
||||
|
||||
/**
|
||||
* List of the service instances.
|
||||
*
|
||||
* @var Service_Interface[]
|
||||
*
|
||||
* @phpstan-var array<non-falsy-string, Service_Interface>
|
||||
*/
|
||||
private $services = array();
|
||||
|
||||
/**
|
||||
* Stores the plugin options.
|
||||
*
|
||||
* @var \WP_Syntex\Polylang\Options\Options
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Polylang's model.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Model $model Polylang's model.
|
||||
*/
|
||||
public function __construct( PLL_Model $model ) {
|
||||
$this->options = $model->options;
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the machine translation feature is enabled.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_enabled(): bool {
|
||||
return (bool) $this->options['machine_translation_enabled'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the active service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return Service_Interface|null
|
||||
*/
|
||||
public function get_active_service() {
|
||||
foreach ( static::get_classnames() as $service ) {
|
||||
$service = $this->build_service( $service );
|
||||
|
||||
if ( $service->is_active() ) {
|
||||
return $service;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all services.
|
||||
*
|
||||
* @since 3.6
|
||||
* @return Service_Interface[]
|
||||
*/
|
||||
public function get_all(): array {
|
||||
foreach ( static::get_classnames() as $service ) {
|
||||
$this->build_service( $service );
|
||||
}
|
||||
|
||||
return $this->services;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all services classnames for static usage.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return string[]
|
||||
* @phpstan-return non-empty-list<class-string<Service_Interface>>
|
||||
*/
|
||||
public static function get_classnames(): array {
|
||||
return self::SERVICES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a service instance.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param string $class_name Service's slug.
|
||||
* @return Service_Interface
|
||||
*
|
||||
* @phpstan-param class-string<Service_Interface> $class_name
|
||||
*/
|
||||
private function build_service( string $class_name ): Service_Interface {
|
||||
$slug = $class_name::get_slug();
|
||||
|
||||
if ( ! empty( $this->services[ $slug ] ) ) {
|
||||
return $this->services[ $slug ];
|
||||
}
|
||||
|
||||
$this->services[ $slug ] = new $class_name( $this->options['machine_translation_services'][ $slug ], $this->model );
|
||||
|
||||
return $this->services[ $slug ];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation;
|
||||
|
||||
use WP_Error;
|
||||
use PLL_Settings;
|
||||
use PLL_Settings_Preview_Machine_Translation;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Factory;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* ...
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
class Module_Settings extends PLL_Settings_Preview_Machine_Translation {
|
||||
/**
|
||||
* List of all translation services' settings.
|
||||
*
|
||||
* @var Settings\Settings_Interface[]
|
||||
*/
|
||||
private $settings = array();
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Settings $polylang Polylang object.
|
||||
*/
|
||||
public function __construct( &$polylang ) {
|
||||
parent::__construct( $polylang, array( 'active_option' => 'machine_translation_enabled' ) );
|
||||
|
||||
$factory = new Factory( $polylang->model );
|
||||
|
||||
foreach ( $factory->get_all() as $slug => $service ) {
|
||||
$this->settings[ $slug ] = $service->get_settings( 'machine_translation_services[{slug}]' );
|
||||
}
|
||||
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueues scripts and styles.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function admin_enqueue_scripts() {
|
||||
$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
|
||||
|
||||
wp_enqueue_style(
|
||||
'pll_machine_translation_settings',
|
||||
plugins_url( '/css/build/machine-translation-settings' . $suffix . '.css', POLYLANG_ROOT_FILE ),
|
||||
array(),
|
||||
POLYLANG_VERSION
|
||||
);
|
||||
|
||||
wp_enqueue_script(
|
||||
'pll_machine_translation_settings',
|
||||
plugins_url( '/js/build/machine-translation-settings' . $suffix . '.js', POLYLANG_ROOT_FILE ),
|
||||
array( 'wp-url', 'wp-hooks' ),
|
||||
POLYLANG_VERSION,
|
||||
true
|
||||
);
|
||||
|
||||
wp_set_script_translations( 'pll_machine_translation_settings', 'polylang-pro' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the settings form.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function form() {
|
||||
foreach ( $this->settings as $service_settings ) {
|
||||
$service_settings->print_notices();
|
||||
|
||||
echo '<table class="form-table pll-table-top"><tbody>';
|
||||
|
||||
$service_settings->print_settings_fields();
|
||||
|
||||
echo '</tbody></table>';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the received data before saving.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $options Raw values to save.
|
||||
* @return array
|
||||
*/
|
||||
protected function prepare_raw_data( array $options ): array {
|
||||
$new_options = array(
|
||||
'machine_translation_services' => array(),
|
||||
);
|
||||
|
||||
foreach ( $this->settings as $slug => $service_settings ) {
|
||||
$service_options = $options['machine_translation_services'][ $slug ] ?? array();
|
||||
|
||||
// Is the API key provided?
|
||||
$has_api_key = $service_settings->has_api_key( $service_options );
|
||||
|
||||
$new_options['machine_translation_services'][ $slug ] = $service_options;
|
||||
|
||||
if ( ! $has_api_key ) {
|
||||
// The API key field was empty before sanitization: don't display any error messages.
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check the API key validity.
|
||||
$error = $service_settings->is_api_key_valid( $new_options['machine_translation_services'][ $slug ] );
|
||||
|
||||
if ( ! $error->has_errors() ) {
|
||||
// Valid.
|
||||
continue;
|
||||
}
|
||||
|
||||
/** @phpstan-var array{type: 'error'|'warning', message_class: string, field_id: non-falsy-string} */
|
||||
$data = array_merge(
|
||||
array(
|
||||
'type' => 'error', // Type of admin notice.
|
||||
'message_class' => '', // HTML class of the error message to display (only for types error and warning).
|
||||
'field_id' => '', // HTML id of the field.
|
||||
),
|
||||
(array) $error->get_error_data()
|
||||
);
|
||||
|
||||
/*
|
||||
* Overwrites error extra data because `pll_add_notice()` expects a string instead of an array.
|
||||
* The `pll-field-id-` prefix is used to determine which field to highlight.
|
||||
* The `pll-message-class-` prefix is used to determine which error message to show.
|
||||
*/
|
||||
$error->add_data( "notice-{$data['type']} pll-field-id-{$data['field_id']} pll-message-class-{$data['message_class']}" );
|
||||
pll_add_notice( $error );
|
||||
}
|
||||
|
||||
// Take care to return only sanitized options.
|
||||
return $new_options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Posts;
|
||||
|
||||
use WP_Error;
|
||||
use PLL_Model;
|
||||
use PLL_Language;
|
||||
use PLL_Admin_Base;
|
||||
use PLL_Admin_Links;
|
||||
use PLL_Admin_Sync;
|
||||
use PLL_Export_Container;
|
||||
use PLL_Toggle_User_Meta;
|
||||
use PLL_Export_Data_From_Posts;
|
||||
use WP_Syntex\Polylang\Capabilities\Capabilities;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Data;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Processor;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Service_Interface;
|
||||
|
||||
/**
|
||||
* Class to manage machine translation action for posts.
|
||||
*
|
||||
* @since 3.6
|
||||
* @since 3.7 Renamed from `WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Action` to `WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Posts\Action`.
|
||||
*/
|
||||
class Action {
|
||||
/**
|
||||
* Instance of the model.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
protected $model;
|
||||
|
||||
/**
|
||||
* Instance of the machine translation service.
|
||||
*
|
||||
* @var Service_Interface
|
||||
*/
|
||||
protected $service;
|
||||
|
||||
/**
|
||||
* Current language.
|
||||
*
|
||||
* @var PLL_Language|null
|
||||
*/
|
||||
protected $curlang;
|
||||
|
||||
/**
|
||||
* Instance of the machine translation processor.
|
||||
*
|
||||
* @var Processor
|
||||
*/
|
||||
protected $processor;
|
||||
|
||||
/**
|
||||
* Used to manage user meta.
|
||||
*
|
||||
* @var PLL_Toggle_User_Meta
|
||||
*/
|
||||
protected $user_meta;
|
||||
|
||||
/**
|
||||
* Whether or not a new post creation has been processed.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $done = false;
|
||||
|
||||
/**
|
||||
* Used to disable taxonomy and post meta copy.
|
||||
*
|
||||
* @var PLL_Admin_Sync
|
||||
*/
|
||||
protected $sync;
|
||||
|
||||
/**
|
||||
* @var PLL_Admin_Links|null
|
||||
*/
|
||||
protected $links;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Admin_Base $polylang The Polylang object.
|
||||
* @param Service_Interface $service Machine translation service.
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( PLL_Admin_Base $polylang, Service_Interface $service ) {
|
||||
$this->model = $polylang->model;
|
||||
$this->service = $service;
|
||||
$this->curlang = &$polylang->curlang;
|
||||
$this->sync = $polylang->sync;
|
||||
$this->links = &$polylang->links;
|
||||
$this->processor = new Processor( $polylang, $this->service->get_client() );
|
||||
$this->user_meta = new PLL_Toggle_User_Meta( sprintf( 'pll_machine_translation_%s', $this->service->get_slug() ) );
|
||||
|
||||
/*
|
||||
* Before `PLL_Duplicate::new_post_translation()`.
|
||||
*/
|
||||
add_filter( 'use_block_editor_for_post', array( $this, 'new_post_translation' ), 1900 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires the content translation.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param bool $is_block_editor Whether the post can be edited or not.
|
||||
* @return bool
|
||||
*/
|
||||
public function new_post_translation( $is_block_editor ) {
|
||||
global $post; // `$post` is the autosave of the new post.
|
||||
|
||||
if ( $this->done || empty( $post ) || empty( $this->links ) ) {
|
||||
return $is_block_editor;
|
||||
}
|
||||
|
||||
// Capability check already done in post-new.php.
|
||||
$data = $this->links->get_data_from_new_post_translation_request();
|
||||
|
||||
if ( empty( $data['new_lang'] ) || empty( $data['from_post'] ) || ! $this->user_meta->is_active() ) {
|
||||
return $is_block_editor;
|
||||
}
|
||||
|
||||
if ( ! current_user_can( 'read_post', $data['from_post'] ) ) {
|
||||
wp_die(
|
||||
esc_html__( 'Sorry, you are not allowed to read this item.', 'polylang-pro' ),
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! Capabilities::get_user()->can_translate( $data['new_lang'] ) ) {
|
||||
wp_die(
|
||||
esc_html(
|
||||
sprintf(
|
||||
/* translators: %s is a language name. */
|
||||
__( 'Sorry, you are not allowed to translate in %s.', 'polylang-pro' ),
|
||||
$data['new_lang']->name
|
||||
)
|
||||
),
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
// Prevent a second translation in the block editor.
|
||||
$this->done = true;
|
||||
|
||||
// No current language during machine translation process (to avoid filtering queries).
|
||||
$current_lang_backup = $this->curlang;
|
||||
$this->curlang = null;
|
||||
$container = new PLL_Export_Container( Data::class );
|
||||
$export_objects = new PLL_Export_Data_From_Posts( $this->model );
|
||||
|
||||
$export_objects->send_to_export( $container, array( $data['from_post'] ), $data['new_lang'] );
|
||||
|
||||
// Save translated data.
|
||||
$result = $this->processor->translate( $container );
|
||||
|
||||
// All done, set back current language.
|
||||
$this->curlang = $current_lang_backup;
|
||||
|
||||
if ( $result->has_errors() ) {
|
||||
pll_add_notice( $result );
|
||||
return $is_block_editor;
|
||||
}
|
||||
|
||||
$result = $this->processor->save( $container );
|
||||
|
||||
if ( $result->has_errors() ) {
|
||||
pll_add_notice( $result );
|
||||
return $is_block_editor;
|
||||
}
|
||||
|
||||
// Ensure global post object is updated.
|
||||
$to_post = get_post( (int) $this->model->post->get_translation( $data['from_post']->ID, $data['new_lang'] ) );
|
||||
|
||||
if ( empty( $to_post ) ) {
|
||||
// The translated post doesn't exist anymore for some reason.
|
||||
pll_add_notice(
|
||||
new WP_Error(
|
||||
'pll_machine_translation_no_translation',
|
||||
__( 'Unable to retrieve the translation.', 'polylang-pro' )
|
||||
)
|
||||
);
|
||||
return $is_block_editor;
|
||||
}
|
||||
|
||||
$post = $to_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
|
||||
|
||||
// Disable duplication.
|
||||
remove_filter( 'use_block_editor_for_post', array( $this->sync, 'new_post_translation' ), 5000 );
|
||||
add_filter( 'get_user_metadata', array( $this, 'disable_post_duplication' ), 10, 3 );
|
||||
|
||||
return $is_block_editor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the user metas to disable post duplication.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param mixed $value The value to return.
|
||||
* @param int $object_id ID of the object metadata is for.
|
||||
* @param string $meta_key Metadata key.
|
||||
* @return mixed False for the post duplication meta, the original value otherwise.
|
||||
*/
|
||||
public function disable_post_duplication( $value, $object_id, $meta_key ) {
|
||||
return 'pll_duplicate_content' === $meta_key ? false : $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Posts;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
use PLL_Base;
|
||||
use PLL_Toggle_User_Meta;
|
||||
use PLL_Metabox_User_Button;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Service_Interface;
|
||||
|
||||
/**
|
||||
* Adds a button in the languages metabox (classic editor), allowing to create a new translation by using a machine
|
||||
* translation service.
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
class Button extends PLL_Metabox_User_Button {
|
||||
/**
|
||||
* Instance of the machine translation service.
|
||||
*
|
||||
* @var Service_Interface
|
||||
*/
|
||||
protected $service;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Base $polylang Polylang object. Unused but passed by `PLL_Admin_Loader` anyway...
|
||||
* @param Service_Interface $service Machine translation service.
|
||||
*/
|
||||
public function __construct( PLL_Base $polylang, Service_Interface $service ) {
|
||||
$this->service = $service;
|
||||
$this->user_meta = new PLL_Toggle_User_Meta( sprintf( 'pll_machine_translation_%s', $this->service->get_slug() ) );
|
||||
|
||||
$args = array(
|
||||
'position' => 'before_post_translations',
|
||||
'activate' => sprintf(
|
||||
/* translators: %s is the name of the machine translation service. */
|
||||
__( 'Activate %s machine translation', 'polylang-pro' ),
|
||||
$this->service->get_name()
|
||||
),
|
||||
'deactivate' => sprintf(
|
||||
/* translators: %s is the name of the machine translation service. */
|
||||
__( 'Deactivate %s machine translation', 'polylang-pro' ),
|
||||
$this->service->get_name()
|
||||
),
|
||||
'icon' => $this->service->get_icon(),
|
||||
'priority' => 20,
|
||||
);
|
||||
|
||||
parent::__construct( 'pll-machine-translation', $args );
|
||||
|
||||
add_action( 'admin_notices', array( $this, 'display_errors' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints translation errors into the page.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function display_errors() {
|
||||
settings_errors( 'polylang' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Posts;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
use PLL_Base;
|
||||
use PLL_Toggle_User_Meta;
|
||||
use PLL_Toggle_User_Button_REST;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Service_Interface;
|
||||
|
||||
/**
|
||||
* Adds a button in the languages metabox (block editor), allowing to create a new translation by using a machine
|
||||
* translation service.
|
||||
* Exposes the pll_machine_translation user meta in the REST API.
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
class Button_REST extends PLL_Toggle_User_Button_REST {
|
||||
|
||||
/**
|
||||
* Instance of the machine translation service.
|
||||
*
|
||||
* @var Service_Interface
|
||||
*/
|
||||
private $service;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Base $polylang Polylang object. Unused but passed by `PLL_Admin_Loader` anyway...
|
||||
* @param Service_Interface $service Machine translation service.
|
||||
*/
|
||||
public function __construct( PLL_Base $polylang, Service_Interface $service ) {
|
||||
$this->service = $service;
|
||||
|
||||
parent::__construct( $polylang->model, new PLL_Toggle_User_Meta( sprintf( 'pll_machine_translation_%s', $this->service->get_slug() ) ) );
|
||||
|
||||
add_filter( 'pll_block_editor_plugin_settings', array( $this, 'get_service_settings' ) );
|
||||
add_filter( 'pll_block_editor_plugin_settings', array( $this, 'get_settings_errors' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds service properties in UI settings.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $settings UI settings.
|
||||
* @return array Updated UI settings.
|
||||
*/
|
||||
public function get_service_settings( $settings ) {
|
||||
$settings['machine_translation'] = array(
|
||||
'slug' => $this->service::get_slug(),
|
||||
'name' => $this->service->get_name(),
|
||||
'icon' => $this->service->get_icon_properties(),
|
||||
'isActive' => $this->service->is_active(),
|
||||
);
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds machine translation errors in UI settings.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $settings UI settings.
|
||||
* @return array Updated UI settings.
|
||||
*/
|
||||
public function get_settings_errors( $settings ) {
|
||||
$settings_errors = get_settings_errors( 'polylang' );
|
||||
|
||||
if ( empty( $settings_errors ) ) {
|
||||
return $settings;
|
||||
}
|
||||
|
||||
$settings['machine_translation']['errors'] = $settings_errors;
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the description of the schema for the current user meta.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return string The description of the schema.
|
||||
*/
|
||||
protected function get_schema_description(): string {
|
||||
return __( 'Whether the machine translation feature is enabled or not per post type for the current user.', 'polylang-pro' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation;
|
||||
|
||||
use PLL_Base;
|
||||
use WP_Error;
|
||||
use PLL_Admin;
|
||||
use PLL_Language;
|
||||
use PLL_Settings;
|
||||
use PLL_Import_Export;
|
||||
use PLL_Export_Container;
|
||||
use PLL_Translation_Post_Model;
|
||||
use PLL_Translation_Term_Model;
|
||||
use PLL_Translation_Strings_Model;
|
||||
use PLL_Translation_Data_Model_Interface;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Data;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Clients\Client_Interface;
|
||||
|
||||
/**
|
||||
* Class to create/update entities with translated data from machine translation.
|
||||
*/
|
||||
class Processor {
|
||||
/**
|
||||
* Manages entities translation.
|
||||
*
|
||||
* @var PLL_Translation_Data_Model_Interface[]
|
||||
*/
|
||||
private $translation_models;
|
||||
|
||||
|
||||
/**
|
||||
* Machine translation client.
|
||||
*
|
||||
* @var Client_Interface
|
||||
*/
|
||||
private $client;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Admin|PLL_Settings $polylang Polylang main object.
|
||||
* @param Client_Interface $client Machine translation client to use.
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( PLL_Base &$polylang, Client_Interface $client ) {
|
||||
$this->translation_models = array(
|
||||
PLL_Import_Export::TYPE_POST => new PLL_Translation_Post_Model( $polylang ),
|
||||
PLL_Import_Export::TYPE_TERM => new PLL_Translation_Term_Model( $polylang ),
|
||||
PLL_Import_Export::STRINGS_TRANSLATIONS => new PLL_Translation_Strings_Model(),
|
||||
);
|
||||
|
||||
$this->client = $client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates all data from the given container.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Export_Container $container Container with data to translate.
|
||||
* @return WP_Error Error object.
|
||||
*/
|
||||
public function translate( PLL_Export_Container $container ): WP_Error {
|
||||
$error = new WP_Error();
|
||||
|
||||
foreach ( $container as &$data ) {
|
||||
if ( ! $data instanceof Data ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ( $data->get() as $entities ) {
|
||||
foreach ( $entities as &$translations ) {
|
||||
$result = $this->client->translate( $translations, $data->get_target_language(), $data->get_source_language() );
|
||||
|
||||
if ( \is_wp_error( $result ) ) {
|
||||
// Abort if an error occurred.
|
||||
return $result;
|
||||
}
|
||||
|
||||
$translations = $result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves all translated data from the given container into corresponding entities.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Export_Container $container Container with data to save.
|
||||
* @return WP_Error Error object.
|
||||
*/
|
||||
public function save( PLL_Export_Container $container ): WP_Error {
|
||||
$error = new WP_Error();
|
||||
|
||||
foreach ( $container as $translations ) {
|
||||
if ( ! $translations instanceof Data ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$target_language = $translations->get_target_language();
|
||||
|
||||
foreach ( $translations->get() as $type => $entities ) {
|
||||
if ( ! isset( $this->translation_models[ $type ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$ids = array();
|
||||
foreach ( $entities as $id => $data ) {
|
||||
$entry = array(
|
||||
'id' => $id,
|
||||
'data' => $data,
|
||||
'fields' => array(
|
||||
'post_status' => 'draft',
|
||||
),
|
||||
);
|
||||
|
||||
$result = $this->translation_models[ $type ]->translate( $entry, $target_language );
|
||||
if ( is_wp_error( $result ) ) {
|
||||
$error->merge_from( $result );
|
||||
continue;
|
||||
}
|
||||
|
||||
$ids[] = $id;
|
||||
}
|
||||
|
||||
$this->translation_models[ $type ]->do_after_process( $ids, $target_language );
|
||||
|
||||
/**
|
||||
* Fires after objects have been saved with machine translated data.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Language $target_language The targeted language for import.
|
||||
* @param int[]|string[] $ids The imported object ids of the import.
|
||||
*/
|
||||
do_action( "pll_after_{$type}_machine_translation", $target_language, $ids );
|
||||
}
|
||||
}
|
||||
|
||||
return $error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
use PLL_Language;
|
||||
use PLL_Model;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Clients\Client_Interface;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Settings\Settings_Interface;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Clients\Deepl as Client;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Settings\Deepl as Settings;
|
||||
|
||||
/**
|
||||
* Machine translation service: DeepL.
|
||||
*
|
||||
* @phpstan-import-type iconProperties from Service_Interface
|
||||
* @phpstan-type DeeplFormality 'default'|'prefer_more'|'prefer_less'
|
||||
* @phpstan-type DeeplOptions array{
|
||||
* api_key: string,
|
||||
* formality: DeeplFormality,
|
||||
* glossary_id: string
|
||||
* }
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
class Deepl implements Service_Interface {
|
||||
/**
|
||||
* Service's options.
|
||||
*
|
||||
* @var array
|
||||
* @phpstan-var DeeplOptions
|
||||
*/
|
||||
private $service_options;
|
||||
|
||||
/**
|
||||
* Polylang's model.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Array of supported languages data.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @var array[]
|
||||
*/
|
||||
private static $languages = array();
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $options Service's options.
|
||||
* @param PLL_Model $model Polylang's model.
|
||||
*/
|
||||
public function __construct( array $options, PLL_Model $model ) {
|
||||
/**
|
||||
* @phpstan-var array{
|
||||
* api_key?: string,
|
||||
* formality?: DeeplFormality,
|
||||
* glossary_id?: string
|
||||
* } $options
|
||||
*/
|
||||
$this->service_options = array_merge(
|
||||
array(
|
||||
'api_key' => '',
|
||||
'formality' => 'default',
|
||||
'glossary_id' => '',
|
||||
),
|
||||
$options
|
||||
);
|
||||
$this->model = $model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the service is active.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_active(): bool {
|
||||
return ! empty( $this->service_options['api_key'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a unique identifier of the service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
public static function get_slug(): string {
|
||||
return 'deepl';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-empty-string
|
||||
*/
|
||||
public function get_name(): string {
|
||||
return 'DeepL';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the svg properties of the service's logo.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return string[] {
|
||||
* An array containing the SVG icon properties.
|
||||
*
|
||||
* @type string $width The icon width.
|
||||
* @type string $height The icon height.
|
||||
* @type string $xmlns The SVG namespace URL.
|
||||
* @type string $viewBox The position and dimension according to the SVG viewport.
|
||||
* @type string $path_d The `d` attribute of the SVG `<path>` to define the icon shape.
|
||||
* }
|
||||
* @phpstan-return iconProperties
|
||||
*/
|
||||
public function get_icon_properties(): array {
|
||||
return array(
|
||||
'width' => '20',
|
||||
'height' => '20',
|
||||
'xmlns' => 'http://www.w3.org/2000/svg',
|
||||
'viewBox' => '0 0 20 20',
|
||||
'path_d' => 'M17.407,4.133l-6.837,-3.954c-0.354,-0.206 -0.786,-0.206 -1.14,0l-6.837,3.967c-0.354,0.207 -0.57,0.584 -0.57,0.984l-0,7.921c-0,0.41 0.216,0.79 0.57,0.994l6.837,3.957c0.016,0.01 0.036,0.02 0.052,0.03l3.367,1.95l-0.01,-1.714l0.007,-0.951l0.003,0.016l0,-0.321c0,-0.19 0.099,-0.361 0.246,-0.466l0.22,-0.124l0.105,-0.059l-0.007,-0l3.994,-2.312c0.354,-0.206 0.57,-0.583 0.57,-0.993l0,-7.931c0,-0.41 -0.216,-0.787 -0.57,-0.994Zm-8.194,8.056c0.102,0.4 -0.01,0.843 -0.331,1.151c-0.456,0.446 -1.184,0.446 -1.639,-0c-0.492,-0.469 -0.492,-1.246 -0,-1.715c0.455,-0.446 1.183,-0.446 1.639,-0c0.02,0.02 0.039,0.039 0.059,0.062l2.767,-1.593l0.571,0.321l-3.066,1.774Zm4.8,-2.007c-0.456,0.446 -1.187,0.446 -1.639,0c-0.344,-0.328 -0.446,-0.809 -0.308,-1.229l-0.01,0.006l-3.122,-1.806c-0.016,0.016 -0.029,0.033 -0.045,0.046c-0.456,0.446 -1.184,0.446 -1.64,-0c-0.492,-0.469 -0.492,-1.246 0,-1.715c0.456,-0.446 1.184,-0.446 1.64,-0c0.327,0.315 0.436,0.764 0.324,1.17l3.144,1.83c0.007,-0.007 0.01,-0.01 0.017,-0.016c0.456,-0.446 1.187,-0.446 1.639,-0c0.489,0.468 0.489,1.245 0,1.714Z',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the service's logo as a svg vector.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-empty-string
|
||||
*/
|
||||
public function get_icon(): string {
|
||||
// Icon from https://www.deepl.com/press.html and modified.
|
||||
$icon_properties = $this->get_icon_properties();
|
||||
return sprintf(
|
||||
'<svg width="%s" height="%s" xmlns="%s" viewBox="%s"><path d="%s"/></svg>',
|
||||
$icon_properties['width'],
|
||||
$icon_properties['height'],
|
||||
$icon_properties['xmlns'],
|
||||
$icon_properties['viewBox'],
|
||||
$icon_properties['path_d']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the client that will be processed for the machine translation.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return Client
|
||||
*/
|
||||
public function get_client(): Client_Interface {
|
||||
return new Client( $this->service_options );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the object that will print the settings for the machine translation.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param string $input_base_name Base of the name attribute used by the inputs.
|
||||
* Can contain a placeholder `{slug}` that will be replaced by the service's slug.
|
||||
* Ex: `machine_translation_services[{slug}]`.
|
||||
* @return Settings
|
||||
*
|
||||
* @phpstan-param non-falsy-string $input_base_name
|
||||
*/
|
||||
public function get_settings( string $input_base_name ): Settings_Interface {
|
||||
return new Settings( $input_base_name, $this->service_options, $this, $this->model );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the object that holds information about the service's options.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_option_schema(): array {
|
||||
return array(
|
||||
'api_key' => array(
|
||||
'type' => 'string',
|
||||
),
|
||||
'formality' => array(
|
||||
'type' => 'string',
|
||||
'enum' => array( 'default', 'prefer_more', 'prefer_less' ),
|
||||
),
|
||||
'glossary_id' => array(
|
||||
'type' => 'string',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns machine translation service code for target language if available.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Language $language Language to check.
|
||||
* @return string Language code, empty if not available.
|
||||
*/
|
||||
public static function get_target_code( PLL_Language $language ): string {
|
||||
if ( empty( self::$languages ) ) {
|
||||
self::$languages = include POLYLANG_DIR . '/src/settings/languages.php'; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.NotAbsolutePath
|
||||
}
|
||||
|
||||
foreach ( array_merge( array( $language->locale ), $language->fallbacks ) as $locale ) {
|
||||
if ( ! empty( self::$languages[ $locale ][ static::get_slug() ] ) ) {
|
||||
return self::$languages[ $locale ][ static::get_slug() ];
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns machine translation service code for source language if available.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Language $language Language to check.
|
||||
* @return string Language code, empty if not available.
|
||||
*/
|
||||
public static function get_source_code( PLL_Language $language ): string {
|
||||
$target_code = static::get_target_code( $language );
|
||||
if ( empty( $target_code ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// If the code contains a dash (e.g., EN-US, ZH-HANS), extract the part before the dash, otherwise return the full code (2 or 3 uppercase letters).
|
||||
return explode( '-', $target_code )[0];
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Clients\Client_Interface;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Settings\Settings_Interface;
|
||||
|
||||
/**
|
||||
* Interface to use to define a machine translation service.
|
||||
*
|
||||
* @phpstan-type iconProperties array{width: non-falsy-string, height: non-falsy-string, xmlns: non-falsy-string, viewBox: non-falsy-string, path_d: non-falsy-string}
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
interface Service_Interface {
|
||||
|
||||
/**
|
||||
* Tells if the service is active.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_active(): bool;
|
||||
|
||||
/**
|
||||
* Returns a unique identifier of the service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-falsy-string
|
||||
*/
|
||||
public static function get_slug(): string;
|
||||
|
||||
/**
|
||||
* Returns the name of the service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-empty-string
|
||||
*/
|
||||
public function get_name(): string;
|
||||
|
||||
/**
|
||||
* Returns the svg properties of the service's logo.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return string[] {
|
||||
* An array containing the SVG icon properties.
|
||||
*
|
||||
* @type string $width The icon width.
|
||||
* @type string $height The icon height.
|
||||
* @type string $xmlns The SVG namespace URL.
|
||||
* @type string $viewBox The position and dimension according to the SVG viewport.
|
||||
* @type string $path_d The `d` attribute of the SVG `<path>` to define the icon shape.
|
||||
* }
|
||||
* @phpstan-return iconProperties
|
||||
*/
|
||||
public function get_icon_properties(): array;
|
||||
|
||||
/**
|
||||
* Returns the service's logo as a svg vector.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @phpstan-return non-empty-string
|
||||
*/
|
||||
public function get_icon(): string;
|
||||
|
||||
/**
|
||||
* Returns the client that will be processed for the machine translation.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return Client_Interface
|
||||
*/
|
||||
public function get_client(): Client_Interface;
|
||||
|
||||
/**
|
||||
* Returns the object that will print the settings for the machine translation.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param string $input_base_name Base of the name attribute used by the inputs.
|
||||
* Can contain a placeholder `{slug}` that will be replaced by the service's slug.
|
||||
* Ex: `machine_translation_services[{slug}]`.
|
||||
* @return Settings_Interface
|
||||
*
|
||||
* @phpstan-param non-falsy-string $input_base_name
|
||||
*/
|
||||
public function get_settings( string $input_base_name ): Settings_Interface;
|
||||
|
||||
/**
|
||||
* Returns the object that holds information about the service's options.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_option_schema(): array;
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Settings;
|
||||
|
||||
use PLL_Language;
|
||||
use PLL_Model;
|
||||
use WP_Error;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Clients\Deepl as Client;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Deepl as Service;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Machine translation settings: DeepL.
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
class Deepl implements Settings_Interface {
|
||||
/**
|
||||
* Name of the action to check the API key.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const API_KEY_ACTION = 'pll_deepl_check_api_key';
|
||||
|
||||
/**
|
||||
* Name of the action to get the DeepL usage.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const USAGE_ACTION = 'pll_deepl_get_usage';
|
||||
|
||||
/**
|
||||
* Name of the action to get the glossaries.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const GLOSSARIES_ACTION = 'pll_deepl_get_glossaries';
|
||||
|
||||
/**
|
||||
* Service.
|
||||
*
|
||||
* @var Service
|
||||
*/
|
||||
private $service;
|
||||
|
||||
/**
|
||||
* Polylang's model.
|
||||
*
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* Base of the name attribute used by the inputs.
|
||||
*
|
||||
* @var string
|
||||
*
|
||||
* @phpstan-var non-falsy-string
|
||||
*/
|
||||
private $input_base_name;
|
||||
|
||||
/**
|
||||
* Stores the fields' options.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $options;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param string $input_base_name Base of the name attribute used by the inputs.
|
||||
* Can contain a placeholder `{slug}` that will be replaced by the service's slug.
|
||||
* Ex: `machine_translation_services[{slug}]`.
|
||||
* @param array $options Service's options.
|
||||
* @param Service $service Service.
|
||||
* @param PLL_Model $model Polylang's model.
|
||||
*
|
||||
* @phpstan-param non-falsy-string $input_base_name
|
||||
*/
|
||||
public function __construct( string $input_base_name, array $options, Service $service, PLL_Model $model ) {
|
||||
$this->service = $service;
|
||||
$this->model = $model;
|
||||
$this->input_base_name = str_replace( '{slug}', $service::get_slug(), $input_base_name );
|
||||
$this->options = $options;
|
||||
|
||||
add_action( 'wp_ajax_' . self::API_KEY_ACTION, array( $this, 'check_api_key' ) );
|
||||
add_action( 'wp_ajax_' . self::USAGE_ACTION, array( $this, 'update_characters_consumption_view' ) );
|
||||
add_action( 'wp_ajax_' . self::GLOSSARIES_ACTION, array( $this, 'update_glossaries_view' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax callback that checks for the API key validity.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @phpstan-return never
|
||||
*/
|
||||
public function check_api_key() {
|
||||
check_ajax_referer( self::API_KEY_ACTION, '_pll_nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_die( -1 );
|
||||
}
|
||||
|
||||
if ( empty( $_GET['api_key'] ) || ! is_string( $_GET['api_key'] ) ) {
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html__( 'Please fill in the API key field.', 'polylang-pro' ),
|
||||
'message_class' => 'pll-message-error-auth', // See `get_error_message_class()`.
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$api_key = (string) sanitize_text_field( wp_unslash( $_GET['api_key'] ) );
|
||||
$valid = $this->is_api_key_valid( array( 'api_key' => $api_key ) );
|
||||
|
||||
if ( $valid->has_errors() ) {
|
||||
// The key is invalid or we had a failure while checking it.
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html( $valid->get_error_message() ),
|
||||
'message_class' => $this->get_error_message_class( $valid ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
wp_send_json_success();
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the characters consumption view.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @phpstan-return never
|
||||
*/
|
||||
public function update_characters_consumption_view() {
|
||||
check_ajax_referer( self::USAGE_ACTION, '_pll_nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_die( -1 );
|
||||
}
|
||||
|
||||
$usage = $this->service->get_client()->get_usage();
|
||||
|
||||
if ( is_wp_error( $usage ) ) {
|
||||
// Error while retrieving the data: display the error message.
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html(
|
||||
sprintf(
|
||||
/* translators: %s is an error message. */
|
||||
__( 'Error while retrieving the data: %s.', 'polylang-pro' ),
|
||||
$usage->get_error_message()
|
||||
)
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! $usage['character_limit'] ) {
|
||||
// The character limit is 0: display only the character count.
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'message' => esc_html(
|
||||
sprintf(
|
||||
/* translators: %s is a formatted count number. */
|
||||
_n( '%s translated character.', '%s translated characters.', $usage['character_count'], 'polylang-pro' ),
|
||||
number_format_i18n( $usage['character_count'] )
|
||||
)
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Display a graphic.
|
||||
$percent = round( $usage['character_count'] * 100 / $usage['character_limit'], 1 );
|
||||
$percent = (float) min( $percent, 100 );
|
||||
$decimals = 1;
|
||||
|
||||
if ( floor( $percent ) === $percent ) {
|
||||
$decimals = 0;
|
||||
}
|
||||
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'percent_formatted' => number_format_i18n( $percent, $decimals ) . '%',
|
||||
'percent' => (string) $percent . '%',
|
||||
'message' => esc_html(
|
||||
sprintf(
|
||||
/* translators: %1$s is a formatted count number, %2$s is a formatted limit number. */
|
||||
_n( '%1$s / %2$s translated character.', '%1$s / %2$s translated characters.', $usage['character_count'], 'polylang-pro' ),
|
||||
number_format_i18n( $usage['character_count'] ),
|
||||
number_format_i18n( $usage['character_limit'] )
|
||||
)
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the glossaries view.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @phpstan-return never
|
||||
*/
|
||||
public function update_glossaries_view() {
|
||||
check_ajax_referer( self::GLOSSARIES_ACTION, '_pll_nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_die( -1 );
|
||||
}
|
||||
|
||||
if ( isset( $_GET['api_key'] ) ) {
|
||||
$api_key = is_string( $_GET['api_key'] ) ? (string) sanitize_text_field( wp_unslash( $_GET['api_key'] ) ) : '';
|
||||
$glossaries = $this->get_new_client( $api_key )->get_glossaries();
|
||||
} else {
|
||||
$glossaries = $this->service->get_client()->get_glossaries();
|
||||
}
|
||||
|
||||
if ( is_wp_error( $glossaries ) ) {
|
||||
// Error while retrieving the data: display the error message.
|
||||
wp_send_json_error(
|
||||
array(
|
||||
'message' => esc_html(
|
||||
sprintf(
|
||||
/* translators: %s is an error message. */
|
||||
__( 'Error while retrieving the data: %s.', 'polylang-pro' ),
|
||||
$glossaries->get_error_message()
|
||||
)
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'glossaries' => $glossaries,
|
||||
'selected' => $this->options['glossary_id'],
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the given service options contain a non-empty authentication key.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $options Options for this service.
|
||||
* @return bool
|
||||
*/
|
||||
public function has_api_key( array $options ): bool {
|
||||
return ! empty( $options['api_key'] ) && is_string( $options['api_key'] ) && '' !== trim( $options['api_key'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells if the authentication key from the given service options is valid by contacting the service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $options Options for this service (must be sanitized beforehand).
|
||||
* @return WP_Error {
|
||||
* An empty `WP_Error` if the authentication succeeded.
|
||||
* In the other cases, the `WP_Error` data will contain an array as follow:
|
||||
*
|
||||
* @type string $type `'error'` if the API key is invalid, or `'warning'` if there was an error while
|
||||
* contacting the service.
|
||||
* @type string $field_id CSS ID of the field in fault.
|
||||
* }
|
||||
*/
|
||||
public function is_api_key_valid( array $options ): WP_Error {
|
||||
if ( ! $this->has_api_key( $options ) ) {
|
||||
$options['api_key'] = '';
|
||||
}
|
||||
|
||||
$error = $this->get_new_client( $options['api_key'] )->is_api_key_valid();
|
||||
|
||||
if ( ! $error->has_errors() ) {
|
||||
// The key is valid.
|
||||
return $error;
|
||||
}
|
||||
|
||||
$error->add_data(
|
||||
array(
|
||||
'message_class' => $this->get_error_message_class( $error ),
|
||||
'field_id' => 'pll-deepl-api-key',
|
||||
)
|
||||
);
|
||||
|
||||
return $error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints error notices.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function print_notices() {
|
||||
if ( $this->service->is_active() ) {
|
||||
$this->print_view(
|
||||
'inner-notices-row',
|
||||
array(
|
||||
'name' => $this->service->get_name(),
|
||||
'languages' => $this->get_unsupported_languages(),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints settings fields.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function print_settings_fields() {
|
||||
$this->print_view(
|
||||
'characters-consumption-row',
|
||||
array(
|
||||
'ajax_action' => self::USAGE_ACTION,
|
||||
)
|
||||
);
|
||||
|
||||
$this->print_view(
|
||||
'service-authentication-row',
|
||||
array(
|
||||
'ajax_action' => self::API_KEY_ACTION,
|
||||
/* translators: %s is a service name. */
|
||||
'button_label' => sprintf( __( 'Check connection to %s', 'polylang-pro' ), $this->service->get_name() ),
|
||||
'id' => 'deepl-api-key',
|
||||
'message_default' => sprintf(
|
||||
/* translators: %1$s is an opening link tag leading to account creation, %2$s is an opening link tag leading to the "API keys" page, %3$s is a closing link tag. */
|
||||
__( '%1$sCreate your account on DeepL%3$s, then %2$sfind your API key in the "API Keys & Limits" tab%3$s.', 'polylang-pro' ),
|
||||
'<a href="https://www.deepl.com/pro-api">',
|
||||
'<a href="https://www.deepl.com/your-account/keys">',
|
||||
'</a>'
|
||||
),
|
||||
'messages_error' => array(
|
||||
'pll-message-error-auth' => sprintf(
|
||||
/* translators: %1$s is an opening link tag leading to the service's "API keys" page, %2$s is a closing link tag. */
|
||||
__( '%1$sVerify your API key in the "API Keys & Limits" tab%2$s.', 'polylang-pro' ),
|
||||
'<a href="https://www.deepl.com/your-account/keys">',
|
||||
'</a>'
|
||||
),
|
||||
'pll-message-error-unavailable' => sprintf(
|
||||
/* translators: %1$s is an opening link tag leading to the service's status page, %2$s is a closing link tag. */
|
||||
__( 'You can look at %1$sthe DeepL Pro/Free API\'s status%2$s.', 'polylang-pro' ),
|
||||
'<a href="https://www.deeplstatus.com/">',
|
||||
'</a>'
|
||||
),
|
||||
),
|
||||
'message_success' => __( 'Your API key is valid.', 'polylang-pro' ),
|
||||
'option' => 'api_key',
|
||||
'title' => __( 'API key', 'polylang-pro' ),
|
||||
)
|
||||
);
|
||||
|
||||
$this->print_view(
|
||||
'deepl-formality-row',
|
||||
array(
|
||||
'option' => 'formality',
|
||||
'formal' => $this->get_active_languages_by_formality( 'formal' ),
|
||||
'informal' => $this->get_active_languages_by_formality( 'informal' ),
|
||||
)
|
||||
);
|
||||
|
||||
$this->print_view(
|
||||
'deepl-glossary-row',
|
||||
array(
|
||||
'option' => 'glossary_id',
|
||||
'ajax_action' => self::GLOSSARIES_ACTION,
|
||||
'description' => sprintf(
|
||||
/* translators: %1$s is an opening link tag, %2$s is a closing link tag. */
|
||||
__( 'Select which glossary to use for the translation process. %1$sEdit your glossaries on DeepL%2$s.', 'polylang-pro' ),
|
||||
'<a href="https://www.deepl.com/glossary">',
|
||||
'</a>'
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a view.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param string $view Name of the view.
|
||||
* @param array $atts Optional. Data to print. See views headers.
|
||||
* @return void
|
||||
*/
|
||||
private function print_view( string $view, array $atts = array() ) {
|
||||
$atts['slug'] = $this->service::get_slug();
|
||||
$atts['input_base_name'] = $this->input_base_name;
|
||||
|
||||
if ( isset( $atts['option'] ) && ! isset( $atts['value'] ) ) {
|
||||
$atts['value'] = $this->options[ $atts['option'] ] ?? '';
|
||||
}
|
||||
|
||||
include POLYLANG_PRO_DIR . "/src/modules/Machine_Translation/Views/{$view}.php";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lists of languages that are not supported by the service.
|
||||
*
|
||||
* @since 3.6
|
||||
* @return string[] Array of language names (and their locale).
|
||||
*
|
||||
* @phpstan-return list<string>
|
||||
*/
|
||||
private function get_unsupported_languages(): array {
|
||||
$languages = array();
|
||||
|
||||
foreach ( $this->model->get_languages_list() as $language ) {
|
||||
if ( empty( $this->service::get_target_code( $language ) ) ) {
|
||||
$languages[] = $this->get_language_label( $language );
|
||||
}
|
||||
}
|
||||
|
||||
sort( $languages );
|
||||
|
||||
return $languages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lists of active formal or informal languages.
|
||||
* Formal languages have a locale with a `_formal` suffix (`de_DE_formal`, `nl_NL_formal`),
|
||||
* Informal languages have a `_informal` suffix (`de_CH_informal`).
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param string $formality Formality.
|
||||
* @return string[] Array of arrays of language names (and their locale).
|
||||
*
|
||||
* @phpstan-param 'formal'|'informal' $formality
|
||||
* @phpstan-return list<string>
|
||||
*/
|
||||
private function get_active_languages_by_formality( string $formality ): array {
|
||||
$languages = array();
|
||||
|
||||
foreach ( $this->model->get_languages_list() as $language ) {
|
||||
if ( empty( $this->service::get_target_code( $language ) ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ! preg_match( "@_{$formality}$@", $language->locale ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$languages[] = $this->get_language_label( $language );
|
||||
}
|
||||
|
||||
sort( $languages );
|
||||
|
||||
return $languages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a language name and its locale.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param PLL_Language $language A language object.
|
||||
* @return string
|
||||
*/
|
||||
private function get_language_label( PLL_Language $language ): string {
|
||||
return sprintf(
|
||||
/* translators: %1$s is a language name, %2$s is a language locale. */
|
||||
_x( '%1$s (%2$s)', 'Language label', 'polylang-pro' ),
|
||||
$language->name,
|
||||
sprintf( '<code>%s</code>', $language->locale )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the HTML class corresponding to the given error.
|
||||
* See the array keys for the 'messages_error' in `print_settings_fields()`.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param WP_Error $error An error object.
|
||||
* @return string `'pll-message-error-auth'` in case of authentication failure, `'pll-message-error-unavailable'` in other cases.
|
||||
*/
|
||||
private function get_error_message_class( WP_Error $error ): string {
|
||||
return 'pll_deepl_authentication_failure' === $error->get_error_code() ? 'pll-message-error-auth' : 'pll-message-error-unavailable';
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new client instance.
|
||||
*
|
||||
* @since 3.8
|
||||
*
|
||||
* @param string $api_key The API key (must be sanitized beforehand).
|
||||
* @return Client
|
||||
*/
|
||||
private function get_new_client( string $api_key = '' ): Client {
|
||||
$service = new Service( array( 'api_key' => $api_key ), $this->model );
|
||||
return $service->get_client();
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Settings;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Machine translation settings.
|
||||
*
|
||||
* @since 3.6
|
||||
*/
|
||||
interface Settings_Interface {
|
||||
/**
|
||||
* Tells if the given service options contain a non-empty authentication key.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $options Options for this service.
|
||||
* @return bool
|
||||
*/
|
||||
public function has_api_key( array $options ): bool;
|
||||
|
||||
/**
|
||||
* Tells if the authentication key from the given service options is valid by contacting the service.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @param array $options Options for this service (must be sanitized beforehand).
|
||||
* @return WP_Error {
|
||||
* An empty `WP_Error` if the authentication succeeded.
|
||||
* In the other cases, the `WP_Error` data will contain an array as follow:
|
||||
*
|
||||
* @type string $type `'error'` if the API key is invalid, or `'warning'` if there was an error while
|
||||
* contacting the service.
|
||||
* @type string $field_id CSS ID of the field in fault.
|
||||
* }
|
||||
*/
|
||||
public function is_api_key_valid( array $options ): WP_Error;
|
||||
|
||||
/**
|
||||
* Prints error notices.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function print_notices();
|
||||
|
||||
/**
|
||||
* Prints settings fields.
|
||||
*
|
||||
* @since 3.6
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function print_settings_fields();
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polyang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Strings;
|
||||
|
||||
use WP_Error;
|
||||
use PLL_Model;
|
||||
use PLL_Language;
|
||||
use PLL_Admin_Base;
|
||||
use PLL_Admin_Strings;
|
||||
use PLL_Export_Container;
|
||||
use PLL_Strings_Form_Trait;
|
||||
use PLL_Export_Strings_Action;
|
||||
use PLL_Export_Data_From_Strings;
|
||||
use WP_Syntex\Polylang\Capabilities\Capabilities;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Data;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Processor;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Service_Interface;
|
||||
|
||||
/**
|
||||
* Class to manage the whole process of the machine translations of strings.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Action {
|
||||
use PLL_Strings_Form_Trait;
|
||||
|
||||
/**
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* @var Processor
|
||||
*/
|
||||
private $processor;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Admin_Base $polylang Instance of Polylang main object for settings page.
|
||||
* @param Service_Interface $service Instance of the machine translation service.
|
||||
*/
|
||||
public function __construct( PLL_Admin_Base $polylang, Service_Interface $service ) {
|
||||
$this->model = $polylang->model;
|
||||
$this->processor = new Processor( $polylang, $service->get_client() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Translates the strings of a given group.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Language $target_language The language to translate the strings to.
|
||||
* @param string $group The group of strings to translate.
|
||||
* @return WP_Error Error object, empty if no error.
|
||||
*/
|
||||
public function translate( PLL_Language $target_language, string $group ): WP_Error {
|
||||
$sources = PLL_Admin_Strings::get_strings();
|
||||
if ( '' !== $group ) {
|
||||
$sources = array_filter(
|
||||
$sources,
|
||||
function ( $source ) use ( $group ) {
|
||||
return $group === $source['context'];
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
$exporter = new PLL_Export_Data_From_Strings( $this->model );
|
||||
$container = new PLL_Export_Container( Data::class );
|
||||
$exporter->send_to_export(
|
||||
$container,
|
||||
$sources,
|
||||
$target_language,
|
||||
true
|
||||
);
|
||||
|
||||
$result = $this->processor->translate( $container );
|
||||
|
||||
if ( $result->has_errors() ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
return $this->processor->save( $container );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the form and translates the strings.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
* @phpstan-return never
|
||||
*/
|
||||
public function validate_form() {
|
||||
check_admin_referer( PLL_Export_Strings_Action::ACTION_NAME, PLL_Export_Strings_Action::NONCE_NAME );
|
||||
|
||||
if ( ! isset( $_POST['target-lang'], $_POST['group'] ) ) {
|
||||
$error = new WP_Error( 'pll_incomplete_form', __( 'Sorry, some data is missing from the form submission.', 'polylang-pro' ) );
|
||||
$this->display_errors( $error );
|
||||
}
|
||||
|
||||
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
|
||||
$target_languages = is_array( $_POST['target-lang'] ) ? wp_unslash( $_POST['target-lang'] ) : array();
|
||||
$target_languages = $this->get_sanitized_languages( $target_languages );
|
||||
|
||||
if ( is_wp_error( $target_languages ) ) {
|
||||
$this->display_errors( $target_languages );
|
||||
}
|
||||
|
||||
$user = Capabilities::get_user();
|
||||
foreach ( $target_languages as $target_language ) {
|
||||
$user->can_translate_or_die( $target_language );
|
||||
}
|
||||
|
||||
$group = is_string( $_POST['group'] ) ? sanitize_text_field( wp_unslash( $_POST['group'] ) ) : '';
|
||||
$group = '-1' === $group ? '' : $group;
|
||||
$errors = new WP_Error();
|
||||
|
||||
foreach ( $target_languages as $target_language ) {
|
||||
$errors->merge_from( $this->translate( $target_language, $group ) );
|
||||
}
|
||||
|
||||
$this->display_errors( $errors );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Strings;
|
||||
|
||||
use PLL_Model;
|
||||
use PLL_Settings;
|
||||
use PLL_Admin_Base;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Strings\Action;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Services\Service_Interface;
|
||||
|
||||
/**
|
||||
* Class to manage machine translation metabox for strings translations.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Metabox {
|
||||
/**
|
||||
* @var PLL_Model
|
||||
*/
|
||||
private $model;
|
||||
|
||||
/**
|
||||
* @var Action
|
||||
*/
|
||||
private $action;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param PLL_Settings $polylang Instance of Polylang main object for settings page.
|
||||
* @param Service_Interface $service Instance of the machine translation service.
|
||||
*/
|
||||
public function __construct( PLL_Settings $polylang, Service_Interface $service ) {
|
||||
$this->model = $polylang->model;
|
||||
$this->action = new Action( $polylang, $service );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the machine translations metabox.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return self Instance of the current class.
|
||||
*/
|
||||
public function init(): self {
|
||||
add_action( 'load-' . PLL_Admin_Base::get_screen_id( 'strings' ), array( $this, 'add' ) );
|
||||
|
||||
/*
|
||||
* See the hook `mlang_action_{$action}` in `PLL_Settings::handle_actions()`.
|
||||
*/
|
||||
add_action(
|
||||
'mlang_action_machine-translations',
|
||||
array( $this->action, 'validate_form' )
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the machine translation metabox.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function add() {
|
||||
if ( empty( $this->model->languages->filter( 'translator' )->filter( 'hide_default' )->get_list() ) ) {
|
||||
return;
|
||||
}
|
||||
add_meta_box(
|
||||
'pll-machine-strings-translations',
|
||||
__( 'Machine translations', 'polylang-pro' ),
|
||||
array( $this, 'render' ),
|
||||
PLL_Admin_Base::get_screen_id( 'strings' ),
|
||||
'normal'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the machine translation metabox.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function render() {
|
||||
$model = $this->model;
|
||||
include POLYLANG_PRO_DIR . '/src/modules/Machine_Translation/Views/string-form.php';
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*
|
||||
* @var array $atts {
|
||||
* @type string $ajax_action Name of the Ajax action to pass to the progress bar view to update it.
|
||||
* @type string $slug Slug of the machine translation service.
|
||||
* }
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
?>
|
||||
<tr id="pll-<?php echo esc_attr( $atts['slug'] ); ?>-data-consumption">
|
||||
<td><?php esc_html_e( 'Data used', 'polylang-pro' ); ?></td>
|
||||
<td>
|
||||
<?php
|
||||
require __DIR__ . '/progress-bar.php';
|
||||
?>
|
||||
<p class="description"> </p>
|
||||
</td>
|
||||
</tr>
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*
|
||||
* @var array $atts {
|
||||
* @type string $option Deepl `formality` option name.
|
||||
* @type string[] $formal List of language names with their locale. Can contain `<code>` tags.
|
||||
* Example array( 'Deutsch (<code>de_DE_formal</code>)', 'Nederlands (<code>nl_NL_formal</code>)').
|
||||
* @type string[] $informal List of language names with their locale. Can contain `<code>` tags.
|
||||
* Example array( 'Deutsch (<code>de_CH_informal</code>)').
|
||||
* @type string $input_base_name HTML `name` attribute of the input field.
|
||||
* @type string $value Current Deepl `formality` option value.
|
||||
* }
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
?>
|
||||
<tr id="pll-deepl-formality-label">
|
||||
<td><label for="pll-deepl-formality"><?php esc_html_e( 'Formality', 'polylang-pro' ); ?></label></td>
|
||||
<td>
|
||||
<select id="pll-deepl-formality" name="<?php echo esc_attr( $atts['input_base_name'] ); ?>[<?php echo esc_attr( $atts['option'] ); ?>]">
|
||||
<?php
|
||||
$values = array(
|
||||
'default' => _x( 'Default', 'Language formality', 'polylang-pro' ),
|
||||
'prefer_more' => __( 'Prefer formal', 'polylang-pro' ),
|
||||
'prefer_less' => __( 'Prefer informal', 'polylang-pro' ),
|
||||
);
|
||||
foreach ( $values as $value => $label ) {
|
||||
printf(
|
||||
'<option value="%s" %s>%s</option>',
|
||||
esc_attr( (string) $value ),
|
||||
selected( $atts['value'], $value, false ),
|
||||
esc_html( $label )
|
||||
);
|
||||
}
|
||||
?>
|
||||
</select>
|
||||
|
||||
<p class="description">
|
||||
<?php esc_html_e( 'Sets whether the translated text should lean on formal or informal language. Automatic fallback on the default formality if not available for the targeted language.', 'polylang-pro' ); ?>
|
||||
</p>
|
||||
|
||||
<?php
|
||||
if ( ! empty( $atts['formal'] ) ) {
|
||||
?>
|
||||
<p class="description">
|
||||
<?php
|
||||
if ( 1 === count( $atts['formal'] ) ) {
|
||||
/* translators: %s is a language name. */
|
||||
$message = __( 'Note: formal tone will always be used for %s language.', 'polylang-pro' );
|
||||
} else {
|
||||
/* translators: %s is a list of language names. */
|
||||
$message = __( 'Note: formal tone will always be used for %s languages.', 'polylang-pro' );
|
||||
}
|
||||
printf( esc_html( $message ), wp_kses( wp_sprintf_l( '%l', $atts['formal'] ), array( 'code' => array() ) ) );
|
||||
?>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
|
||||
if ( ! empty( $atts['informal'] ) ) {
|
||||
?>
|
||||
<p class="description">
|
||||
<?php
|
||||
if ( 1 === count( $atts['informal'] ) ) {
|
||||
/* translators: %s is a language name. */
|
||||
$message = __( 'Note: informal tone will always be used for %s language.', 'polylang-pro' );
|
||||
} else {
|
||||
/* translators: %s is a list of language names. */
|
||||
$message = __( 'Note: informal tone will always be used for %s languages.', 'polylang-pro' );
|
||||
}
|
||||
printf( esc_html( $message ), wp_kses( wp_sprintf_l( '%l', $atts['informal'] ), array( 'code' => array() ) ) );
|
||||
?>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
?>
|
||||
</td>
|
||||
</tr>
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*
|
||||
* @var array $atts {
|
||||
* @type string $ajax_action Name of the Ajax action to fetch the glossaries.
|
||||
* @type string $option Deepl `glossary` option name.
|
||||
* @type string $description Description displayed under the field. Can contain `<a>`, and `<code>` tags.
|
||||
* @type string $input_base_name HTML `name` attribute of the input field.
|
||||
* }
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
$tags = array(
|
||||
'a' => array( 'href' => true ),
|
||||
'code' => array(),
|
||||
);
|
||||
|
||||
?>
|
||||
<tr id="pll-deepl-glossary-label">
|
||||
<td><label for="pll-deepl-glossary"><?php esc_html_e( 'Glossary', 'polylang-pro' ); ?></label></td>
|
||||
<td>
|
||||
<?php
|
||||
printf(
|
||||
'<select id="pll-deepl-glossary" name="%s[%s]" data-action="%s" data-nonce="%s">',
|
||||
esc_attr( $atts['input_base_name'] ),
|
||||
esc_attr( $atts['option'] ),
|
||||
esc_attr( $atts['ajax_action'] ),
|
||||
esc_attr( wp_create_nonce( $atts['ajax_action'] ) )
|
||||
);
|
||||
?>
|
||||
<option value="">
|
||||
<?php
|
||||
/* translators: Empty choice for <select> box. */
|
||||
esc_html_e( '— Select —', 'polylang-pro' );
|
||||
?>
|
||||
</option>
|
||||
</select>
|
||||
<span class="spinner pll-spinner-inline"></span>
|
||||
|
||||
<p class="description"><?php echo wp_kses( $atts['description'], $tags ); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*
|
||||
* @var array $atts {
|
||||
* @type string $message Notice to display. Can contain `<br>` and `<code>` tags.
|
||||
* @type string $slug Slug of the machine translation service.
|
||||
* @type string $type Optional. Possible values are `success`, `warning`, `error`, and `info`. Default is `error`.
|
||||
* }
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
$tags = array(
|
||||
'br' => array(),
|
||||
'code' => array(),
|
||||
);
|
||||
|
||||
$atts['type'] = ! empty( $atts['type'] ) && in_array( $atts['type'], array( 'success', 'warning', 'info' ), true ) ? $atts['type'] : 'error';
|
||||
?>
|
||||
<div class="pll-<?php echo esc_attr( $atts['slug'] ); ?>-notice pll-inner-notice notice-<?php echo esc_attr( $atts['type'] ); ?>">
|
||||
<p><strong><?php echo wp_kses( $atts['message'], $tags ); ?></strong></p>
|
||||
</div>
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*
|
||||
* @var array $atts {
|
||||
* @type string $message Notice to display. Can contain `<br>` and `<code>` tags.
|
||||
* @type string $type Optional type of notice. Possible values are `success`, `warning`, `error`, and `info`. Default is `error`.
|
||||
* @type string $name Name of the machine translation service.
|
||||
* @type string[] $languages List of language names with their locale. Can contain `<code>` tags.
|
||||
* Example array( 'Afrikaans (<code>af</code>)' ).
|
||||
* }
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( ! empty( $atts['languages'] ) ) {
|
||||
$atts['type'] = 'warning';
|
||||
if ( 1 === count( $atts['languages'] ) ) {
|
||||
/* translators: %1$s is a machine translation service's name, %2$s is a language name (and its locale). */
|
||||
$atts['message'] = __( 'The following language is not available in %1$s: %2$s.', 'polylang-pro' );
|
||||
} else {
|
||||
/* translators: %1$s is a machine translation service's name, %2$s is a list of language names (and their locale). */
|
||||
$atts['message'] = __( 'The following languages are not available in %1$s: %2$s.', 'polylang-pro' );
|
||||
}
|
||||
$atts['message'] = sprintf( $atts['message'], $atts['name'], wp_sprintf_l( '%l', $atts['languages'] ) );
|
||||
|
||||
include __DIR__ . '/inner-notice.php';
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*
|
||||
* @var array $atts {
|
||||
* @type string $ajax_action Name of the Ajax action to update the progress bar.
|
||||
* }
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
printf(
|
||||
'<div class="pll-progress-bar-wrapper" data-action="%s" data-nonce="%s"><span class="spinner pll-spinner-inline"></span><div style="width: 0%%;"></div></div>',
|
||||
esc_attr( $atts['ajax_action'] ),
|
||||
esc_attr( wp_create_nonce( $atts['ajax_action'] ) )
|
||||
);
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*
|
||||
* @var array $atts {
|
||||
* @type string $ajax_action Name of the Ajax action to launch the API key check.
|
||||
* @type string $button_label Label of the button to launch the API key check
|
||||
* @type string $id Id of the HTML input field to fill the API key.
|
||||
* @type string $input_base_name Name of the HTML input field to fill the API key
|
||||
* @type string $message_default Notice displayed by default. Can contain `<a>`, and `<code>` tags.
|
||||
* @type string $message_success Notice displayed on success. Can contain `<a>`, and `<code>` tags.
|
||||
* @type string[] $messages_warning Notices displayed on error. Can contain `<a>`, and `<code>` tags.
|
||||
* @type string[] $messages_error Notices displayed on error. Can contain `<a>`, and `<code>` tags.
|
||||
* @type string $option API key option name.
|
||||
* @type string $title HTML API key option label.
|
||||
* @type string $value Current API key option value.
|
||||
* }
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
$tags = array(
|
||||
'a' => array( 'href' => true ),
|
||||
'code' => array(),
|
||||
);
|
||||
|
||||
?>
|
||||
<tr id="pll-<?php echo esc_attr( $atts['id'] ); ?>-label">
|
||||
<td>
|
||||
<label for="pll-<?php echo esc_attr( $atts['id'] ); ?>"><?php echo esc_html( $atts['title'] ); ?></label>
|
||||
</td>
|
||||
<td>
|
||||
<p>
|
||||
<?php
|
||||
printf(
|
||||
'<input id="pll-%s" name="%s[%s]" type="password" value="%s" class="regular-text code" data-name="%s"/>',
|
||||
esc_attr( $atts['id'] ),
|
||||
esc_attr( $atts['input_base_name'] ),
|
||||
esc_attr( $atts['option'] ),
|
||||
esc_attr( $atts['value'] ),
|
||||
esc_attr( $atts['option'] )
|
||||
);
|
||||
printf(
|
||||
'<button class="button button-secondary pll-ajax-button" type="button" data-action="%s" data-nonce="%s">%s</button>',
|
||||
esc_attr( $atts['ajax_action'] ),
|
||||
esc_attr( wp_create_nonce( $atts['ajax_action'] ) ),
|
||||
esc_html( $atts['button_label'] )
|
||||
);
|
||||
?>
|
||||
<span class="spinner pll-spinner-inline"></span>
|
||||
</p>
|
||||
|
||||
<?php
|
||||
/**
|
||||
* The `message_default` is shown when no AJAX call has been made yet.
|
||||
* The `message_success` is shown when the AJAX call is a success.
|
||||
* A `messages_warning`/`messages_error` is shown if the class `pll-message-shown` is added to it.
|
||||
*/
|
||||
if ( ! empty( $atts['message_default'] ) ) {
|
||||
?>
|
||||
<p class="description pll-origin-message pll-message"><?php echo wp_kses( $atts['message_default'], $tags ); ?></p>
|
||||
<?php
|
||||
}
|
||||
if ( ! empty( $atts['message_success'] ) ) {
|
||||
?>
|
||||
<p class="description pll-success-message pll-message">
|
||||
<span class="pll-icon" aria-hidden="true">✓</span>
|
||||
<?php echo wp_kses( $atts['message_success'], $tags ); ?>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
if ( ! empty( $atts['messages_warning'] ) ) {
|
||||
foreach ( $atts['messages_warning'] as $error_code => $error_message ) {
|
||||
?>
|
||||
<p class="description pll-warning-message pll-message <?php echo esc_attr( $error_code ); ?>">
|
||||
<span class="pll-icon" aria-hidden="true">✗</span>
|
||||
<span class="pll-error-message-text"></span>
|
||||
<?php echo wp_kses( $error_message, $tags ); ?>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
}
|
||||
if ( ! empty( $atts['messages_error'] ) ) {
|
||||
foreach ( $atts['messages_error'] as $error_code => $error_message ) {
|
||||
?>
|
||||
<p class="description pll-error-message pll-message <?php echo esc_attr( $error_code ); ?>">
|
||||
<span class="pll-icon" aria-hidden="true">✗</span>
|
||||
<span class="pll-error-message-text"></span>
|
||||
<?php echo wp_kses( $error_message, $tags ); ?>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
}
|
||||
?>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
/**
|
||||
* Displays the strings translations machine translation form.
|
||||
*
|
||||
* @package Polylang-Pro
|
||||
* @since 3.7
|
||||
*
|
||||
* @var PLL_Model $model `PLL_Model` instance.
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit; // Don't access directly.
|
||||
|
||||
$url = admin_url( 'admin.php?page=mlang_strings&translate=machine-translation&noheader=true' );
|
||||
$authorized_languages = $model->languages->filter( 'translator' )->filter( 'hide_default' )->get_list();
|
||||
$strings = PLL_Admin_Strings::get_strings();
|
||||
$groups = array_unique( wp_list_pluck( $strings, 'context' ) );
|
||||
?>
|
||||
<div class="form-wrap">
|
||||
<form id="machine-strings-translations" method="post" action="<?php echo esc_url( $url ); ?>">
|
||||
<div class="form-field">
|
||||
<fieldset>
|
||||
<?php wp_nonce_field( PLL_Export_Strings_Action::ACTION_NAME, PLL_Export_Strings_Action::NONCE_NAME ); ?>
|
||||
<input type="hidden" name="pll_action" value="machine-translations" />
|
||||
<legend class="pll-legend"><?php esc_html_e( 'Target languages', 'polylang-pro' ); ?></legend>
|
||||
<?php
|
||||
foreach ( $authorized_languages as $language ) {
|
||||
printf(
|
||||
'<label><input name="target-lang[]" type="checkbox" value="%1$s" /><span class="pll-translation-flag">%3$s</span>%2$s</label>',
|
||||
esc_attr( $language->slug ),
|
||||
esc_html( $language->name ),
|
||||
$language->flag // phpcs:ignore WordPress.Security.EscapeOutput
|
||||
);
|
||||
}
|
||||
?>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label for="select-groups-machine"><?php esc_html_e( 'Filter group', 'polylang-pro' ); ?></label>
|
||||
<select name="group" id="select-groups-machine">
|
||||
<option selected value="-1">
|
||||
<?php esc_html_e( 'Translate all groups', 'polylang-pro' ); ?>
|
||||
</option>
|
||||
<?php
|
||||
foreach ( $groups as $group ) {
|
||||
?>
|
||||
<option value="<?php echo esc_attr( $group ); ?>">
|
||||
<?php echo esc_html( $group ); ?>
|
||||
</option>
|
||||
<?php
|
||||
}
|
||||
?>
|
||||
</select>
|
||||
</div>
|
||||
<p class="submit">
|
||||
<button type="submit" name="action" class="button button-primary" value="translate"><?php echo esc_html__( 'Translate', 'polylang-pro' ); ?></button>
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Posts\Action as Post_Action;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Posts\Button_REST;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Machine_Translation\Strings\Metabox as Strings_Metabox;
|
||||
use WP_Syntex\Polylang_Pro\Modules\Capabilities\Mapper\Machine_Translation as Capability;
|
||||
|
||||
if ( $polylang->model->has_languages() ) {
|
||||
// Ensure dependencies are loaded.
|
||||
require_once POLYLANG_PRO_DIR . '/src/modules/Capabilities/load.php';
|
||||
require_once POLYLANG_PRO_DIR . '/src/modules/sync/load.php';
|
||||
require_once POLYLANG_PRO_DIR . '/src/modules/sync-post/load.php';
|
||||
require_once POLYLANG_DIR . '/src/modules/sync/load.php';
|
||||
|
||||
if ( current_user_can( Capability::CAPABILITY ) ) {
|
||||
$machine_translation_factory = new Machine_Translation\Factory( $polylang->model );
|
||||
|
||||
if ( $machine_translation_factory->is_enabled() ) {
|
||||
$active_service = $machine_translation_factory->get_active_service();
|
||||
|
||||
if ( $active_service && $polylang instanceof PLL_Admin ) {
|
||||
new PLL_Admin_Loader( $polylang, 'machine_translation', array( $active_service ) );
|
||||
$polylang->machine_translation_action = new Post_Action( $polylang, $active_service );
|
||||
} elseif ( $active_service && $polylang instanceof PLL_REST_Request ) {
|
||||
$polylang->machine_translation = new Button_REST( $polylang, $active_service );
|
||||
} elseif ( $active_service && $polylang instanceof PLL_Settings ) {
|
||||
$polylang->machine_translation = ( new Strings_Metabox( $polylang, $active_service ) )->init();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( $polylang instanceof PLL_Settings ) {
|
||||
add_filter(
|
||||
'pll_settings_modules',
|
||||
function ( $modules ) {
|
||||
$k = array_search( PLL_Settings_Preview_Machine_Translation::class, $modules, true );
|
||||
if ( $k ) {
|
||||
unset( $modules[ $k ] );
|
||||
$modules['machine_translation'] = Machine_Translation\Module_Settings::class;
|
||||
}
|
||||
return $modules;
|
||||
},
|
||||
100
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
defined( 'WP_UNINSTALL_PLUGIN' ) || exit;
|
||||
|
||||
delete_metadata( 'user', 0, 'pll_machine_translation_deepl', '', true );
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Modules\Site_Health;
|
||||
|
||||
/**
|
||||
* Add debug info in WP Site Health.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
class Info {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
public function __construct() {
|
||||
add_filter( 'site_status_test_php_modules', array( $this, 'site_status_test_php_modules' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires libxml and ZipArchive in Site Health.
|
||||
*
|
||||
* @since 3.7
|
||||
*
|
||||
* @param array $modules An associative array of modules to test for.
|
||||
* @return array
|
||||
*/
|
||||
public function site_status_test_php_modules( $modules ) {
|
||||
$modules['mod_xml'] = array(
|
||||
'extension' => 'libxml',
|
||||
'required' => true,
|
||||
);
|
||||
$modules['zip'] = array(
|
||||
'class' => 'ZipArchive',
|
||||
'required' => true,
|
||||
);
|
||||
return $modules;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
/**
|
||||
* Loads the site health.
|
||||
*
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Modules\Site_Health\Info;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
if ( $polylang instanceof PLL_Admin && $polylang->model->has_languages() ) {
|
||||
$polylang->site_health_pro = new Info();
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Widget_Blocks;
|
||||
|
||||
use WP_Block_Parser;
|
||||
use PLL_Frontend_Filters_Widgets;
|
||||
|
||||
/**
|
||||
* Filters widgets blocks by language on frontend.
|
||||
*
|
||||
* @since 3.1
|
||||
* @since 3.7 Formerly PLL_Frontend_Filters_Widgets_Blocks.
|
||||
*/
|
||||
class Frontend_Filters extends PLL_Frontend_Filters_Widgets {
|
||||
/**
|
||||
* Method that handles the removal of widgets in the sidebars depending on their display language.
|
||||
*
|
||||
* @since 3.1
|
||||
*
|
||||
* @param array $widget_data An array containing the widget data.
|
||||
* @param array $sidebars_widgets An associative array of sidebars and their widgets.
|
||||
* @param string $sidebar Sidebar name.
|
||||
* @param int $key Widget number.
|
||||
* @return array An associative array of sidebars and their widgets.
|
||||
*/
|
||||
public function handle_widget_in_sidebar_callback( $widget_data, $sidebars_widgets, $sidebar, $key ) {
|
||||
// Remove the widget if not visible in the current language (blocks in legacy widget).
|
||||
if ( ! empty( $widget_data['settings'][ $widget_data['number'] ]['content'] ) ) {
|
||||
$parser = new WP_Block_Parser();
|
||||
$parser->parse( $widget_data['settings'][ $widget_data['number'] ]['content'] );
|
||||
if ( is_array( $parser->output ) ) {
|
||||
foreach ( $parser->output as $output ) {
|
||||
if ( isset( $output['attrs'] ) ) {
|
||||
if ( array_key_exists( 'pll_lang', $output['attrs'] ) ) {
|
||||
$lang_to_be_displayed = $output['attrs']['pll_lang'];
|
||||
|
||||
if ( ! empty( $this->curlang ) && $this->curlang->slug !== $lang_to_be_displayed ) {
|
||||
unset( $sidebars_widgets[ $sidebar ][ $key ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $sidebars_widgets;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
namespace WP_Syntex\Polylang_Pro\Widget_Blocks;
|
||||
|
||||
/**
|
||||
* Widget editor language attribute.
|
||||
*
|
||||
* @since 3.1
|
||||
* @since 3.7 Formerly PLL_Widget_Editor_Language_Attribute.
|
||||
*/
|
||||
class Language_Attribute {
|
||||
|
||||
/**
|
||||
* Adds hooks.
|
||||
*
|
||||
* @since 3.7
|
||||
*/
|
||||
public function init(): self {
|
||||
add_filter( 'register_block_type_args', array( $this, 'add_block_attribute' ) ); // Since WP 5.5.
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Adds the 'pll_lang' attribute to an existing block.
|
||||
* Do not add the 'pll_lang' attribute if the block is a legacy widget.
|
||||
*
|
||||
* @since 3.1
|
||||
* @since 3.7.6 Removed default value (empty string) for `pll_lang`.
|
||||
*
|
||||
* @param array $block_properties Array of parameters for registering a block type.
|
||||
* Each of them becomes a property of the block type object.
|
||||
* @return array Array of modified parameters for registering a block type.
|
||||
*/
|
||||
public function add_block_attribute( $block_properties ) {
|
||||
$is_block_dynamic = $this->is_block_dynamic( $block_properties );
|
||||
$is_legacy_widget = 'core/legacy-widget' === $block_properties['name'];
|
||||
if ( $is_block_dynamic && ! $is_legacy_widget ) {
|
||||
$block_properties['attributes']['pll_lang'] = array( 'type' => 'string' );
|
||||
}
|
||||
return $block_properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the block is a dynamic one or not.
|
||||
*
|
||||
* Copied from {@see https://github.com/WordPress/wordpress-develop/blob/2382765afa36e10bf3c74420024ad4e85763a47c/src/wp-includes/class-wp-block-type.php#L261 WP_Block_Type::is_dynamic()}.
|
||||
*
|
||||
* Explanation: 'register_block_type_args' filter only passes the WP_Block_Type::name property, so the WP_Block_Type::is_dynamic() method is inaccessible in a callback function, {@see https://github.com/WordPress/WordPress/blob/5.7/wp-includes/class-wp-block-type.php#L330 }.
|
||||
* We could not use the WP_Block_Type_Registry to get the block object neither, because the WP_Block_Type instance is added to the registry only after the use of the 'register_block_type_args' filter ( done in WP_Block_Type::set_props itself done in the WP_Block_Type constructor ):
|
||||
* - {@see https://github.com/WordPress/WordPress/blob/5.7/wp-includes/class-wp-block-type.php#L223}
|
||||
* - {@see https://github.com/WordPress/WordPress/blob/5.7/wp-includes/class-wp-block-type.php#L312}
|
||||
* - {@see https://github.com/WordPress/WordPress/blob/058f9903676a7efaee534a682df0a2a8b87574d8/wp-includes/class-wp-block-type-registry.php#L80-L84}
|
||||
*
|
||||
* @since 3.1
|
||||
*
|
||||
* @param array $block_properties Associative array mimicking the structure of a {@see https://github.com/WordPress/wordpress-develop/blob/2382765afa36e10bf3c74420024ad4e85763a47c/src/wp-includes/class-wp-block-parser.php#L15 WP_Block_Parser_Block}.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_block_dynamic( $block_properties ) {
|
||||
$render_callback = $block_properties['render_callback'];
|
||||
|
||||
return is_callable( $render_callback );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Polylang-Pro
|
||||
*/
|
||||
|
||||
use WP_Syntex\Polylang_Pro\Widget_Blocks\Frontend_Filters;
|
||||
use WP_Syntex\Polylang_Pro\Widget_Blocks\Language_Attribute;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit; // Don't access directly.
|
||||
}
|
||||
|
||||
add_action(
|
||||
'pll_init',
|
||||
function ( $polylang ) {
|
||||
if ( $polylang->model->languages->has() && pll_use_block_editor_plugin() ) {
|
||||
if ( $polylang instanceof PLL_Frontend ) {
|
||||
$polylang->filters_widgets_blocks = new Frontend_Filters( $polylang );
|
||||
}
|
||||
|
||||
$polylang->widget_editor = ( new Language_Attribute() )->init();
|
||||
}
|
||||
}
|
||||
);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user