Weglot Translate – Translate your WP website - Version 1.12

Version Description

(03/05/2018) = * Bugfix : undefined index on ajax call * Bugfix : Redirection checkout payment on WooCommerce * Bugfix : Register widget * Add option for AMP compatibility * Add filter for dynamic string

Download this release

Release Info

Developer remyb92
Plugin Icon 128x128 Weglot Translate – Translate your WP website
Version 1.12
Comparing to
See all releases

Code changes from version 1.11 to 1.12

includes/wg-settings-page.php CHANGED
@@ -2,16 +2,17 @@
2
 
3
  use Weglot\Helpers\WeglotUtils;
4
  use Weglot\Helpers\WeglotLang;
 
5
 
6
  $showRTL = false;
7
  $showLTR = false;
8
 
9
- if (WeglotUtils::isLanguageRTL($this->original_l)) { // Right lo left language
10
- if (WeglotUtils::hasLanguageLTR(explode(',', $this->destination_l))) {
11
  $showLTR = true;
12
  }
13
  } else { // Left to right language
14
- if (WeglotUtils::hasLanguageRTL(explode(',', $this->destination_l))) {
15
  $showRTL = true;
16
  }
17
  } ?>
@@ -93,8 +94,8 @@ if (WeglotUtils::isLanguageRTL($this->original_l)) { // Right lo left language
93
  name="destination_l">
94
  <?php foreach (WeglotLang::getCodeLangs() as $code): ?>
95
  <option <?php if (strpos(esc_attr(get_option('destination_l')), $code) !== false) {
96
- echo 'selected';
97
- } ?> value="<?php echo $code ?>"><?php echo esc_html(WeglotLang::getStrLangByCode($code)); ?></option>
98
  <?php endforeach; ?>
99
  </select>
100
  </div>
@@ -325,28 +326,50 @@ color: blue!important;
325
  </td>
326
  </tr>
327
  </table>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  <?php if ($this->userInfo['plan'] > 0) {
329
- ?>
330
- <h3 style="border-bottom:1px solid #c0c0c0;padding-bottom:10px;max-width:800px;margin-top:40px;">
331
- <?php
332
- echo esc_html__('Other options', 'weglot') . ' ' . esc_html__('(Optional)', 'weglot'); ?>
333
- </h3>
334
- <table class="form-table">
335
- <tr valign="top">
336
- <th scope="row"><?php esc_html_e('Auto redirect?', 'weglot'); ?></th>
337
- <td><input id="id_auto_switch" type="checkbox"
338
- name="wg_auto_switch"
339
- <?php
340
- if (esc_attr(get_option('wg_auto_switch')) == 'on') {
341
- echo 'checked';
342
- } ?>
343
- /><label for="id_auto_switch"
344
- style="font-weight: normal;margin-left: 20px;font-style: italic;display: inline-block;"><?php esc_html_e('Check if you want to redirect users based on their browser language.', 'weglot'); ?></label>
345
- </td>
346
- </tr>
347
- </table>
348
  <?php
349
  } ?>
 
350
  <?php
351
  if ($showLTR || $showRTL) {
352
  $ltrOrRtl = $showLTR ? esc_html__('Left to Right languages', 'weglot') : esc_html__('Right to Left languages', 'weglot'); ?>
@@ -392,5 +415,5 @@ text-align: right;
392
  style="font-size : 17px;"></i>
393
  <p style="display:inline-block; margin-left:5px;"><?php echo sprintf(esc_html__('If you need any help, you can contact us via our live chat at %1$sweglot.com%2$s or email us at support@weglot.com.', 'weglot'), '<a href="https://weglot.com/" target="_blank">', '</a>') . '<br>' . sprintf(esc_html__('You can also check our %1$sFAQ%2$s', 'weglot'), '<a href="http://support.weglot.com/" target="_blank">', '</a>'); ?></p>
394
  <br><br><br>
395
- <h2></h2>
396
  </div>
2
 
3
  use Weglot\Helpers\WeglotUtils;
4
  use Weglot\Helpers\WeglotLang;
5
+ use Weglot\WeglotContext;
6
 
7
  $showRTL = false;
8
  $showLTR = false;
9
 
10
+ if (WeglotUtils::isLanguageRTL(WeglotContext::getOriginalLanguage())) { // Right lo left language
11
+ if (WeglotUtils::hasLanguageLTR(explode(',', WeglotContext::getDestinationLanguage()))) {
12
  $showLTR = true;
13
  }
14
  } else { // Left to right language
15
+ if (WeglotUtils::hasLanguageRTL(explode(',', WeglotContext::getDestinationLanguage()))) {
16
  $showRTL = true;
17
  }
18
  } ?>
94
  name="destination_l">
95
  <?php foreach (WeglotLang::getCodeLangs() as $code): ?>
96
  <option <?php if (strpos(esc_attr(get_option('destination_l')), $code) !== false) {
97
+ echo 'selected';
98
+ } ?> value="<?php echo $code ?>"><?php echo esc_html(WeglotLang::getStrLangByCode($code)); ?></option>
99
  <?php endforeach; ?>
100
  </select>
101
  </div>
326
  </td>
327
  </tr>
328
  </table>
329
+ <?php
330
+ $classHideOption = "hidden-option";
331
+ if ($this->userInfo['plan'] > 0) {
332
+ $classHideOption = "";
333
+ }
334
+ ?>
335
+ <h3 class="<?php echo $classHideOption; ?>" style="border-bottom:1px solid #c0c0c0;padding-bottom:10px;max-width:800px;margin-top:40px;">
336
+ <?php
337
+ echo esc_html__('Other options', 'weglot') . ' ' . esc_html__('(Optional)', 'weglot'); ?>
338
+ </h3>
339
+ <table class="form-table <?php echo $classHideOption; ?>">
340
+ <tr valign="top" class="hidden-option">
341
+ <th scope="row"><?php esc_html_e('Exclude AMP pages ?', 'weglot'); ?></th>
342
+ <td><input id="id_exclude_amp" type="checkbox"
343
+ name="wg_exclude_amp"
344
+ <?php
345
+ if (esc_attr(get_option('wg_exclude_amp', 'on')) == 'on') {
346
+ echo 'checked';
347
+ } ?>
348
+ /><label for="id_exclude_amp"
349
+ style="font-weight: normal;margin-left: 20px;font-style: italic;display: inline-block;"><?php esc_html_e('Exclude translation for Accelerated Mobile Pages. Default : On', 'weglot'); ?></label>
350
+ </td>
351
+ </tr>
352
+
353
  <?php if ($this->userInfo['plan'] > 0) {
354
+ ?>
355
+
356
+
357
+ <tr valign="top">
358
+ <th scope="row"><?php esc_html_e('Auto redirect?', 'weglot'); ?></th>
359
+ <td><input id="id_auto_switch" type="checkbox"
360
+ name="wg_auto_switch"
361
+ <?php
362
+ if (esc_attr(get_option('wg_auto_switch')) == 'on') {
363
+ echo 'checked';
364
+ } ?>
365
+ /><label for="id_auto_switch"
366
+ style="font-weight: normal;margin-left: 20px;font-style: italic;display: inline-block;"><?php esc_html_e('Check if you want to redirect users based on their browser language.', 'weglot'); ?></label>
367
+ </td>
368
+ </tr>
369
+
 
 
 
370
  <?php
371
  } ?>
372
+ </table>
373
  <?php
374
  if ($showLTR || $showRTL) {
375
  $ltrOrRtl = $showLTR ? esc_html__('Left to Right languages', 'weglot') : esc_html__('Right to Left languages', 'weglot'); ?>
415
  style="font-size : 17px;"></i>
416
  <p style="display:inline-block; margin-left:5px;"><?php echo sprintf(esc_html__('If you need any help, you can contact us via our live chat at %1$sweglot.com%2$s or email us at support@weglot.com.', 'weglot'), '<a href="https://weglot.com/" target="_blank">', '</a>') . '<br>' . sprintf(esc_html__('You can also check our %1$sFAQ%2$s', 'weglot'), '<a href="http://support.weglot.com/" target="_blank">', '</a>'); ?></p>
417
  <br><br><br>
418
+
419
  </div>
includes/wg-status-page.php ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ <?php
3
+ use Weglot\WeglotContext;
4
+
5
+ $apacheModRewrite = ' <mark class="yes"><span class="dashicons dashicons-yes"></span></mark>';
6
+ if (!function_exists('apache_get_modules')) {
7
+ $apacheModRewrite = 'Unknown';
8
+ } elseif (!in_array('mod_rewrite', apache_get_modules())) {
9
+ $apacheModRewrite = '<mark class="error"><span class="dashicons dashicons-warning"></span></mark>';
10
+ }
11
+
12
+ $phpMin56 = true;
13
+ if (version_compare(phpversion(), "5.6", "<")) {
14
+ $phpMin56 = false;
15
+ }
16
+
17
+ ?>
18
+
19
+ <script>
20
+ jQuery(document).ready(function(){
21
+ jQuery("#system-report").on("click", function(e){
22
+ e.preventDefault();
23
+
24
+ jQuery("#view-system-report").slideToggle();
25
+ })
26
+ })
27
+ </script>
28
+
29
+ <div class="wrap">
30
+ <button class="button" id="system-report">
31
+ <?php _e("Get system report", "weglot"); ?>
32
+ </button>
33
+ <div id="view-system-report" style="display:none";>
34
+ <textarea readonly="readonly" style="width:100%; min-height:300px;">
35
+ ## WordPress environment
36
+
37
+ Home URL: <?php echo home_url() . "\n"; ?>
38
+ Site URL: <?php echo site_url() . "\n"; ?>
39
+ Weglot version: <?php echo WEGLOT_VERSION . "\n" ?>
40
+ WP version: <?php echo get_bloginfo('version') . "\n"; ?>
41
+ WP multisite: <?php echo is_multisite() ? "Yes\n" :"-\n" ?>
42
+ WP debug mode: <?php echo (defined(WP_DEBUG)) ? "Yes\n" : "-\n"; ?>
43
+ Permalink structure: <?php echo get_option('permalink_structure') . "\n"; ?>
44
+ Language: <?php echo get_locale() . "\n"; ?>
45
+
46
+ ## Server environment
47
+
48
+ Server info: <?php echo (isset($_SERVER['SERVER_SOFTWARE'])) ? $_SERVER['SERVER_SOFTWARE'] . "\n" : "Unknown\n" ?>
49
+ PHP version: <?php echo phpversion() . "\n"; ?>
50
+ Module mod_rewrite: <?php echo $apacheModRewrite . "\n"; ?>
51
+
52
+ ## Weglot environment
53
+
54
+ Original Language: <?php echo WeglotContext::getOriginalLanguage() . "\n"; ?>
55
+ Destination Language: <?php echo WeglotContext::getDestinationLanguage() . "\n"; ?>
56
+ Exclude URLs: <?php echo get_option('exclude_url') . "\n"; ?>
57
+ Exclude blocks: <?php echo get_option('exclude_blocks') . "\n"; ?>
58
+ </textarea>
59
+ </div>
60
+ <br />
61
+ <br />
62
+ <table class="widefat" cellspacing="0" id="status">
63
+ <thead>
64
+ <tr>
65
+ <th colspan="3" data-export-label="WordPress Environment"><h2>WordPress environment</h2></th>
66
+ </tr>
67
+ </thead>
68
+ <tbody>
69
+ <tr>
70
+ <td>Home URL:</td>
71
+ <td><?php echo home_url(); ?></td>
72
+ </tr>
73
+ <tr>
74
+ <td>Site URL:</td>
75
+ <td><?php echo site_url(); ?></td>
76
+ </tr>
77
+ <tr>
78
+ <td>Weglot version:</td>
79
+ <td><?php echo WEGLOT_VERSION ?></td>
80
+ </tr>
81
+ <tr>
82
+ <td>WP version:</td>
83
+ <td><?php echo get_bloginfo('version'); ?></td>
84
+ </tr>
85
+ <tr>
86
+ <td>WP multisite:</td>
87
+ <td>
88
+ <?php echo is_multisite() ? "Yes" :"-" ?>
89
+
90
+ </td>
91
+ </tr>
92
+ <tr>
93
+ <td>WP debug mode:</td>
94
+ <td>
95
+ <?php if (defined(WP_DEBUG) && WP_DEBUG) {
96
+ ?>
97
+ <mark class="yes"><span class="dashicons dashicons-yes"></span></mark>
98
+ <?php
99
+ } ?>
100
+ </td>
101
+ </tr>
102
+ <tr>
103
+ <td>Permalink structure:</td>
104
+ <td><?php echo get_option('permalink_structure'); ?></td>
105
+ </tr>
106
+ <tr>
107
+ <td>Language:</td>
108
+ <td><?php echo get_locale(); ?></td>
109
+ </tr>
110
+ </tbody>
111
+ </table>
112
+ <br />
113
+ <table class="widefat" cellspacing="0">
114
+ <thead>
115
+ <tr>
116
+ <th colspan="3" data-export-label="Server Environment"><h2>Server environment</h2></th>
117
+ </tr>
118
+ </thead>
119
+ <tbody>
120
+ <tr>
121
+ <td>Server info:</td>
122
+ <td><?php echo (isset($_SERVER['SERVER_SOFTWARE'])) ? $_SERVER['SERVER_SOFTWARE'] : "Unknown" ?></td>
123
+ </tr>
124
+ <tr>
125
+ <td>PHP version:</td>
126
+ <td>
127
+ <?php echo phpversion(); ?>
128
+ <?php if (!$phpMin56) {
129
+ ?>
130
+ <mark class="error">
131
+ <span class="dashicons dashicons-warning"></span> - <?php echo __("We recommend a minimum PHP version of 5.6.", "weglot") ?>
132
+ </mark>
133
+ <?php
134
+ } ?>
135
+ </td>
136
+ </tr>
137
+ <tr>
138
+ <td>Module mod_rewrite:</td>
139
+ <td>
140
+ <?php echo $apacheModRewrite; ?>
141
+ </td>
142
+ </tr>
143
+ </tbody>
144
+ </table>
145
+ <br />
146
+ <table class="widefat" cellspacing="0">
147
+ <thead>
148
+ <tr>
149
+ <th colspan="3" data-export-label="Server Environment"><h2>Weglot environment</h2></th>
150
+ </tr>
151
+ </thead>
152
+ <tbody>
153
+ <tr>
154
+ <td>Original Language:</td>
155
+ <td><?php echo WeglotContext::getOriginalLanguage(); ?></td>
156
+ </tr>
157
+ <tr>
158
+ <td>Destination Language:</td>
159
+ <td><?php echo WeglotContext::getDestinationLanguage(); ?></td>
160
+ </tr>
161
+ <tr>
162
+ <td>Exclude URLs:</td>
163
+ <td><?php echo get_option('exclude_url'); ?></td>
164
+ </tr>
165
+ <tr>
166
+ <td>Exclude blocks:</td>
167
+ <td><?php echo get_option('exclude_blocks'); ?></td>
168
+ </tr>
169
+ </tbody>
170
+ </table>
171
+ </div>
readme.txt CHANGED
@@ -4,7 +4,7 @@ Tags: translate,translation,language,multilingual,bilingual,international,locali
4
  Requires at least: 4.5
5
  Tested up to: 4.9
6
  Requires PHP: 5.3
7
- Stable tag: 1.11
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
@@ -152,12 +152,19 @@ See changelog for upgrade changes.
152
 
153
  == Changelog ==
154
 
155
- = 1.11 (05/04/2018) =
 
 
 
 
 
 
 
156
  * Add new languages
157
  * Add new filters
158
  * Add Yoast Premium compatibility on redirect
159
  * Bugfix : Exclusion AMP
160
- * Bugfix : Redirection checkout order on WooCommerce
161
 
162
  = 1.10 =
163
  * Add new languages + add Oman flag
@@ -422,4 +429,4 @@ See changelog for upgrade changes.
422
  * Fix LTR CSS, api v2 transmit strings type, fix regex escaping
423
 
424
  = 0.40 =
425
- * Add PDF translate, fix simple dom limit, uninstall hook, no &lt;/body&gt; case.
4
  Requires at least: 4.5
5
  Tested up to: 4.9
6
  Requires PHP: 5.3
7
+ Stable tag: 1.12
8
  License: GPLv2 or later
9
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
 
152
 
153
  == Changelog ==
154
 
155
+ = 1.12 (03/05/2018) =
156
+ * Bugfix : undefined index on ajax call
157
+ * Bugfix : Redirection checkout payment on WooCommerce
158
+ * Bugfix : Register widget
159
+ * Add option for AMP compatibility
160
+ * Add filter for dynamic string
161
+
162
+ = 1.11 (05/04/2018) =
163
  * Add new languages
164
  * Add new filters
165
  * Add Yoast Premium compatibility on redirect
166
  * Bugfix : Exclusion AMP
167
+ * Bugfix : Redirection checkout order on WooCommerce
168
 
169
  = 1.10 =
170
  * Add new languages + add Oman flag
429
  * Fix LTR CSS, api v2 transmit strings type, fix regex escaping
430
 
431
  = 0.40 =
432
+ * Add PDF translate, fix simple dom limit, uninstall hook, no &lt;/body&gt; case.
resources/wp-weglot-admin-css.css CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  .wg-widget-option-form {
2
  width : 60%;
3
  display : inline-block;
@@ -197,4 +200,4 @@
197
  height: 50px;
198
  padding: 0 30px!important;
199
  font-size: 16px;
200
- }
1
+ .hidden-option{
2
+ display:none;
3
+ }
4
  .wg-widget-option-form {
5
  width : 60%;
6
  display : inline-block;
200
  height: 50px;
201
  padding: 0 30px!important;
202
  font-size: 16px;
203
+ }
src/Client/WeglotClient.php CHANGED
@@ -11,6 +11,7 @@ class WeglotClient
11
 
12
  const API_BASE = 'https://api.weglot.com';
13
  const API_BASE_OLD = 'https://weglot.com/api/';
 
14
 
15
  public function __construct($key)
16
  {
@@ -387,7 +388,7 @@ class WeglotClient
387
  ),
388
  );
389
 
390
- $elements_to_check = apply_filters("weglot_elements_to_check" , $elements_to_check);
391
 
392
  foreach ($elements_to_check as $key => $elem) {
393
  foreach ($html->find($key) as $k => $row) {
@@ -395,10 +396,20 @@ class WeglotClient
395
  $property = $element['property'];
396
  $t = $element['t'];
397
  $type = $element['type'];
398
- $functionName = 'check' . ucfirst($type);
399
 
400
- if ($this->full_trim($row->$property) != '' && ! $this->hasAncestorAttribute($row, 'data-wg-notranslate')
401
- && $this->$functionName($row)
 
 
 
 
 
 
 
 
 
 
402
  ) {
403
  array_push(
404
  $words,
@@ -449,7 +460,7 @@ class WeglotClient
449
  if (isset($this->thirds["woocommerce"])) {
450
  $countWC18n = $this->thirds["woocommerce"]->translate($dom, $words); // TODO : Improve countWC18n
451
  }
452
-
453
  $title = 'Empty title';
454
  foreach ($html->find('title') as $k => $row) {
455
  if ($row->innertext != '') {
@@ -466,6 +477,21 @@ class WeglotClient
466
  $title = 'Ajax data';
467
  }
468
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
469
  $bot = $this->bot_detected();
470
  $parameters = array(
471
  'l_from' => $l_from,
@@ -478,62 +504,78 @@ class WeglotClient
478
  $results = $this->doRequest(self::API_BASE . '/translate?api_key=' . $this->api_key, $parameters);
479
 
480
  $json = json_decode($results, true);
481
- if (json_last_error() == JSON_ERROR_NONE) {
482
- $answer = $json;
483
- if (isset($answer['to_words'])) {
484
- $translated_words = $answer['to_words'];
485
- $from_words = $answer['from_words'];
486
-
487
- if ((count($nodes) + $nbJsonStrings + $countWC18n) == count($translated_words)) {
488
- for ($i = 0;$i < count($nodes);$i++) {
489
- $property = $nodes[$i]['property'];
490
- $type = $nodes[$i]['type'];
491
-
492
- if ($type == "meta_desc") {
493
- $nodes[$i]['node']->$property = htmlspecialchars($translated_words[$i]);
494
- } else {
495
- $nodes[$i]['node']->$property = $translated_words[$i];
496
- }
497
-
498
-
499
- if ($nodes[$i]['type'] == 'img_src') {
500
- $nodes[$i]['node']->src = $translated_words[$i];
501
- if ($nodes[$i]['node']->hasAttribute('srcset') && $nodes[$i]['node']->srcset != '' && htmlspecialchars_decode($translated_words[$i]) != htmlspecialchars_decode($words[$i]['w'])) {
502
- $nodes[$i]['node']->srcset = '';
503
- }
504
- }
505
- }
506
- $index = count($nodes);
507
- for ($j = 0;$j < count($jsons);$j++) {
508
- $jsonArray = $jsons[$j]['json'];
509
- $node = $jsons[$j]['node'];
510
- foreach ($microData as $key) {
511
- $path = explode(">", $key);
512
- $hasV = $this->getValue($jsonArray, $path);
513
-
514
- if (isset($hasV)) {
515
- $this->setValues($jsonArray, $path, $translated_words, $index);
516
- }
517
- }
518
- $node->innertext = json_encode($jsonArray, JSON_PRETTY_PRINT);
519
- }
520
 
521
- $dom = $html->save();
 
 
 
522
 
523
- for ($k = 0; $k < $countWC18n; $k++) {
524
- $dom = str_replace('\"'.$this->unformatFromApi($from_words[$k + $index + $nbJsonStrings]).'\"', '\"'.$this->unformatFromApi($translated_words[$k + $index + $nbJsonStrings]).'\"', $dom);
525
- }
526
 
527
- return $dom;
528
- } else {
529
- throw new WeglotException('Unknown error with Weglot Api (0006)');
530
- }
 
 
 
 
 
 
 
 
531
  } else {
532
- throw new WeglotException('Unknown error with Weglot Api (0005) Error is: ' . serialize($results));
 
 
 
 
 
 
 
 
533
  }
534
- } else {
535
- throw new WeglotException('Error with Weglot Api (0001) : ' . json_last_error() . ' Error is: ' . serialize($results));
536
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
  }
538
 
539
  public function getUserInfo()
11
 
12
  const API_BASE = 'https://api.weglot.com';
13
  const API_BASE_OLD = 'https://weglot.com/api/';
14
+ const NUMBER_MAX_CHARS = 500;
15
 
16
  public function __construct($key)
17
  {
388
  ),
389
  );
390
 
391
+ $elements_to_check = apply_filters("weglot_elements_to_check", $elements_to_check);
392
 
393
  foreach ($elements_to_check as $key => $elem) {
394
  foreach ($html->find($key) as $k => $row) {
396
  $property = $element['property'];
397
  $t = $element['t'];
398
  $type = $element['type'];
399
+ $functionName = apply_filters('weglot_check_type_element', 'check' . ucfirst($type), $type);
400
 
401
+ $checkType = true;
402
+ if (method_exists($this, $functionName)) {
403
+ $checkType = $this->$functionName($row);
404
+ } elseif (function_exists($functionName)) {
405
+ $checkType = $functionName($row);
406
+ }
407
+
408
+ if (
409
+ $this->full_trim($row->$property) != '' &&
410
+ ! $this->hasAncestorAttribute($row, 'data-wg-notranslate') &&
411
+ $checkType &&
412
+ strlen($row->$property) <= self::NUMBER_MAX_CHARS
413
  ) {
414
  array_push(
415
  $words,
460
  if (isset($this->thirds["woocommerce"])) {
461
  $countWC18n = $this->thirds["woocommerce"]->translate($dom, $words); // TODO : Improve countWC18n
462
  }
463
+
464
  $title = 'Empty title';
465
  foreach ($html->find('title') as $k => $row) {
466
  if ($row->innertext != '') {
477
  $title = 'Ajax data';
478
  }
479
 
480
+ $otherWords = apply_filters("weglot_words_translate", array());
481
+
482
+ if (!empty($otherWords) && is_array($otherWords)) {
483
+ foreach ($otherWords as $otherWord) {
484
+ if (strlen($otherWord) > self::NUMBER_MAX_CHARS) {
485
+ continue;
486
+ }
487
+
488
+ $words[] = array(
489
+ "t" => 1,
490
+ "w" => $otherWord
491
+ );
492
+ }
493
+ }
494
+
495
  $bot = $this->bot_detected();
496
  $parameters = array(
497
  'l_from' => $l_from,
504
  $results = $this->doRequest(self::API_BASE . '/translate?api_key=' . $this->api_key, $parameters);
505
 
506
  $json = json_decode($results, true);
507
+ if (json_last_error() !== JSON_ERROR_NONE) {
508
+ throw new WeglotException('Error with Weglot Api (0001) : ' . json_last_error() . ' Error is: ' . serialize($results));
509
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
 
511
+ $answer = $json;
512
+ if (!isset($answer['to_words'])) {
513
+ throw new WeglotException('Unknown error with Weglot Api (0005) Error is: ' . serialize($results));
514
+ }
515
 
516
+ $translated_words = $answer['to_words'];
517
+ $from_words = $answer['from_words'];
 
518
 
519
+ $totalWordsToTranslate = count($nodes) + $nbJsonStrings + $countWC18n + count($otherWords);
520
+ if ($totalWordsToTranslate !== count($translated_words)) {
521
+ throw new WeglotException('Unknown error with Weglot Api (0006)');
522
+ }
523
+
524
+ for ($i = 0;$i < count($nodes);$i++) {
525
+ $currentNode = $nodes[$i];
526
+ $property = $currentNode['property'];
527
+ $type = $currentNode['type'];
528
+
529
+ if ($type == "meta_desc") {
530
+ $currentNode['node']->$property = htmlspecialchars($translated_words[$i]);
531
  } else {
532
+ $currentNode['node']->$property = $translated_words[$i];
533
+ }
534
+
535
+
536
+ if ($currentNode['type'] == 'img_src') {
537
+ $currentNode['node']->src = $translated_words[$i];
538
+ if ($currentNode['node']->hasAttribute('srcset') && $currentNode['node']->srcset != '' && htmlspecialchars_decode($translated_words[$i]) != htmlspecialchars_decode($words[$i]['w'])) {
539
+ $currentNode['node']->srcset = '';
540
+ }
541
  }
 
 
542
  }
543
+
544
+ $index = count($nodes);
545
+ for ($i = 0;$i < count($jsons);$i++) {
546
+ $currentJson = $jsons[$i];
547
+ $jsonArray = $currentJson['json'];
548
+ $node = $currentJson['node'];
549
+ foreach ($microData as $key) {
550
+ $path = explode(">", $key);
551
+ $hasV = $this->getValue($jsonArray, $path);
552
+
553
+ if (isset($hasV)) {
554
+ $this->setValues($jsonArray, $path, $translated_words, $index);
555
+ }
556
+ }
557
+ $node->innertext = json_encode($jsonArray, JSON_PRETTY_PRINT);
558
+ }
559
+
560
+ $dom = $html->save();
561
+
562
+ for ($i = 0; $i < $countWC18n; $i++) {
563
+ $dom = str_replace('\"'.$this->unformatFromApi($from_words[$i + $index + $nbJsonStrings]).'\"', '\"'.$this->unformatFromApi($translated_words[$i + $index + $nbJsonStrings]).'\"', $dom);
564
+ }
565
+
566
+
567
+ if (empty($otherWords)) {
568
+ return $dom;
569
+ }
570
+
571
+ $fromWords = array_slice($from_words, $index);
572
+ $otherWordsTranslated = array_slice($translated_words, $index);
573
+
574
+ foreach ($fromWords as $key => $fromWord) {
575
+ $dom = str_replace($fromWord, $otherWordsTranslated[$key], $dom);
576
+ }
577
+
578
+ return $dom;
579
  }
580
 
581
  public function getUserInfo()
src/Helpers/WeglotUrl.php CHANGED
@@ -2,9 +2,11 @@
2
 
3
  namespace Weglot\Helpers;
4
 
5
- abstract class WeglotUrl {
6
- public static function isEligibleURL($url) // Change this in another helper and remove static
7
 
 
 
 
8
  {
9
  $url = urldecode(self::URLToRelative($url));
10
  //Format exclude URL
@@ -19,17 +21,17 @@ abstract class WeglotUrl {
19
  }
20
  $excludeURL = implode(',', $excludedUrls);
21
  }
22
-
23
  $exclusions = preg_replace('#\s+#', ',', $excludeURL);
24
-
25
  $listRegex = explode(',', $exclusions);
26
-
27
  $excludeAmp = apply_filters("weglot_exclude_amp", true); // Too dependecy WP
28
-
29
  if ($excludeAmp) {
30
- $listRegex[] = apply_filters('weglot_regex_amp', '([&,\?,/])?amp(/)?');
31
  }
32
-
33
  if (empty($exclusions)) {
34
  return true;
35
  }
@@ -46,7 +48,6 @@ abstract class WeglotUrl {
46
  }
47
 
48
  public static function escapeSlash($str) // Change this in another helper and remove static
49
-
50
  {
51
  return str_replace('/', '\/', $str);
52
  }
@@ -71,16 +72,17 @@ abstract class WeglotUrl {
71
  return $url;
72
  }
73
 
74
- /** Returns the subdirectories where WP is installed
75
- *
76
- * returns /directories if there is one
77
- * return empty string otherwise
78
- *
79
- */
80
  public static function getHomeDirectory()
81
  {
82
- if(isset(self::$home_dir)){
83
- return self::$home_dir;
 
84
  }
85
 
86
  $opt_siteurl = trim(get_option('siteurl'), '/');
@@ -89,11 +91,10 @@ abstract class WeglotUrl {
89
  if ((substr($opt_home, 0, 7) == 'http://' && strpos(substr($opt_home, 7), '/') !== false) || (substr($opt_home, 0, 8) == 'https://' && strpos(substr($opt_home, 8), '/') !== false)) {
90
  $parsed_url = parse_url($opt_home);
91
  $path = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
92
- self::$home_dir = $path;
93
  return $path;
94
  }
95
  }
96
  return null;
97
  }
98
-
99
- }
2
 
3
  namespace Weglot\Helpers;
4
 
5
+ use Weglot\WeglotContext;
 
6
 
7
+ abstract class WeglotUrl
8
+ {
9
+ public static function isEligibleURL($url) // Change this in another helper and remove static
10
  {
11
  $url = urldecode(self::URLToRelative($url));
12
  //Format exclude URL
21
  }
22
  $excludeURL = implode(',', $excludedUrls);
23
  }
24
+
25
  $exclusions = preg_replace('#\s+#', ',', $excludeURL);
26
+
27
  $listRegex = explode(',', $exclusions);
28
+
29
  $excludeAmp = apply_filters("weglot_exclude_amp", true); // Too dependecy WP
30
+
31
  if ($excludeAmp) {
32
+ $listRegex[] = apply_filters('weglot_regex_amp', '([&\?/])amp(/)?$');
33
  }
34
+
35
  if (empty($exclusions)) {
36
  return true;
37
  }
48
  }
49
 
50
  public static function escapeSlash($str) // Change this in another helper and remove static
 
51
  {
52
  return str_replace('/', '\/', $str);
53
  }
72
  return $url;
73
  }
74
 
75
+ /** Returns the subdirectories where WP is installed
76
+ *
77
+ * returns /directories if there is one
78
+ * return empty string otherwise
79
+ *
80
+ */
81
  public static function getHomeDirectory()
82
  {
83
+ $homeDir = WeglotContext::getHomeDirectory();
84
+ if (isset($homeDir) ) {
85
+ return $homeDir;
86
  }
87
 
88
  $opt_siteurl = trim(get_option('siteurl'), '/');
91
  if ((substr($opt_home, 0, 7) == 'http://' && strpos(substr($opt_home, 7), '/') !== false) || (substr($opt_home, 0, 8) == 'https://' && strpos(substr($opt_home, 8), '/') !== false)) {
92
  $parsed_url = parse_url($opt_home);
93
  $path = isset($parsed_url['path']) ? $parsed_url['path'] : '/';
94
+ WeglotContext::setHomeDirectory($path);
95
  return $path;
96
  }
97
  }
98
  return null;
99
  }
100
+ }
 
src/Notices/AdminNotices.php CHANGED
@@ -12,7 +12,7 @@ class AdminNotices
12
  /**
13
  * @see wgExceededFreeLimit
14
  */
15
- protected function wgExceededFreeLimitNotice()
16
  {
17
  ?>
18
  <div class="updated settings-error notice is-dismissible">
@@ -29,7 +29,7 @@ class AdminNotices
29
  /**
30
  * @see wgRequireRewriteModule
31
  */
32
- protected function wgRequireRewriteModuleNotice()
33
  {
34
  ?>
35
  <div class="error settings-error notice is-dismissible">
@@ -50,7 +50,7 @@ class AdminNotices
50
  {
51
  ?>
52
  <div class="error settings-error notice is-dismissible">
53
- <p><?php echo sprintf(esc_html__('Weglot Translate is installed but not yet configured, you need to configure Weglot here : %1$sWeglot configuration page%2$s. The configuration takes only 1 minute! ', 'weglot'), '<a href="'.admin_url().'admin.php?page=Weglot">', '</a>'); ?></p>
54
  </div>
55
  <?php
56
  }
@@ -59,7 +59,7 @@ class AdminNotices
59
  {
60
  add_action('admin_notices', array($this, 'wgGtranslateNotice'), 0);
61
  }
62
-
63
  public function hasGTranslatePlugin() // Not single responsability
64
  {
65
  return is_plugin_active('gtranslate/gtranslate.php');
@@ -78,7 +78,7 @@ class AdminNotices
78
  if ($screen->id === "toplevel_page_Weglot") {
79
  return;
80
  }
81
-
82
  $pluginFile = 'gtranslate/gtranslate.php';
83
  $deactivateLink = wp_nonce_url('plugins.php?action=deactivate&amp;plugin='.urlencode($pluginFile).'&amp;plugin_status=all&amp;paged=1&amp;s=', 'deactivate-plugin_' . $pluginFile)
84
 
12
  /**
13
  * @see wgExceededFreeLimit
14
  */
15
+ public function wgExceededFreeLimitNotice()
16
  {
17
  ?>
18
  <div class="updated settings-error notice is-dismissible">
29
  /**
30
  * @see wgRequireRewriteModule
31
  */
32
+ public function wgRequireRewriteModuleNotice()
33
  {
34
  ?>
35
  <div class="error settings-error notice is-dismissible">
50
  {
51
  ?>
52
  <div class="error settings-error notice is-dismissible">
53
+ <p><?php echo sprintf(esc_html__('Weglot Translate is installed but not yet configured, you need to configure Weglot here : %1$sWeglot configuration page%2$s. The configuration takes only 1 minute! ', 'weglot'), '<a href="'.admin_url().'admin.php?page=weglot">', '</a>'); ?></p>
54
  </div>
55
  <?php
56
  }
59
  {
60
  add_action('admin_notices', array($this, 'wgGtranslateNotice'), 0);
61
  }
62
+
63
  public function hasGTranslatePlugin() // Not single responsability
64
  {
65
  return is_plugin_active('gtranslate/gtranslate.php');
78
  if ($screen->id === "toplevel_page_Weglot") {
79
  return;
80
  }
81
+
82
  $pluginFile = 'gtranslate/gtranslate.php';
83
  $deactivateLink = wp_nonce_url('plugins.php?action=deactivate&amp;plugin='.urlencode($pluginFile).'&amp;plugin_status=all&amp;paged=1&amp;s=', 'deactivate-plugin_' . $pluginFile)
84
 
src/WeglotContext.php ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace Weglot;
4
+
5
+ abstract class WeglotContext
6
+ {
7
+ protected static $originalLang;
8
+
9
+ protected static $destinationLang;
10
+
11
+ protected static $homeDirectory;
12
+
13
+ protected static $currentLang;
14
+
15
+ public static function setOriginalLanguage($originalL)
16
+ {
17
+ self::$originalLang = $originalL;
18
+ }
19
+
20
+ public static function setDestinationLanguage($destL)
21
+ {
22
+ self::$destinationLang = $destL;
23
+ }
24
+
25
+ public static function getOriginalLanguage()
26
+ {
27
+ return self::$originalLang;
28
+ }
29
+
30
+ public static function getDestinationLanguage(){
31
+ return self::$destinationLang;
32
+ }
33
+
34
+ public static function setHomeDirectory($homeDir)
35
+ {
36
+ self::$homeDirectory = $homeDir;
37
+ }
38
+
39
+ public static function getHomeDirectory()
40
+ {
41
+ return self::$homeDirectory;
42
+ }
43
+
44
+ public static function setCurrentLanguage($currentLang)
45
+ {
46
+ self::$currentLang = $currentLang;
47
+ }
48
+
49
+ public static function getCurrentLanguage()
50
+ {
51
+ return self::$currentLang;
52
+ }
53
+ }
weglot.php CHANGED
@@ -1,7 +1,7 @@
1
  <?php
2
  /**
3
  * @package Weglot
4
- * @version 1.11
5
  */
6
 
7
  /*
@@ -12,7 +12,7 @@ Author: Weglot Translate team
12
  Author URI: https://weglot.com/
13
  Text Domain: weglot
14
  Domain Path: /languages/
15
- Version: 1.11
16
  */
17
 
18
  /*
@@ -41,7 +41,7 @@ if (! defined('ABSPATH')) {
41
  }
42
 
43
 
44
- define('WEGLOT_VERSION', '1.11');
45
  define('WEGLOT_DIR', dirname(__FILE__));
46
  define('WEGLOT_BNAME', plugin_basename(__FILE__));
47
  define('WEGLOT_DIRURL', plugin_dir_url(__FILE__));
@@ -52,30 +52,38 @@ require_once WEGLOT_DIR . "/vendor/autoload.php";
52
  require_once WEGLOT_DIR . '/simple_html_dom.php';
53
  require_once WEGLOT_DIR . '/WeglotWidget.php';
54
 
 
55
  use Weglot\Helpers\WeglotUtils;
56
  use Weglot\Helpers\WeglotLang;
 
57
  use Weglot\Notices\AdminNotices;
58
  use Weglot\Third\Yoast\RedirectHandler;
59
 
60
- $dirYoastPremum = plugin_dir_path(__DIR__) . "wordpress-seo-premium/premium/";
61
- if(!function_exists('is_plugin_active')){
62
- include_once(ABSPATH . 'wp-admin/includes/plugin.php');
63
- }
64
 
65
- // Override yoast redirect
66
- if (
67
- ! is_admin() &&
68
- is_plugin_active("wordpress-seo-premium/wp-seo-premium.php") &&
69
- file_exists($dirYoastPremum) &&
70
- file_exists($dirYoastPremum . 'classes/redirect/redirect-handler.php') &&
71
- file_exists($dirYoastPremum . 'classes/redirect/redirect-util.php')
72
- ){
73
 
74
- require_once $dirYoastPremum . 'classes/redirect/redirect-handler.php';
75
- require_once $dirYoastPremum . 'classes/redirect/redirect-util.php';
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- $redirectHandler = new RedirectHandler();
78
- $redirectHandler->load();
 
79
  }
80
 
81
 
@@ -83,9 +91,6 @@ if (
83
  * Singleton class Weglot */
84
  class Weglot
85
  {
86
- private $original_l;
87
- private $destination_l;
88
-
89
  private $request_uri;
90
  private $home_dir;
91
  private $network_paths;
@@ -107,7 +112,6 @@ class Weglot
107
 
108
  if (function_exists('apache_get_modules') && ! in_array('mod_rewrite', apache_get_modules())) {
109
  $this->services["AdminNotices"]->wgRequireRewriteModule();
110
- return;
111
  }
112
 
113
  $this->services["AdminNotices"]->thirdNotices();
@@ -118,11 +122,12 @@ class Weglot
118
  add_action('wp', array( $this, 'rr_404_my_event' ));
119
  add_filter('plugin_action_links_' . plugin_basename(__FILE__), array( $this, 'wg_plugin_action_links' ));
120
 
121
- $this->original_l = get_option('original_l');
122
- $this->destination_l = get_option('destination_l');
 
123
 
124
- $this->home_dir = $this->getHomeDirectory();
125
- $this->request_uri = $this->getRequestUri($this->home_dir);
126
  $this->network_paths = $this->getListOfNetworkPath();
127
 
128
  $this->noredirect = false;
@@ -137,21 +142,24 @@ class Weglot
137
  }
138
  }
139
 
140
- $this->request_uri = str_replace('?no_lredirect=true', '', $this->request_uri);
141
- $curr = $this->getLangFromUrl($this->request_uri);
142
- $this->currentlang = $curr ? $curr : $this->original_l;
143
- $this->request_uri_no_language = ($this->currentlang != $this->original_l) ? substr($this->request_uri, 3) : $this->request_uri;
 
 
 
144
 
145
- if ($this->currentlang != $this->original_l) {
146
  $_SERVER['REQUEST_URI'] = str_replace(
147
- '/' . $this->currentlang .
148
  '/',
149
  '/',
150
  $_SERVER['REQUEST_URI']
151
  );
152
  }
153
 
154
- if (WeglotUtils::isLanguageRTL($this->currentlang)) {
155
  $GLOBALS['text_direction'] = 'rtl';
156
  } else {
157
  $GLOBALS['text_direction'] = 'ltr';
@@ -159,6 +167,7 @@ class Weglot
159
 
160
  add_filter('woocommerce_get_cart_url', array( $this,'filter_woocommerce_get_cart_url'));
161
  add_filter('woocommerce_get_checkout_url', array( $this,'filter_woocommerce_get_cart_url'));
 
162
  add_filter('woocommerce_get_checkout_order_received_url', array( $this, 'filter_woocommerce_get_checkout_order_received_url'));
163
  add_action('woocommerce_reset_password_notification', array( $this, 'redirectUrlLostPassword'));
164
 
@@ -178,7 +187,7 @@ class Weglot
178
  $this->allowed = $apikey ? get_option('wg_allowed') : true;
179
 
180
  if (is_admin()) {
181
- if (strpos($this->request_uri, 'page=Weglot') !== false) {
182
  if ($this->translator) {
183
  try {
184
  $this->userInfo = $this->translator->getUserInfo();
@@ -200,9 +209,13 @@ class Weglot
200
 
201
 
202
  $isURLOK = $this->isEligibleURL($this->request_uri_no_language);
 
 
 
 
 
203
  if ($isURLOK) {
204
  add_action('wp_head', array( $this, 'add_alternate' ));
205
- add_action('widgets_init', array( $this, 'addWidget' ));
206
  add_shortcode('weglot_switcher', array( $this, 'wg_switcher_creation' ));
207
  if (get_option('is_menu') == 'on') {
208
  add_filter('wp_nav_menu_items', 'your_custom_menu_item', 10, 2);
@@ -219,17 +232,18 @@ class Weglot
219
  }
220
  }
221
 
 
222
  /**
223
  * Redirect URL Lost password for WooCommerce
224
  */
225
  public function redirectUrlLostPassword($url)
226
  {
227
- if ($this->currentlang === $this->original_l) {
228
  return;
229
  }
230
 
231
  $urlRedirect = add_query_arg('reset-link-sent', 'true', wc_get_account_endpoint_url('lost-password'));
232
- $urlRedirect = $this->replaceUrl($urlRedirect, $this->currentlang);
233
 
234
  wp_redirect($urlRedirect);
235
  exit;
@@ -285,50 +299,64 @@ class Weglot
285
 
286
  public function wg_plugin_action_links($links)
287
  {
288
- $links[] = '<a href="' . esc_url(get_admin_url(null, 'admin.php?page=Weglot')) . '">' . __('Settings', 'weglot') . '</a>';
289
  return $links;
290
  }
291
 
292
  public function filter_woocommerce_get_cart_url($wc_get_page_permalink)
293
  {
294
- if ($this->currentlang != $this->original_l) {
295
- return $this->replaceUrl($wc_get_page_permalink, $this->currentlang);
296
  } else {
297
  return $wc_get_page_permalink;
298
  }
299
  }
300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  public function filter_woocommerce_get_checkout_order_received_url($order_received_url)
302
- {
303
- if ($this->currentlang != $this->original_l) {
304
- if (substr(get_option('permalink_structure'), -1) != '/') {
305
- return str_replace('/?key', '?key', $this->replaceUrl($order_received_url, $this->currentlang));
306
- } else {
307
- return str_replace('//?key', '/?key', str_replace('?key', '/?key', $this->replaceUrl($order_received_url, $this->currentlang)));
308
- }
309
- } else {
310
- if (isset($_SERVER['HTTP_REFERER'])) {
311
- $l = $this->getLangFromUrl($this->URLToRelative($_SERVER['HTTP_REFERER']));
312
- if ($l && $l != $this->original_l) {
313
- if (substr(get_option('permalink_structure'), -1) != '/') {
314
- return str_replace('/?key', '?key', $this->replaceUrl($order_received_url, $l));
315
- } else {
316
- return str_replace('//?key', '/?key', str_replace('?key', '/?key', $this->replaceUrl($order_received_url, $l)));
317
- }
318
- }
319
- }
320
- return $order_received_url;
321
- }
322
- }
323
 
324
  public function wg_log_redirect($redirect_to)
325
  {
326
- if ($this->currentlang != $this->original_l) {
327
- return $this->replaceUrl($redirect_to, $this->currentlang);
328
  } else {
329
  if (isset($_SERVER['HTTP_REFERER'])) {
330
- $l = $this->getLangFromUrl($this->URLToRelative($_SERVER['HTTP_REFERER']));
331
- if ($l && $l != $this->original_l) {
332
  return $this->replaceUrl($redirect_to, $l);
333
  }
334
  }
@@ -340,17 +368,17 @@ class Weglot
340
  {
341
  $messageAndSubject = "<p>".$args['subject']."</p>".$args['message'];
342
 
343
- if ($this->currentlang != $this->original_l) {
344
- $messageAndSubjectTranslated = $this->translateEmail($messageAndSubject, $this->currentlang);
345
  } elseif (isset($_SERVER['HTTP_REFERER'])) {
346
- $l = $this->getLangFromUrl($this->URLToRelative($_SERVER['HTTP_REFERER']));
347
- if ($l && $l != $this->original_l) { //If language in referer
348
  $messageAndSubjectTranslated = $this->translateEmail($messageAndSubject, $l);
349
  } elseif (strpos($_SERVER['HTTP_REFERER'], 'wg_language=') !== false) { //If language in parameter
350
  $pos = strpos($_SERVER['HTTP_REFERER'], 'wg_language=');
351
  $start = $pos + strlen('wg_language=');
352
  $l = substr($_SERVER['HTTP_REFERER'], $start, 2);
353
- if ($l && $l != $this->original_l) {
354
  $messageAndSubjectTranslated = $this->translateEmail($messageAndSubject, $l);
355
  }
356
  }
@@ -380,9 +408,18 @@ class Weglot
380
  public function init_function()
381
  {
382
  add_action('admin_menu', array( $this, 'plugin_menu' ));
 
 
383
  add_action('admin_init', array( $this, 'plugin_settings' ));
 
 
 
384
 
385
- $dest = explode(',', $this->destination_l);
 
 
 
 
386
 
387
  if ($this->request_uri == '/' && ! $this->noredirect && ! WeglotUtils::is_bot()) { // front_page
388
 
@@ -391,7 +428,7 @@ class Weglot
391
  $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
392
  // exit(print_r($dest));
393
  if (in_array($lang, $dest)) {
394
- wp_safe_redirect($this->home_dir . "/$lang/");
395
  exit();
396
  }
397
  }
@@ -410,61 +447,102 @@ class Weglot
410
  add_action('template_redirect', array( $this, 'kill_canonical_wg_92103' ), 1);
411
  }
412
 
413
- if (! is_admin() || (is_admin() && strpos($this->request_uri, 'page=Weglot') !== false)) {
414
- // Add JS
415
- wp_register_script('wp-weglot-js', WEGLOT_RESURL . 'wp-weglot-js.js', false, WEGLOT_VERSION, false);
416
- wp_enqueue_script('wp-weglot-js');
417
-
418
- // Add CSS
419
- wp_register_style('wp-weglot-css', WEGLOT_RESURL . 'wp-weglot-css.css', false, WEGLOT_VERSION, false);
420
- wp_enqueue_style('wp-weglot-css');
421
-
422
- wp_add_inline_style('wp-weglot-css', $this->getInlineCSS());
423
-
424
- if (is_admin()) {
425
- // Add Admin JS
426
- wp_register_script('wp-weglot-admin-js', WEGLOT_RESURL . 'wp-weglot-admin-js.js', array( 'jquery' ), WEGLOT_VERSION, true);
427
- wp_enqueue_script('wp-weglot-admin-js');
428
-
429
- // Add Admin CSS
430
- wp_register_style('wp-weglot-admin-css', WEGLOT_RESURL . 'wp-weglot-admin-css.css', false, WEGLOT_VERSION, false);
431
- wp_enqueue_style('wp-weglot-admin-css');
432
-
433
- // Add Selectize JS
434
- wp_enqueue_script('jquery-ui', WEGLOT_RESURL . 'selectize/js/jquery-ui.min.js', array( 'jquery' ), WEGLOT_VERSION, true);
435
- wp_enqueue_script('jquery-selectize', WEGLOT_RESURL . 'selectize/js/selectize.min.js', array( 'jquery' ), WEGLOT_VERSION, true);
436
- // wp_enqueue_style( 'selectize-css', WEGLOT_RESURL . 'selectize/css/selectize.css', array(), $ver );
437
- wp_enqueue_style('selectize-defaut-css', WEGLOT_RESURL . 'selectize/css/selectize.default.css', array(), WEGLOT_VERSION);
438
-
439
- if (! function_exists('is_plugin_active')) { // Need to refactor enqueue script
440
- require_once(ABSPATH . '/wp-admin/includes/plugin.php');
441
- }
442
 
443
- if ($this->services["AdminNotices"]->hasGTranslatePlugin()) {
444
- $customCss = "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445
  .gt-admin-notice{
446
  display:none !important;
447
  }
448
  ";
449
-
450
- wp_add_inline_style('wp-weglot-css', $customCss);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
  }
452
  }
453
  }
454
-
455
- /* Putting it in init makes that buffer deeper than caching ob */
456
- ob_start(array($this, 'treatPage' ));
457
  }
458
 
459
  public function add_alternate()
460
  {
461
- if ($this->destination_l != '') {
462
 
463
- // $thisL = $this->currentlang;
464
- $dest = explode(',', $this->destination_l);
465
 
466
- $full_url = ($this->currentlang != $this->original_l) ? str_replace('/' . $this->currentlang . '/', '/', $this->full_url($_SERVER)) : $this->full_url($_SERVER);
467
- $output = '<link rel="alternate" hreflang="' . $this->original_l . '" href="' . $full_url . '" />' . "\n";
468
  foreach ($dest as $d) {
469
  $output .= '<link rel="alternate" hreflang="' . $d . '" href="' . $this->replaceUrl($full_url, $d) . '" />' . "\n";
470
  }
@@ -478,17 +556,12 @@ class Weglot
478
  }
479
  }
480
 
481
- public function getCurrentLang()
482
- {
483
- return $this->currentlang;
484
- }
485
-
486
  public function rr_404_my_event()
487
  {
488
 
489
  // regex logic here
490
  $isURLOK = $this->isEligibleURL($this->request_uri_no_language);
491
- if (! $isURLOK && $this->currentlang != $this->original_l) {
492
  global $wp_query;
493
  $wp_query->set_404();
494
  status_header(404);
@@ -502,24 +575,26 @@ class Weglot
502
 
503
  public function plugin_menu()
504
  {
505
- $hook = add_menu_page('Weglot', 'Weglot', 'administrator', 'Weglot', array( $this, 'plugin_settings_page' ), WEGLOT_DIRURL . '/images/weglot_fav_bw.png');
 
 
506
 
507
  // add_action('load-'.$hook,array($this, 'updateRewriteRule'));
508
  if (isset($this->request_uri_no_language)
509
  // && isset( $_POST['settings-updated-nonce'] )
510
  && $this->request_uri_no_language
511
- && strpos($this->request_uri_no_language, 'page=Weglot') !== false
512
  && strpos($this->request_uri_no_language, 'settings-updated=true') !==
513
  false) {
514
- $d = explode(',', preg_replace('/\s+/', '', trim($this->destination_l, ',')));
515
  $accepted = WeglotLang::getCodeLangs();
516
  foreach ($d as $k => $l) {
517
- if (! in_array($l, $accepted) || $l == $this->original_l) {
518
  unset($d[ $k ]);
519
  }
520
  }
521
  update_option('destination_l', implode(',', $d));
522
- $this->destination_l = implode(',', $d);
523
 
524
  /* Display Box */
525
  if (! get_option('show_box')) {
@@ -527,19 +602,25 @@ class Weglot
527
  }
528
 
529
  if ($this->userInfo['plan'] <= 0 || in_array($this->userInfo['plan'], array( 18, 19, 1001, 1002 ))) {
530
- $d = explode(',', preg_replace('/\s+/', '', trim($this->destination_l, ',')));
531
- $this->destination_l = $d[0];
532
- update_option('destination_l', $this->destination_l);
533
  }
534
  }
535
  }
536
 
 
 
 
 
 
537
  public function plugin_settings()
538
  {
539
  register_setting('my-plugin-settings-group', 'project_key');
540
  register_setting('my-plugin-settings-group', 'original_l');
541
  register_setting('my-plugin-settings-group', 'destination_l');
542
  register_setting('my-plugin-settings-group', 'wg_auto_switch');
 
543
  register_setting('my-plugin-settings-group', 'override_css');
544
  register_setting('my-plugin-settings-group', 'flag_css');
545
  register_setting('my-plugin-settings-group', 'with_flags');
@@ -565,24 +646,23 @@ class Weglot
565
 
566
  public function translateEmail($body, $l)
567
  {
568
- $translatedEmail = $this->translator->translateDomFromTo($body, $this->original_l, $l);
569
  return $translatedEmail;
570
  }
571
  public function treatPage($final)
572
  {
573
  $request_uri = $this->request_uri;
574
- if (! is_admin() && strpos($request_uri, 'jax') === false && $this->original_l != '' && $this->destination_l != '') {
575
-
576
  // $final = file_get_contents(__DIR__.'/content.html'); //Testing purpose.
577
  // Get the original request
578
  $url = $this->request_uri_no_language;
579
-
580
  if ($this->isEligibleURL($url) && WeglotUtils::is_HTML($final)) {
581
 
582
  // If a language is set, we translate the page & links.
583
- if ($this->currentlang != $this->original_l) {
584
  try {
585
- $l = $this->currentlang;
586
  $final = $this->translatePageTo($final, $l);
587
  } catch (\Weglot\Exceptions\WeglotException $e) {
588
  $final .= '<!--Weglot error : ' . $e->getMessage() . '-->';
@@ -615,12 +695,11 @@ class Weglot
615
  $button = WeglotUtils::str_lreplace('<aside data-wg-notranslate class="', '<aside data-wg-notranslate class="wg-default ', $button);
616
  $final = (strpos($final, '</body>') !== false) ? WeglotUtils::str_lreplace('</body>', $button . ' </body>', $final) : WeglotUtils::str_lreplace('</footer>', $button . ' </footer>', $final);
617
  }
618
- {
619
- return $final;
620
- }
621
- } elseif ($this->isEligibleURL($url) && isset($final[0]) && $final[0] == '{' || ($final[0] == '[' && (isset($final[1]) && $final[1] == '{'))) {
622
  $thisL = $this->getLangFromUrl(
623
- $this->URLToRelative(
624
  $_SERVER['HTTP_REFERER']
625
  )
626
  );
@@ -651,17 +730,17 @@ class Weglot
651
  return $final;
652
  }
653
  } elseif ((strpos($request_uri, 'jax') !== false) &&
654
- $this->destination_l != '' && $this->original_l != '' && isset(
655
  $_SERVER['HTTP_REFERER']
656
  ) && strpos($_SERVER['HTTP_REFERER'], 'admin') === false) {
657
  $thisL = $this->getLangFromUrl(
658
- $this->URLToRelative(
659
  $_SERVER['HTTP_REFERER']
660
  )
661
  );
662
  if (isset($thisL) && $thisL != '') {
663
  try {
664
- if ($final[0] == '{' || ($final[0] == '[' && $final[1] == '{')) {
665
  $json = json_decode($final, true);
666
  if (json_last_error() == JSON_ERROR_NONE) {
667
  $jsonT = $this->translateArray($json, $thisL);
@@ -709,8 +788,8 @@ class Weglot
709
  if ($this->allowed == 0) {
710
  return $final . '<!--Not allowed-->';
711
  }
712
-
713
- $translatedPage = $this->translator->translateDomFromTo($final, $this->original_l, $l); // $page is your html page
714
 
715
  $this->modifyLink('/<a([^\>]+?)?href=(\"|\')([^\s\>]+?)(\"|\')([^\>]+?)?>/', $translatedPage, $l, 'A');
716
  $this->modifyLink('/<([^\>]+?)?data-link=(\"|\')([^\s\>]+?)(\"|\')([^\>]+?)?>/', $translatedPage, $l, 'DATALINK');
@@ -772,7 +851,7 @@ class Weglot
772
 
773
  return (
774
  (($current_url[0] == 'h' && $parsed_url['host'] == $_SERVER['HTTP_HOST'])
775
- || ($current_url[0] == '/' && $current_url[1] != '/'))
776
  && strpos($current_url, $admin_url) === false
777
  && strpos($current_url, 'wp-login') === false
778
  && !$this->isLinkAFile($current_url)
@@ -791,7 +870,6 @@ class Weglot
791
  $sometags = null,
792
  $sometags2 = null
793
  ) {
794
-
795
  $translatedPage = preg_replace('/<a' . preg_quote($sometags, '/') . 'href=' .
796
  preg_quote($quote1 . $current_url . $quote2, '/') . '/', '<a' . $sometags . 'href=' . $quote1 . $this->replaceUrl(
797
  $current_url,
@@ -909,7 +987,7 @@ class Weglot
909
  /* Urls functions */
910
  public function replaceUrl($url, $l)
911
  {
912
- //$home_dir = $this->home_dir;
913
 
914
  $parsed_url = parse_url($url);
915
  $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
@@ -930,7 +1008,7 @@ class Weglot
930
  "/$l/") ?
931
  "$scheme$user$pass$host$port$path$query$fragment" : "$scheme$user$pass$host$port/$l$path$query$fragment";
932
 
933
- foreach ($this->network_paths as $np) {
934
  if (strlen($np) > 2 && strpos($urlTranslated, $np) !==
935
  false) {
936
  $urlTranslated = str_replace(
@@ -961,13 +1039,13 @@ class Weglot
961
  $paths = array();
962
 
963
  if (is_multisite()) {
964
- $sites = get_sites();
965
  foreach ($sites as $site) {
966
  $path = $site->path;
967
  array_push($paths, $path);
968
  }
969
  } else {
970
- array_push($paths, $this->home_dir.'/');
971
  }
972
 
973
  return $paths;
@@ -979,7 +1057,7 @@ class Weglot
979
  }
980
  public function isEligibleURL($url)
981
  {
982
- $url = urldecode($this->URLToRelative($url));
983
  //Format exclude URL
984
  $excludeURL = get_option('exclude_url');
985
 
@@ -988,7 +1066,7 @@ class Weglot
988
 
989
  $excludedUrls = explode(',', $excludeURL);
990
  foreach ($excludedUrls as &$ex_url) {
991
- $ex_url = $this->URLToRelative($ex_url);
992
  }
993
  $excludeURL = implode(',', $excludedUrls);
994
  }
@@ -996,15 +1074,15 @@ class Weglot
996
 
997
  $exclusions = preg_replace('#\s+#', ',', $excludeURL);
998
 
999
- $listRegex = null;
1000
- if(!empty($exclusions)) {
1001
  $listRegex = explode(',', $exclusions);
1002
  }
1003
 
1004
 
1005
- $excludeAmp = apply_filters("weglot_exclude_amp", true);
1006
- if ($excludeAmp) {
1007
- $listRegex[] = apply_filters('weglot_regex_amp', '([&,\?,/])?amp(/)?');
1008
  }
1009
 
1010
  foreach ($listRegex as $regex) {
@@ -1023,25 +1101,7 @@ class Weglot
1023
  return str_replace('/', '\/', $str);
1024
  }
1025
 
1026
- public function URLToRelative($url)
1027
- {
1028
- if ((substr($url, 0, 7) == 'http://') || (substr($url, 0, 8) == 'https://')) {
1029
- // the current link is an "absolute" URL - parse it to get just the path
1030
- $parsed = parse_url($url);
1031
- $path = isset($parsed['path']) ? $parsed['path'] : '';
1032
- $query = isset($parsed['query']) ? '?' . $parsed['query'] : '';
1033
- $fragment = isset($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
1034
-
1035
- if ($this->home_dir) {
1036
- $relative = str_replace($this->home_dir, '', $path);
1037
 
1038
- return ($relative == '') ? '/' : $relative;
1039
- } else {
1040
- return $path . $query . $fragment;
1041
- }
1042
- }
1043
- return $url;
1044
- }
1045
  public function getRequestUri($home_dir)
1046
  {
1047
  if ($home_dir) {
@@ -1053,7 +1113,7 @@ class Weglot
1053
  public function getLangFromUrl($request_uri)
1054
  {
1055
  $l = null;
1056
- $dest = explode(',', $this->destination_l);
1057
  foreach ($dest as $d) {
1058
  if (substr($request_uri, 0, 4) == '/' . $d . '/') {
1059
  $l = $d;
@@ -1086,8 +1146,8 @@ class Weglot
1086
  public function getInlineCSS()
1087
  {
1088
  $css = get_option('override_css');
1089
- if ((WeglotUtils::isLanguageRTL($this->original_l) && ! WeglotUtils::isLanguageRTL($this->currentlang)) ||
1090
- (! WeglotUtils::isLanguageRTL($this->original_l) && WeglotUtils::isLanguageRTL($this->currentlang))) {
1091
  $css .= get_option('rtl_ltr_style');
1092
  }
1093
  if (! is_admin()) {
@@ -1121,14 +1181,15 @@ class Weglot
1121
  $type_flags = get_option('type_flags') ? get_option('type_flags') : 0;
1122
  $flag_class .= $type_flags == 0 ? '' : 'flag-' . $type_flags . ' ';
1123
 
1124
- $current = $this->currentlang;
1125
  $list = $is_dropdown ? '<ul>' : '';
1126
- $destEx = explode(',', $this->destination_l);
1127
- array_unshift($destEx, $this->original_l);
 
1128
  foreach ($destEx as $d) {
1129
  if ($d != $current) {
1130
- $link = ($d != $this->original_l) ? $this->replaceUrl($this->home_dir.$this->request_uri_no_language, $d) : $this->home_dir.$this->request_uri_no_language;
1131
- if ($link == $this->home_dir.'/' && get_option('wg_auto_switch') == 'on') {
1132
  $link = $link . '?no_lredirect=true';
1133
  }
1134
  $list .= '<li class="wg-li ' . $flag_class . $d . '"><a data-wg-notranslate href="' . $link . '">' . ($withname ? ($full ? WeglotUtils::getLangNameFromCode($d, false) : strtoupper($d)) : '') . '</a></li>';
@@ -1139,7 +1200,7 @@ class Weglot
1139
 
1140
  $moreclass = (get_option('is_dropdown') == 'on') ? 'wg-drop ' : 'wg-list ';
1141
 
1142
- $aside1 = ($is_menu && ! $is_dropdown) ? '' : '<aside data-wg-notranslate class="' . $moreclass . 'country-selector closed" onclick="openClose(this);" >';
1143
  $aside2 = ($is_menu && ! $is_dropdown) ? '' : '</aside>';
1144
 
1145
  $button = '<!--Weglot ' . WEGLOT_VERSION . '-->' . $aside1 . '<' . $tag . ' data-wg-notranslate class="wgcurrent wg-li ' . $flag_class . $current . '"><a href="#" onclick="return false;" >' . ($withname ? ($full ? WeglotUtils::getLangNameFromCode($current, false) : strtoupper($current)) : '') . '</a></' . $tag . '>' . $list . $aside2;
1
  <?php
2
  /**
3
  * @package Weglot
4
+ * @version 1.12
5
  */
6
 
7
  /*
12
  Author URI: https://weglot.com/
13
  Text Domain: weglot
14
  Domain Path: /languages/
15
+ Version: 1.12
16
  */
17
 
18
  /*
41
  }
42
 
43
 
44
+ define('WEGLOT_VERSION', '1.12');
45
  define('WEGLOT_DIR', dirname(__FILE__));
46
  define('WEGLOT_BNAME', plugin_basename(__FILE__));
47
  define('WEGLOT_DIRURL', plugin_dir_url(__FILE__));
52
  require_once WEGLOT_DIR . '/simple_html_dom.php';
53
  require_once WEGLOT_DIR . '/WeglotWidget.php';
54
 
55
+ use Weglot\WeglotContext;
56
  use Weglot\Helpers\WeglotUtils;
57
  use Weglot\Helpers\WeglotLang;
58
+ use Weglot\Helpers\WeglotUrl;
59
  use Weglot\Notices\AdminNotices;
60
  use Weglot\Third\Yoast\RedirectHandler;
61
 
62
+ $dirYoastPremum = plugin_dir_path(__DIR__) . "wordpress-seo-premium";
 
 
 
63
 
64
+ if (file_exists($dirYoastPremum . '/wp-seo-premium.php')) {
65
+ if (!function_exists('is_plugin_active')) {
66
+ include_once(ABSPATH . 'wp-admin/includes/plugin.php');
67
+ }
 
 
 
 
68
 
69
+ $yoastPluginData = get_plugin_data($dirYoastPremum . '/wp-seo-premium.php');
70
+ $dirYoastPremiumInside = $dirYoastPremum . '/premium/';
71
+
72
+ // Override yoast redirect
73
+ if (
74
+ ! is_admin() &&
75
+ version_compare($yoastPluginData["Version"], '7.1.0', '>=') &&
76
+ is_plugin_active("wordpress-seo-premium/wp-seo-premium.php") &&
77
+ file_exists($dirYoastPremiumInside) &&
78
+ file_exists($dirYoastPremiumInside . 'classes/redirect/redirect-handler.php') &&
79
+ file_exists($dirYoastPremiumInside . 'classes/redirect/redirect-util.php')
80
+ ) {
81
+ require_once $dirYoastPremiumInside . 'classes/redirect/redirect-handler.php';
82
+ require_once $dirYoastPremiumInside . 'classes/redirect/redirect-util.php';
83
 
84
+ $redirectHandler = new RedirectHandler();
85
+ $redirectHandler->load();
86
+ }
87
  }
88
 
89
 
91
  * Singleton class Weglot */
92
  class Weglot
93
  {
 
 
 
94
  private $request_uri;
95
  private $home_dir;
96
  private $network_paths;
112
 
113
  if (function_exists('apache_get_modules') && ! in_array('mod_rewrite', apache_get_modules())) {
114
  $this->services["AdminNotices"]->wgRequireRewriteModule();
 
115
  }
116
 
117
  $this->services["AdminNotices"]->thirdNotices();
122
  add_action('wp', array( $this, 'rr_404_my_event' ));
123
  add_filter('plugin_action_links_' . plugin_basename(__FILE__), array( $this, 'wg_plugin_action_links' ));
124
 
125
+ WeglotContext::setOriginalLanguage(get_option('original_l'));
126
+ WeglotContext::setDestinationLanguage(get_option('destination_l'));
127
+ WeglotContext::setHomeDirectory(WeglotUrl::getHomeDirectory());
128
 
129
+
130
+ $this->request_uri = $this->getRequestUri(WeglotContext::getHomeDirectory());
131
  $this->network_paths = $this->getListOfNetworkPath();
132
 
133
  $this->noredirect = false;
142
  }
143
  }
144
 
145
+ $this->request_uri = str_replace('?no_lredirect=true', '', $this->request_uri);
146
+ $curr = $this->getLangFromUrl($this->request_uri);
147
+ $currentLang = $curr ? $curr : WeglotContext::getOriginalLanguage();
148
+
149
+ WeglotContext::setCurrentLanguage($currentLang);
150
+
151
+ $this->request_uri_no_language = (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) ? substr($this->request_uri, 3) : $this->request_uri;
152
 
153
+ if (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) {
154
  $_SERVER['REQUEST_URI'] = str_replace(
155
+ '/' . WeglotContext::getCurrentLanguage() .
156
  '/',
157
  '/',
158
  $_SERVER['REQUEST_URI']
159
  );
160
  }
161
 
162
+ if (WeglotUtils::isLanguageRTL(WeglotContext::getCurrentLanguage())) {
163
  $GLOBALS['text_direction'] = 'rtl';
164
  } else {
165
  $GLOBALS['text_direction'] = 'ltr';
167
 
168
  add_filter('woocommerce_get_cart_url', array( $this,'filter_woocommerce_get_cart_url'));
169
  add_filter('woocommerce_get_checkout_url', array( $this,'filter_woocommerce_get_cart_url'));
170
+ add_filter('woocommerce_payment_successful_result', array( $this,'filter_woocommerce_payment_successful_result'));
171
  add_filter('woocommerce_get_checkout_order_received_url', array( $this, 'filter_woocommerce_get_checkout_order_received_url'));
172
  add_action('woocommerce_reset_password_notification', array( $this, 'redirectUrlLostPassword'));
173
 
187
  $this->allowed = $apikey ? get_option('wg_allowed') : true;
188
 
189
  if (is_admin()) {
190
+ if (strpos($this->request_uri, 'page=weglot') !== false) {
191
  if ($this->translator) {
192
  try {
193
  $this->userInfo = $this->translator->getUserInfo();
209
 
210
 
211
  $isURLOK = $this->isEligibleURL($this->request_uri_no_language);
212
+
213
+ if($isURLOK || is_admin()){
214
+ add_action('widgets_init', array( $this, 'addWidget' ));
215
+ }
216
+
217
  if ($isURLOK) {
218
  add_action('wp_head', array( $this, 'add_alternate' ));
 
219
  add_shortcode('weglot_switcher', array( $this, 'wg_switcher_creation' ));
220
  if (get_option('is_menu') == 'on') {
221
  add_filter('wp_nav_menu_items', 'your_custom_menu_item', 10, 2);
232
  }
233
  }
234
 
235
+
236
  /**
237
  * Redirect URL Lost password for WooCommerce
238
  */
239
  public function redirectUrlLostPassword($url)
240
  {
241
+ if (WeglotContext::getCurrentLanguage() === WeglotContext::getOriginalLanguage()) {
242
  return;
243
  }
244
 
245
  $urlRedirect = add_query_arg('reset-link-sent', 'true', wc_get_account_endpoint_url('lost-password'));
246
+ $urlRedirect = $this->replaceUrl($urlRedirect, WeglotContext::getCurrentLanguage());
247
 
248
  wp_redirect($urlRedirect);
249
  exit;
299
 
300
  public function wg_plugin_action_links($links)
301
  {
302
+ $links[] = '<a href="' . esc_url(get_admin_url(null, 'admin.php?page=weglot')) . '">' . __('Settings', 'weglot') . '</a>';
303
  return $links;
304
  }
305
 
306
  public function filter_woocommerce_get_cart_url($wc_get_page_permalink)
307
  {
308
+ if (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) {
309
+ return $this->replaceUrl($wc_get_page_permalink, WeglotContext::getCurrentLanguage());
310
  } else {
311
  return $wc_get_page_permalink;
312
  }
313
  }
314
 
315
+ public function filter_woocommerce_payment_successful_result($result)
316
+ {
317
+ if (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) { // Not ajax
318
+ $result["redirect"] = $this->replaceUrl($result["redirect"], WeglotContext::getCurrentLanguage());
319
+ } else {
320
+ if (isset($_SERVER['HTTP_REFERER'])) { // ajax
321
+ $fromLanguage = $this->getLangFromUrl(WeglotUrl::URLToRelative($_SERVER['HTTP_REFERER']));
322
+ $result["redirect"] = $this->replaceUrl($result["redirect"], $fromLanguage);
323
+ }
324
+ }
325
+
326
+ return $result;
327
+ }
328
+
329
  public function filter_woocommerce_get_checkout_order_received_url($order_received_url)
330
+ {
331
+ if (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) { // Not ajax
332
+ if (substr(get_option('permalink_structure'), -1) != '/') {
333
+ return str_replace('/?key', '?key', $this->replaceUrl($order_received_url, WeglotContext::getCurrentLanguage()));
334
+ } else {
335
+ return str_replace('//?key', '/?key', str_replace('?key', '/?key', $this->replaceUrl($order_received_url, WeglotContext::getCurrentLanguage())));
336
+ }
337
+ } else { // ajax
338
+ if (isset($_SERVER['HTTP_REFERER'])) {
339
+ $l = $this->getLangFromUrl(WeglotUrl::URLToRelative($_SERVER['HTTP_REFERER']));
340
+ if ($l && $l != WeglotContext::getOriginalLanguage()) {
341
+ if (substr(get_option('permalink_structure'), -1) != '/') {
342
+ return str_replace('/?key', '?key', $this->replaceUrl($order_received_url, $l));
343
+ } else {
344
+ return str_replace('//?key', '/?key', str_replace('?key', '/?key', $this->replaceUrl($order_received_url, $l)));
345
+ }
346
+ }
347
+ }
348
+ return $order_received_url;
349
+ }
350
+ }
351
 
352
  public function wg_log_redirect($redirect_to)
353
  {
354
+ if (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) {
355
+ return $this->replaceUrl($redirect_to, WeglotContext::getCurrentLanguage());
356
  } else {
357
  if (isset($_SERVER['HTTP_REFERER'])) {
358
+ $l = $this->getLangFromUrl(WeglotUrl::URLToRelative($_SERVER['HTTP_REFERER']));
359
+ if ($l && $l != WeglotContext::getOriginalLanguage()) {
360
  return $this->replaceUrl($redirect_to, $l);
361
  }
362
  }
368
  {
369
  $messageAndSubject = "<p>".$args['subject']."</p>".$args['message'];
370
 
371
+ if (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) {
372
+ $messageAndSubjectTranslated = $this->translateEmail($messageAndSubject, WeglotContext::getCurrentLanguage());
373
  } elseif (isset($_SERVER['HTTP_REFERER'])) {
374
+ $l = $this->getLangFromUrl(WeglotUrl::URLToRelative($_SERVER['HTTP_REFERER']));
375
+ if ($l && $l != WeglotContext::getOriginalLanguage()) { //If language in referer
376
  $messageAndSubjectTranslated = $this->translateEmail($messageAndSubject, $l);
377
  } elseif (strpos($_SERVER['HTTP_REFERER'], 'wg_language=') !== false) { //If language in parameter
378
  $pos = strpos($_SERVER['HTTP_REFERER'], 'wg_language=');
379
  $start = $pos + strlen('wg_language=');
380
  $l = substr($_SERVER['HTTP_REFERER'], $start, 2);
381
+ if ($l && $l != WeglotContext::getOriginalLanguage()) {
382
  $messageAndSubjectTranslated = $this->translateEmail($messageAndSubject, $l);
383
  }
384
  }
408
  public function init_function()
409
  {
410
  add_action('admin_menu', array( $this, 'plugin_menu' ));
411
+ add_action('admin_head', array( $this, 'menuOrderCount' ));
412
+
413
  add_action('admin_init', array( $this, 'plugin_settings' ));
414
+ add_action('admin_enqueue_scripts', array( $this, 'adminEnqueueScripts' ));
415
+ add_action('wp_enqueue_scripts', array( $this, 'enqueueScripts' ));
416
+ add_action('login_enqueue_scripts', array( $this, 'enqueueScripts' ));
417
 
418
+ if(defined('AMPFORWP_PLUGIN_DIR')){ // compatibility with ampforwp
419
+ add_action('amp_post_template_css', array( $this, 'cssCustomAmp' ));
420
+ }
421
+
422
+ $dest = explode(',', WeglotContext::getDestinationLanguage());
423
 
424
  if ($this->request_uri == '/' && ! $this->noredirect && ! WeglotUtils::is_bot()) { // front_page
425
 
428
  $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
429
  // exit(print_r($dest));
430
  if (in_array($lang, $dest)) {
431
+ wp_safe_redirect(WeglotContext::getHomeDirectory() . "/$lang/");
432
  exit();
433
  }
434
  }
447
  add_action('template_redirect', array( $this, 'kill_canonical_wg_92103' ), 1);
448
  }
449
 
450
+ /* Putting it in init makes that buffer deeper than caching ob */
451
+ ob_start(array($this, 'treatPage' ));
452
+ }
453
+
454
+
455
+ public function enqueueScriptsAmp(){
456
+ ?>
457
+ <link rel="stylesheet" href="<?php echo WEGLOT_RESURL . 'wp-weglot-css.css'?>" />
458
+ <?php
459
+ }
460
+
461
+ public function cssCustomAmp(){
462
+ echo $this->getInlineCSS();
463
+ ?>
464
+ .weglot-selector{
465
+ display:none;
466
+ }
467
+ <?php
468
+ }
469
+
470
+ public function enqueueScripts()
471
+ {
472
+ // Add JS
473
+ wp_register_script('wp-weglot-js', WEGLOT_RESURL . 'wp-weglot-js.js', false, WEGLOT_VERSION, false);
474
+ wp_enqueue_script('wp-weglot-js');
475
+
476
+ // Add CSS
477
+ wp_register_style('wp-weglot-css', WEGLOT_RESURL . 'wp-weglot-css.css', false, WEGLOT_VERSION, false);
478
+ wp_enqueue_style('wp-weglot-css');
479
 
480
+ wp_add_inline_style('wp-weglot-css', $this->getInlineCSS());
481
+ }
482
+
483
+ public function adminEnqueueScripts($page)
484
+ {
485
+ if (!in_array($page, array("toplevel_page_weglot", "settings_page_weglot-status"))) {
486
+ return;
487
+ }
488
+
489
+ $this->enqueueScripts();
490
+
491
+ // Add Admin JS
492
+ wp_register_script('wp-weglot-admin-js', WEGLOT_RESURL . 'wp-weglot-admin-js.js', array( 'jquery' ), WEGLOT_VERSION, true);
493
+ wp_enqueue_script('wp-weglot-admin-js');
494
+
495
+ // Add Admin CSS
496
+ wp_register_style('wp-weglot-admin-css', WEGLOT_RESURL . 'wp-weglot-admin-css.css', false, WEGLOT_VERSION, false);
497
+ wp_enqueue_style('wp-weglot-admin-css');
498
+
499
+ // Add Selectize JS
500
+ wp_enqueue_script('jquery-ui', WEGLOT_RESURL . 'selectize/js/jquery-ui.min.js', array( 'jquery' ), WEGLOT_VERSION, true);
501
+ wp_enqueue_script('jquery-selectize', WEGLOT_RESURL . 'selectize/js/selectize.min.js', array( 'jquery' ), WEGLOT_VERSION, true);
502
+ // wp_enqueue_style( 'selectize-css', WEGLOT_RESURL . 'selectize/css/selectize.css', array(), $ver );
503
+ wp_enqueue_style('selectize-defaut-css', WEGLOT_RESURL . 'selectize/css/selectize.default.css', array(), WEGLOT_VERSION);
504
+
505
+ if (! function_exists('is_plugin_active')) { // Need to refactor enqueue script
506
+ require_once(ABSPATH . '/wp-admin/includes/plugin.php');
507
+ }
508
+
509
+ if ($this->services["AdminNotices"]->hasGTranslatePlugin()) {
510
+ $customCss = "
511
  .gt-admin-notice{
512
  display:none !important;
513
  }
514
  ";
515
+
516
+ wp_add_inline_style('wp-weglot-css', $customCss);
517
+ }
518
+ }
519
+
520
+
521
+ /**
522
+ * @return void
523
+ */
524
+ public function menuOrderCount()
525
+ {
526
+ global $submenu;
527
+
528
+ if (isset($submenu["weglot"])) {
529
+ foreach ($submenu["weglot"] as $key => $value) {
530
+ if ($value[2] === "weglot-status" || $value[2] === "weglot") {
531
+ unset($submenu["weglot"][$key]);
532
  }
533
  }
534
  }
 
 
 
535
  }
536
 
537
  public function add_alternate()
538
  {
539
+ if (WeglotContext::getDestinationLanguage() != '') {
540
 
541
+ // $thisL = WeglotContext::getCurrentLanguage();
542
+ $dest = explode(',', WeglotContext::getDestinationLanguage());
543
 
544
+ $full_url = (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) ? str_replace('/' . WeglotContext::getCurrentLanguage() . '/', '/', $this->full_url($_SERVER)) : $this->full_url($_SERVER);
545
+ $output = '<link rel="alternate" hreflang="' . WeglotContext::getOriginalLanguage() . '" href="' . $full_url . '" />' . "\n";
546
  foreach ($dest as $d) {
547
  $output .= '<link rel="alternate" hreflang="' . $d . '" href="' . $this->replaceUrl($full_url, $d) . '" />' . "\n";
548
  }
556
  }
557
  }
558
 
 
 
 
 
 
559
  public function rr_404_my_event()
560
  {
561
 
562
  // regex logic here
563
  $isURLOK = $this->isEligibleURL($this->request_uri_no_language);
564
+ if (! $isURLOK && WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) {
565
  global $wp_query;
566
  $wp_query->set_404();
567
  status_header(404);
575
 
576
  public function plugin_menu()
577
  {
578
+ $hook = add_menu_page('Weglot', 'Weglot', 'manage_options', 'weglot', array( $this, 'plugin_settings_page' ), WEGLOT_DIRURL . '/images/weglot_fav_bw.png');
579
+ add_submenu_page('weglot', 'Status', 'Status', 'manage_options', 'weglot-status', array($this, "weglot_status_page"));
580
+
581
 
582
  // add_action('load-'.$hook,array($this, 'updateRewriteRule'));
583
  if (isset($this->request_uri_no_language)
584
  // && isset( $_POST['settings-updated-nonce'] )
585
  && $this->request_uri_no_language
586
+ && strpos($this->request_uri_no_language, 'page=weglot') !== false
587
  && strpos($this->request_uri_no_language, 'settings-updated=true') !==
588
  false) {
589
+ $d = explode(',', preg_replace('/\s+/', '', trim(WeglotContext::getDestinationLanguage(), ',')));
590
  $accepted = WeglotLang::getCodeLangs();
591
  foreach ($d as $k => $l) {
592
+ if (! in_array($l, $accepted) || $l == WeglotContext::getOriginalLanguage()) {
593
  unset($d[ $k ]);
594
  }
595
  }
596
  update_option('destination_l', implode(',', $d));
597
+ WeglotContext::setDestinationLanguage(implode(',', $d));
598
 
599
  /* Display Box */
600
  if (! get_option('show_box')) {
602
  }
603
 
604
  if ($this->userInfo['plan'] <= 0 || in_array($this->userInfo['plan'], array( 18, 19, 1001, 1002 ))) {
605
+ $d = explode(',', preg_replace('/\s+/', '', trim(WeglotContext::getDestinationLanguage(), ',')));
606
+ WeglotContext::setDestinationLanguage($d[0]);
607
+ update_option('destination_l', WeglotContext::getDestinationLanguage());
608
  }
609
  }
610
  }
611
 
612
+ public function weglot_status_page()
613
+ {
614
+ include(WEGLOT_DIR . '/includes/wg-status-page.php');
615
+ }
616
+
617
  public function plugin_settings()
618
  {
619
  register_setting('my-plugin-settings-group', 'project_key');
620
  register_setting('my-plugin-settings-group', 'original_l');
621
  register_setting('my-plugin-settings-group', 'destination_l');
622
  register_setting('my-plugin-settings-group', 'wg_auto_switch');
623
+ register_setting('my-plugin-settings-group', 'wg_exclude_amp');
624
  register_setting('my-plugin-settings-group', 'override_css');
625
  register_setting('my-plugin-settings-group', 'flag_css');
626
  register_setting('my-plugin-settings-group', 'with_flags');
646
 
647
  public function translateEmail($body, $l)
648
  {
649
+ $translatedEmail = $this->translator->translateDomFromTo($body, WeglotContext::getOriginalLanguage(), $l);
650
  return $translatedEmail;
651
  }
652
  public function treatPage($final)
653
  {
654
  $request_uri = $this->request_uri;
655
+ if (! is_admin() && strpos($request_uri, 'jax') === false && WeglotContext::getOriginalLanguage() != '' && WeglotContext::getDestinationLanguage() != '') {
 
656
  // $final = file_get_contents(__DIR__.'/content.html'); //Testing purpose.
657
  // Get the original request
658
  $url = $this->request_uri_no_language;
659
+
660
  if ($this->isEligibleURL($url) && WeglotUtils::is_HTML($final)) {
661
 
662
  // If a language is set, we translate the page & links.
663
+ if (WeglotContext::getCurrentLanguage() != WeglotContext::getOriginalLanguage()) {
664
  try {
665
+ $l = WeglotContext::getCurrentLanguage();
666
  $final = $this->translatePageTo($final, $l);
667
  } catch (\Weglot\Exceptions\WeglotException $e) {
668
  $final .= '<!--Weglot error : ' . $e->getMessage() . '-->';
695
  $button = WeglotUtils::str_lreplace('<aside data-wg-notranslate class="', '<aside data-wg-notranslate class="wg-default ', $button);
696
  $final = (strpos($final, '</body>') !== false) ? WeglotUtils::str_lreplace('</body>', $button . ' </body>', $final) : WeglotUtils::str_lreplace('</footer>', $button . ' </footer>', $final);
697
  }
698
+
699
+ return $final;
700
+ } elseif ($this->isEligibleURL($url) && isset($final[0]) && $final[0] == '{' || (isset($final[0]) && $final[0] == '[' && (isset($final[1]) && $final[1] == '{'))) {
 
701
  $thisL = $this->getLangFromUrl(
702
+ WeglotUrl::URLToRelative(
703
  $_SERVER['HTTP_REFERER']
704
  )
705
  );
730
  return $final;
731
  }
732
  } elseif ((strpos($request_uri, 'jax') !== false) &&
733
+ WeglotContext::getDestinationLanguage() != '' && WeglotContext::getOriginalLanguage() != '' && isset(
734
  $_SERVER['HTTP_REFERER']
735
  ) && strpos($_SERVER['HTTP_REFERER'], 'admin') === false) {
736
  $thisL = $this->getLangFromUrl(
737
+ WeglotUrl::URLToRelative(
738
  $_SERVER['HTTP_REFERER']
739
  )
740
  );
741
  if (isset($thisL) && $thisL != '') {
742
  try {
743
+ if (isset($final[0]) && $final[0] == '{' || (isset($final[0]) && $final[0] == '[' && isset($final[1]) && $finale[1] == '{')) {
744
  $json = json_decode($final, true);
745
  if (json_last_error() == JSON_ERROR_NONE) {
746
  $jsonT = $this->translateArray($json, $thisL);
788
  if ($this->allowed == 0) {
789
  return $final . '<!--Not allowed-->';
790
  }
791
+
792
+ $translatedPage = $this->translator->translateDomFromTo($final, WeglotContext::getOriginalLanguage(), $l); // $page is your html page
793
 
794
  $this->modifyLink('/<a([^\>]+?)?href=(\"|\')([^\s\>]+?)(\"|\')([^\>]+?)?>/', $translatedPage, $l, 'A');
795
  $this->modifyLink('/<([^\>]+?)?data-link=(\"|\')([^\s\>]+?)(\"|\')([^\>]+?)?>/', $translatedPage, $l, 'DATALINK');
851
 
852
  return (
853
  (($current_url[0] == 'h' && $parsed_url['host'] == $_SERVER['HTTP_HOST'])
854
+ || (isset($current_url[0]) && $current_url[0] == '/' && (isset($current_url[1])) && $current_url[1] != '/'))
855
  && strpos($current_url, $admin_url) === false
856
  && strpos($current_url, 'wp-login') === false
857
  && !$this->isLinkAFile($current_url)
870
  $sometags = null,
871
  $sometags2 = null
872
  ) {
 
873
  $translatedPage = preg_replace('/<a' . preg_quote($sometags, '/') . 'href=' .
874
  preg_quote($quote1 . $current_url . $quote2, '/') . '/', '<a' . $sometags . 'href=' . $quote1 . $this->replaceUrl(
875
  $current_url,
987
  /* Urls functions */
988
  public function replaceUrl($url, $l)
989
  {
990
+ //$home_dir = WeglotContext::getHomeDirectory();
991
 
992
  $parsed_url = parse_url($url);
993
  $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
1008
  "/$l/") ?
1009
  "$scheme$user$pass$host$port$path$query$fragment" : "$scheme$user$pass$host$port/$l$path$query$fragment";
1010
 
1011
+ foreach (array_reverse($this->network_paths) as $np) {
1012
  if (strlen($np) > 2 && strpos($urlTranslated, $np) !==
1013
  false) {
1014
  $urlTranslated = str_replace(
1039
  $paths = array();
1040
 
1041
  if (is_multisite()) {
1042
+ $sites = get_sites(array( 'number' => 0 ));
1043
  foreach ($sites as $site) {
1044
  $path = $site->path;
1045
  array_push($paths, $path);
1046
  }
1047
  } else {
1048
+ array_push($paths, WeglotContext::getHomeDirectory().'/');
1049
  }
1050
 
1051
  return $paths;
1057
  }
1058
  public function isEligibleURL($url)
1059
  {
1060
+ $url = urldecode(WeglotUrl::URLToRelative($url));
1061
  //Format exclude URL
1062
  $excludeURL = get_option('exclude_url');
1063
 
1066
 
1067
  $excludedUrls = explode(',', $excludeURL);
1068
  foreach ($excludedUrls as &$ex_url) {
1069
+ $ex_url = WeglotUrl::URLToRelative($ex_url);
1070
  }
1071
  $excludeURL = implode(',', $excludedUrls);
1072
  }
1074
 
1075
  $exclusions = preg_replace('#\s+#', ',', $excludeURL);
1076
 
1077
+ $listRegex = [];
1078
+ if (!empty($exclusions)) {
1079
  $listRegex = explode(',', $exclusions);
1080
  }
1081
 
1082
 
1083
+ $excludeAmp = get_option("wg_exclude_amp", 'on');
1084
+ if ($excludeAmp === "on") {
1085
+ $listRegex[] = apply_filters('weglot_regex_amp', '([&\?/])amp(/)?$');
1086
  }
1087
 
1088
  foreach ($listRegex as $regex) {
1101
  return str_replace('/', '\/', $str);
1102
  }
1103
 
 
 
 
 
 
 
 
 
 
 
 
1104
 
 
 
 
 
 
 
 
1105
  public function getRequestUri($home_dir)
1106
  {
1107
  if ($home_dir) {
1113
  public function getLangFromUrl($request_uri)
1114
  {
1115
  $l = null;
1116
+ $dest = explode(',', WeglotContext::getDestinationLanguage());
1117
  foreach ($dest as $d) {
1118
  if (substr($request_uri, 0, 4) == '/' . $d . '/') {
1119
  $l = $d;
1146
  public function getInlineCSS()
1147
  {
1148
  $css = get_option('override_css');
1149
+ if ((WeglotUtils::isLanguageRTL(WeglotContext::getOriginalLanguage()) && ! WeglotUtils::isLanguageRTL(WeglotContext::getCurrentLanguage())) ||
1150
+ (! WeglotUtils::isLanguageRTL(WeglotContext::getOriginalLanguage()) && WeglotUtils::isLanguageRTL(WeglotContext::getCurrentLanguage()))) {
1151
  $css .= get_option('rtl_ltr_style');
1152
  }
1153
  if (! is_admin()) {
1181
  $type_flags = get_option('type_flags') ? get_option('type_flags') : 0;
1182
  $flag_class .= $type_flags == 0 ? '' : 'flag-' . $type_flags . ' ';
1183
 
1184
+ $current = WeglotContext::getCurrentLanguage();
1185
  $list = $is_dropdown ? '<ul>' : '';
1186
+ $destEx = explode(',', WeglotContext::getDestinationLanguage());
1187
+ array_unshift($destEx, WeglotContext::getOriginalLanguage());
1188
+
1189
  foreach ($destEx as $d) {
1190
  if ($d != $current) {
1191
+ $link = ($d != WeglotContext::getOriginalLanguage()) ? $this->replaceUrl(WeglotContext::getHomeDirectory().$this->request_uri_no_language, $d) : WeglotContext::getHomeDirectory().$this->request_uri_no_language;
1192
+ if ($link == WeglotContext::getHomeDirectory().'/' && get_option('wg_auto_switch') == 'on') {
1193
  $link = $link . '?no_lredirect=true';
1194
  }
1195
  $list .= '<li class="wg-li ' . $flag_class . $d . '"><a data-wg-notranslate href="' . $link . '">' . ($withname ? ($full ? WeglotUtils::getLangNameFromCode($d, false) : strtoupper($d)) : '') . '</a></li>';
1200
 
1201
  $moreclass = (get_option('is_dropdown') == 'on') ? 'wg-drop ' : 'wg-list ';
1202
 
1203
+ $aside1 = ($is_menu && ! $is_dropdown) ? '' : '<aside data-wg-notranslate class="' . $moreclass . 'country-selector closed weglot-selector" onclick="openClose(this);" >';
1204
  $aside2 = ($is_menu && ! $is_dropdown) ? '' : '</aside>';
1205
 
1206
  $button = '<!--Weglot ' . WEGLOT_VERSION . '-->' . $aside1 . '<' . $tag . ' data-wg-notranslate class="wgcurrent wg-li ' . $flag_class . $current . '"><a href="#" onclick="return false;" >' . ($withname ? ($full ? WeglotUtils::getLangNameFromCode($current, false) : strtoupper($current)) : '') . '</a></' . $tag . '>' . $list . $aside2;