Repository navigation
Expand file tree
/
Copy pathtranslated-object.php
More file actions
666 lines (567 loc) · 19.3 KB
/
Copy pathtranslated-object.php
File metadata and controls
666 lines (567 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
<?php
/**
* @package Polylang
*/
use WP_Syntex\Polylang\Options\Options;
defined( 'ABSPATH' ) || exit;
/**
* Abstract class to use for object types that support translations.
*
* @since 1.8
*/
abstract class PLL_Translated_Object extends PLL_Translatable_Object {
/**
* Taxonomy name for the translation groups.
*
* @var string
*
* @phpstan-var non-empty-string
*/
protected $tax_translations;
/**
* Constructor.
*
* @since 1.8
*
* @param PLL_Model $model Instance of `PLL_Model`.
*/
public function __construct( PLL_Model $model ) {
parent::__construct( $model );
$this->tax_to_cache[] = $this->tax_translations;
/*
* Register our taxonomy as soon as possible.
*/
$this->register_translations_taxonomy();
}
/**
* Registers the translations taxonomy.
*
* @since 3.7
*
* @return void
*/
protected function register_translations_taxonomy(): void {
register_taxonomy(
$this->tax_translations,
(array) $this->object_type,
array(
'label' => false,
'public' => false,
'query_var' => false,
'rewrite' => false,
'_pll' => true,
'update_count_callback' => '_update_generic_term_count', // Count *all* objects to correctly detect unused terms.
)
);
$this->add_sanitization_hooks( $this->tax_translations );
}
/**
* Returns the translations group taxonomy name.
*
* @since 3.4
*
* @return string
*
* @phpstan-return non-empty-string
*/
public function get_tax_translations() {
return $this->tax_translations;
}
/**
* Assigns a language to an object, taking care of the translations group.
*
* @since 3.4
*
* @param int $id Object ID.
* @param PLL_Language|string|int $lang Language to assign to the object.
* @return bool True when successfully assigned. False otherwise (or if the given language is already assigned to
* the object).
*/
public function set_language( $id, $lang ) {
if ( ! parent::set_language( $id, $lang ) ) {
return false;
}
$id = pll_sanitize_id( $id );
$translations = $this->get_translations( $id );
// Don't create translation groups with only 1 value.
if ( ! empty( $translations ) ) {
// Remove the object's former language from the new translations group before adding the new value.
$translations = array_diff( $translations, array( $id ) );
$this->save_translations( $id, $translations );
}
return true;
}
/**
* Returns a list of object translations, given a `tax_translations` term ID.
*
* @since 3.2
*
* @param int $term_id A `tax_translations` term ID.
* @return int[] An associative array of translations with language code as key and translation ID as value.
*
* @phpstan-return array<non-empty-string, positive-int>
*/
public function get_translations_from_term_id( $term_id ) {
$term_id = pll_sanitize_id( $term_id );
if ( empty( $term_id ) ) {
return array();
}
$translations_term = get_term( $term_id, $this->tax_translations );
if ( ! $translations_term instanceof WP_Term || empty( $translations_term->description ) ) {
return array();
}
// Lang slugs as array keys, translation IDs as array values.
$translations = pll_maybe_unserialize( $translations_term->description );
$translations = is_array( $translations ) ? $translations : array();
return $this->validate_translations( $translations, 0, 'display' );
}
/**
* Saves the object's translations.
*
* @since 0.5
*
* @param int $id Object ID.
* @param int[] $translations An associative array of translations with language code as key and translation ID as value.
* @return int[] An associative array with language codes as key and object IDs as values.
*
* @phpstan-return array<non-empty-string, positive-int>
*/
public function save_translations( $id, array $translations = array() ) {
$id = pll_sanitize_id( $id );
if ( empty( $id ) ) {
return array();
}
$this->update_object_term_cache( array_merge( array( $id ), $translations ) );
$lang = $this->get_language( $id );
if ( empty( $lang ) ) {
return array();
}
// Sanitize and validate the translations array.
$translations = $this->validate_translations( $translations, $id );
// Unlink removed translations.
$old_translations = $this->get_objects_translations( $translations );
foreach ( array_diff_assoc( $old_translations, $translations ) as $tr_id ) {
$this->delete_translation( $tr_id );
}
// Check ID we need to create or update the translation group.
if ( ! $this->should_update_translation_group( $id, $translations ) ) {
return $translations;
}
$terms = $this->get_object_terms( $translations, $this->tax_translations );
$term = is_array( $terms ) && ! empty( $terms ) ? reset( $terms ) : false;
if ( empty( $term ) ) {
// Create a new term if necessary.
$result = wp_insert_term( uniqid( 'pll_' ), $this->tax_translations, array( 'description' => (string) maybe_serialize( $translations ) ) );
if ( is_wp_error( $result ) ) {
return array();
}
$group = (int) $result['term_id'];
} else {
// Take care not to overwrite extra data stored in the description field, if any.
$group = (int) $term->term_id;
$descr = pll_maybe_unserialize( $term->description );
$descr = is_array( $descr ) ? array_diff_key( $descr, $old_translations ) : array(); // Remove old translations.
$descr = array_merge( $descr, $translations ); // Add new one.
wp_update_term( $group, $this->tax_translations, array( 'description' => (string) maybe_serialize( $descr ) ) );
}
// Link all translations to the new term.
foreach ( $translations as $p ) {
wp_set_object_terms( $p, $group, $this->tax_translations );
}
// Clean now unused translation groups, except the one we just filled: its count may be stale (e.g. deferred term counting).
$terms = array_filter( $terms );
foreach ( $terms as $term ) {
// The group we just filled is never cleaned, so no need to read it again.
if ( $group === $term->term_id ) {
continue;
}
// Get fresh count value.
$term = get_term( $term->term_id, $this->tax_translations );
if ( $term instanceof WP_Term && empty( $term->count ) ) {
wp_delete_term( $term->term_id, $this->tax_translations );
}
}
return $translations;
}
/**
* Deletes a translation of an object.
*
* @since 0.5
*
* @param int $id Object ID.
* @return void
*/
public function delete_translation( $id ) {
$id = pll_sanitize_id( $id );
if ( empty( $id ) ) {
return;
}
$term = $this->get_object_term( $id, $this->tax_translations );
if ( empty( $term ) ) {
return;
}
$descr = pll_maybe_unserialize( $term->description );
if ( ! empty( $descr ) && is_array( $descr ) ) {
/*
* Search the ID to remove only among our language keys
* in case some plugin stores the same value with different key.
* Remove all keys with this ID as `get_translations()` may return
* temporarily 2 languages for the same ID (old and new language)
* when `set_language()` is called.
*/
$slugs = array_keys( $this->get_translations( $id ), $id, true );
$descr = array_diff_key( $descr, array_flip( $slugs ) );
}
if ( empty( $descr ) || ! is_array( $descr ) ) {
wp_delete_term( (int) $term->term_id, $this->tax_translations );
} else {
wp_update_term( (int) $term->term_id, $this->tax_translations, array( 'description' => (string) maybe_serialize( $descr ) ) );
}
}
/**
* Returns an array of valid translations of an object.
*
* @since 0.5
*
* @param int $id Object ID.
* @return int[] An associative array of translations with language code as key and translation ID as value.
*
* @phpstan-return array<non-empty-string, positive-int>
*/
public function get_translations( $id ) {
$id = pll_sanitize_id( $id );
if ( empty( $id ) ) {
return array();
}
return $this->get_objects_translations( array( $id ) );
}
/**
* Returns an unvalidated array of translations of an object.
* It is generally preferable to use `get_translations()`.
*
* @since 3.4
*
* @param int $id Object ID.
* @return int[] An associative array of translations with language code as key and translation ID as value.
*
* @phpstan-return array<non-empty-string, positive-int>
*/
public function get_raw_translations( $id ) {
$id = pll_sanitize_id( $id );
if ( empty( $id ) ) {
return array();
}
return $this->get_raw_objects_translations( array( $id ) )[ $id ] ?? array();
}
/**
* Returns the ID of the translation of an object.
*
* @since 0.5
*
* @param int $id Object ID.
* @param PLL_Language|string $lang Language (slug or object).
* @return int Object ID of the translation, `0` if there is none.
*
* @phpstan-return int<0, max>
*/
public function get_translation( $id, $lang ) {
$lang = $this->languages->get( $lang );
if ( empty( $lang ) ) {
return 0;
}
$translations = $this->get_translations( $id );
return $translations[ $lang->slug ] ?? 0;
}
/**
* Among the object and its translations, returns the ID of the object which is in `$lang`.
*
* @since 0.1
* @since 3.4 Returns `0` instead of `false`.
*
* @param int $id Object ID.
* @param PLL_Language|string|int $lang Language (object, slug, or term ID).
* @return int The translation object ID if exists. `0` if the passed object has no language or if not translated.
*
* @phpstan-return int<0, max>
*/
public function get( $id, $lang ) {
$id = pll_sanitize_id( $id );
if ( empty( $id ) ) {
return 0;
}
$lang = $this->languages->get( $lang );
if ( empty( $lang ) ) {
return 0;
}
$obj_lang = $this->get_language( $id );
if ( empty( $obj_lang ) ) {
return 0;
}
return $obj_lang->term_id === $lang->term_id ? $id : $this->get_translation( $id, $lang );
}
/**
* Checks if a user can synchronize translations.
*
* @since 2.6
*
* @param int $id Object ID.
* @return bool
*/
public function current_user_can_synchronize( $id ) {
$id = pll_sanitize_id( $id );
if ( empty( $id ) ) {
return false;
}
/**
* Filters whether a synchronization capability check should take place.
*
* @since 2.6
*
* @param bool|null $check Null to enable the capability check,
* true to always allow the synchronization,
* false to always disallow the synchronization.
* Defaults to true.
* @param int $id The synchronization source object ID.
*/
$check = apply_filters( "pll_pre_current_user_can_synchronize_{$this->type}", true, $id );
if ( null !== $check ) {
return (bool) $check;
}
if ( ! current_user_can( "edit_{$this->type}", $id ) ) {
return false;
}
foreach ( $this->get_translations( $id ) as $tr_id ) {
if ( $tr_id !== $id && ! current_user_can( "edit_{$this->type}", $tr_id ) ) {
return false;
}
}
return true;
}
/**
* Tells whether a translation term must be updated.
*
* @since 2.3
*
* @param int $id Object ID.
* @param int[] $translations An associative array of translations with language code as key and translation ID as
* value. Make sure to sanitize this.
* @return bool
*
* @phpstan-param array<non-empty-string, positive-int> $translations
*/
protected function should_update_translation_group( $id, $translations ) {
return count( $translations ) > 1;
}
/**
* Returns an array of valid translations for multiple objects.
*
* @since 3.8
*
* @param int[] $object_ids Array of object IDs.
* @return int[] An associative array of translations with language code as key and translation ID as value.
*
* @phpstan-return array<non-empty-string, positive-int>
*/
protected function get_objects_translations( array $object_ids ) {
$translations_arrays = $this->get_raw_objects_translations( $object_ids );
$validated = array();
foreach ( $translations_arrays as $id => $translations ) {
$validated = array_merge( $validated, $this->validate_translations( $translations, $id, 'display' ) );
}
return $validated;
}
/**
* Returns an unvalidated array of translations for multiple objects.
* It is generally preferable to use `get_objects_translations()`.
*
* @since 3.8
*
* @param int[] $object_ids Array of object IDs.
* @return int[][] An array of an associative array of translations with language code as key and translation ID as value.
* First level key is the id of the object that translations are related to.
*
* @phpstan-return array<int,array<non-empty-string, positive-int>>
*/
protected function get_raw_objects_translations( array $object_ids ) {
$terms = $this->get_object_terms( $object_ids, $this->tax_translations );
$translations = array();
foreach ( $object_ids as $id ) {
if ( empty( $terms[ $id ] ) || empty( $terms[ $id ]->description ) ) {
$translations[ $id ] = array();
continue;
}
$trans = pll_maybe_unserialize( $terms[ $id ]->description );
$translations[ $id ] = is_array( $trans ) ? $trans : array();
}
return $translations;
}
/**
* Validates and sanitizes translations.
* This will:
* - Make sure to return only translations in existing languages (and only translations).
* - Sanitize the values.
* - Make sure the provided translation (`$id`) is in the list.
* - Check that the translated objects are in the right language, if `$context` is set to 'save'.
*
* @since 3.1
* @since 3.2 Doesn't return `0` ID values.
* @since 3.2 Added parameters `$id` and `$context`.
*
* @param int[] $translations An associative array of translations with language code as key and translation ID as
* value.
* @param int $id Optional. The object ID for which the translations are validated. When provided, the
* process makes sure it is added to the list. Default 0.
* @param string $context Optional. The operation for which the translations are validated. When set to
* 'save', a check is done to verify that the IDs and langs correspond.
* 'display' should be used otherwise. Default 'save'.
* @return int[]
*
* @phpstan-param non-empty-string $context
* @phpstan-return array<non-empty-string, positive-int>
*/
protected function validate_translations( $translations, $id = 0, $context = 'save' ) {
if ( ! is_array( $translations ) ) {
$translations = array();
}
/**
* Remove translations in non-existing languages, and non-translation data (we allow plugins to store other
* information in the array).
*/
$translations = array_intersect_key(
$translations,
array_flip( $this->languages->get_list( array( 'fields' => 'slug' ) ) )
);
// Make sure values are clean before working with them.
/** @phpstan-var array<non-empty-string, positive-int> $translations */
$translations = pll_sanitize_ids( $translations );
if ( 'save' === $context ) {
/**
* Check that the translated objects are in the right language.
* For better performance, this should be done only when saving the data into the database, not when
* retrieving data from it.
*/
$valid_translations = array();
foreach ( $translations as $lang_slug => $tr_id ) {
$tr_lang = $this->get_language( $tr_id );
if ( ! empty( $tr_lang ) && $tr_lang->slug === $lang_slug ) {
$valid_translations[ $lang_slug ] = $tr_id;
}
}
$translations = $valid_translations;
}
$id = pll_sanitize_id( $id );
if ( empty( $id ) ) {
return $translations;
}
// Make sure to return at least the passed object in its translation array.
$lang = $this->get_language( $id );
if ( empty( $lang ) ) {
return $translations;
}
/** @phpstan-var array<non-empty-string, positive-int> $translations */
return array_merge( array( $lang->slug => $id ), $translations );
}
/**
* Creates translations groups in mass.
*
* @since 1.6.3
* @since 3.4 Moved from PLL_Admin_Model class. The `$type` parameter is removed.
* @since 3.8 The name of the translation terms can be customized.
*
* @param int[][] $translations Array of translations arrays. The keys of the first level array can be used to
* customize the name of the translation terms. Example:
* array(
* 'pll_term_name_1' => array(
* 'lang_slug_1' => {object ID},
* 'lang_slug_2' => {object ID},
* )
* )
* @return void
*
* @phpstan-param array<array<string,int>> $translations
*/
public function set_translation_in_mass( $translations ) {
global $wpdb;
$terms = array();
$slugs = array();
$description = array();
$count = array();
foreach ( $translations as $k => $t ) {
$term = is_string( $k ) ? $k : uniqid( 'pll_' ); // The term name.
$terms[] = array( $term, $term );
$slugs[] = $term;
$description[ $term ] = maybe_serialize( $t );
$count[ $term ] = count( $t );
}
// Insert terms.
if ( ! empty( $terms ) ) {
$wpdb->query(
$wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
sprintf(
"INSERT INTO {$wpdb->terms} ( slug, name ) VALUES %s",
implode( ',', array_fill( 0, count( $terms ), '( %s, %s )' ) )
),
array_merge( ...$terms )
)
);
}
// Get all terms with their term_id.
$terms = $wpdb->get_results(
$wpdb->prepare(
sprintf(
"SELECT term_id, slug FROM {$wpdb->terms} WHERE slug IN (%s)",
implode( ',', array_fill( 0, count( $slugs ), '%s' ) )
),
$slugs
)
);
$term_ids = array();
$tts = array();
// Prepare terms taxonomy relationship.
foreach ( $terms as $term ) {
$term_ids[] = $term->term_id;
$tts[] = array( $term->term_id, $this->tax_translations, $description[ $term->slug ], $count[ $term->slug ] );
}
// Insert term_taxonomy.
if ( ! empty( $tts ) ) {
$wpdb->query(
$wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
sprintf(
"INSERT INTO {$wpdb->term_taxonomy} ( term_id, taxonomy, description, count ) VALUES %s",
implode( ',', array_fill( 0, count( $tts ), '( %d, %s, %s, %d )' ) )
),
array_merge( ...$tts )
)
);
}
// Get all terms with term_taxonomy_id.
$terms = get_terms( array( 'taxonomy' => $this->tax_translations, 'hide_empty' => false ) );
$trs = array();
// Prepare objects relationships.
if ( is_array( $terms ) ) {
foreach ( $terms as $term ) {
$t = pll_maybe_unserialize( $term->description );
if ( is_array( $t ) && in_array( $t, $translations ) ) {
foreach ( $t as $object_id ) {
if ( ! empty( $object_id ) ) {
$trs[] = array( $object_id, $term->term_taxonomy_id );
}
}
}
}
}
// Insert term_relationships.
if ( ! empty( $trs ) ) {
$wpdb->query(
$wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
sprintf(
"INSERT INTO {$wpdb->term_relationships} ( object_id, term_taxonomy_id ) VALUES %s",
implode( ',', array_fill( 0, count( $trs ), '( %d, %d )' ) )
),
array_merge( ...$trs )
)
);
}
clean_term_cache( $term_ids, $this->tax_translations );
}
}