-
Notifications
You must be signed in to change notification settings - Fork 6
/
transposh.php
2238 lines (2006 loc) · 93 KB
/
transposh.php
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Plugin Name: Transposh Translation Filter
Plugin URI: https://transposh.org/
Description: Translation filter for WordPress, After enabling please set languages at the <a href="admin.php?page=tp_main">the options page</a> Want to help? visit our development site at <a href="https://github.com/oferwald/transposh">github</a>.
Author: Team Transposh
Version: %VERSION%
Author URI: https://transposh.org/
License: GPL (https://www.gnu.org/licenses/gpl.txt)
Text Domain: transposh
Domain Path: /langs
*/
/*
* Transposh v%VERSION%
* https://transposh.org/
*
* Copyright %YEAR%, Team Transposh
* Licensed under the GPL Version 2 or higher.
* https://transposh.org/license
*
* Date: %DATE%
*/
//avoid direct calls to this file where wp core files not present
if (!function_exists('add_action')) {
header('Status: 403 Forbidden');
header('HTTP/1.1 403 Forbidden');
exit();
}
require_once("core/logging.php");
require_once("core/constants.php");
require_once("core/utils.php");
require_once("core/parser.php");
require_once("wp/transposh_db.php");
require_once("wp/transposh_widget.php");
require_once("wp/transposh_admin.php");
require_once("wp/transposh_options.php");
require_once("wp/transposh_postpublish.php");
require_once("wp/transposh_backup.php");
require_once("wp/transposh_3rdparty.php");
require_once("wp/transposh_mail.php");
//require_once("wp/transposh_wpmenu.php");
/**
* This class represents the complete plugin
*/
class transposh_plugin {
// List of contained objects
/** @var transposh_plugin_options An options object */
public $options;
/** @var transposh_plugin_admin Admin page */
private $admin;
/** @var transposh_plugin_widget Widget control */
public $widget;
/** @var transposh_database The database class */
public $database;
/** @var transposh_postpublish Happens after editing */
public $postpublish;
/** @var transposh_3rdparty Happens after editing */
private $third_party;
// list of properties
/** @var string The site url */
public $home_url;
/** @var a url of the request, assuming there was no language */
private $clean_url;
/** @var string The url to the plugin directory */
public $transposh_plugin_url;
/** @var string The directory of the plugin */
public $transposh_plugin_dir;
/** @var string Plugin main file and dir */
public $transposh_plugin_basename;
/** @var boolean Enable rewriting of URLs */
public $enable_permalinks_rewrite;
/** @var string The language to translate the page to, from params */
public $target_language;
/** @var string The language extracted from the url */
public $tgl;
/** @var boolean Are we currently editing the page? */
public $edit_mode;
/** @var string Error message displayed for the admin in case of failure */
private $admin_msg;
/** @var string Saved search variables */
private $search_s;
/** @var variable to make sure we only attempt to fix the url once, could have used remove_filter */
private $got_request = false;
/** @var might be that page is json... */
private $attempt_json = false;
/** @var boolean Is the wp_redirect being called by transposh? */
private $transposh_redirect = false;
/** @var boolean Did we get to process but got an empty buffer with no language? (someone flushed us) */
private $tried_buffer = false;
/** @var boolean Do I need to check for updates by myself? After wordpress checked his */
private $do_update_check = false;
/**
* class constructor
*/
function __construct() {
// create and initialize sub-objects
$this->options = new transposh_plugin_options();
$this->database = new transposh_database($this);
$this->admin = new transposh_plugin_admin($this);
$this->widget = new transposh_plugin_widget($this);
$this->postpublish = new transposh_postpublish($this);
$this->third_party = new transposh_3rdparty($this);
$this->mail = new transposh_mail($this);
// initialize logger
if ($this->options->debug_enable) {
$GLOBALS['tp_logger'] = tp_logger::getInstance(true);
$GLOBALS['tp_logger']->show_caller = true;
$GLOBALS['tp_logger']->set_debug_level($this->options->debug_loglevel);
$GLOBALS['tp_logger']->set_log_file($this->options->debug_logfile);
$GLOBALS['tp_logger']->set_remoteip($this->options->debug_remoteip);
}
// "global" vars
$this->home_url = get_option('home');
// Handle windows ('C:\wordpress')
$local_dir = preg_replace("/\\\\/", "/", dirname(__FILE__));
// Get last directory name
$local_dir = preg_replace("/.*\//", "", $local_dir);
$this->transposh_plugin_url = preg_replace('#^https?://#', '//', WP_PLUGIN_URL . '/' . $local_dir);
// TODO - test on more platforms - this failed in 2.7.1 so I am reverting for now...
//$tr_plugin_url= plugins_url('', __FILE__);
$this->transposh_plugin_dir = plugin_dir_path(__FILE__);
if ($this->options->debug_enable)
tp_logger('Transposh object created: ' . transposh_utils::get_clean_server_var('REQUEST_URI'), 3);
$this->transposh_plugin_basename = plugin_basename(__FILE__);
//Register some functions into wordpress
if ($this->options->debug_enable) {
//tp_logger(preg_replace('|^' . preg_quote(WP_PLUGIN_DIR, '|') . '/|', '', __FILE__), 4); // includes transposh dir and php
// tp_logger($this->get_plugin_name());
tp_logger(plugin_basename(__FILE__));
}
// TODO: get_class_methods to replace said mess, other way?
add_filter('plugin_action_links_' . $this->transposh_plugin_basename, array(&$this, 'plugin_action_links'));
add_filter('query_vars', array(&$this, 'parameter_queryvars'));
add_filter('rewrite_rules_array', array(&$this, 'update_rewrite_rules'));
if ($this->options->enable_url_translate) {
add_filter('request', array(&$this, 'request_filter'));
}
add_filter('comment_post_redirect', array(&$this, 'comment_post_redirect_filter'));
add_filter('comment_text', array(&$this, 'comment_text_wrap'), 9999); // this is a late filter...
add_action('init', array(&$this, 'on_init'), 0); // really high priority
// add_action('admin_init', array(&$this, 'on_admin_init')); might use to mark where not to work?
add_action('parse_request', array(&$this, 'on_parse_request'), 0); // should have high enough priority
add_action('plugins_loaded', array(&$this, 'plugin_loaded'));
add_action('shutdown', array(&$this, 'on_shutdown'));
add_action('wp_print_styles', array(&$this, 'add_transposh_css'));
add_action('wp_print_scripts', array(&$this, 'add_transposh_js'));
if (!$this->options->dont_add_rel_alternate) {
add_action('wp_head', array(&$this, 'add_rel_alternate'));
}
// add_action('wp_head', array(&$this,'add_transposh_async'));
add_action('transposh_backup_event', array(&$this, 'run_backup'));
add_action('transposh_oht_event', array(&$this, 'run_oht'));
add_action('comment_post', array(&$this, 'add_comment_meta_settings'), 1);
// our translation proxy
// add_action('wp_ajax_tp_gp', array(&$this, 'on_ajax_nopriv_tp_gp'));
// add_action('wp_ajax_nopriv_tp_gp', array(&$this, 'on_ajax_nopriv_tp_gp'));
add_action('wp_ajax_tp_tp', array(&$this, 'on_ajax_nopriv_tp_tp')); // translate suggest proxy
add_action('wp_ajax_nopriv_tp_tp', array(&$this, 'on_ajax_nopriv_tp_tp'));
add_action('wp_ajax_tp_oht', array(&$this, 'on_ajax_nopriv_tp_oht'));
add_action('wp_ajax_nopriv_tp_oht', array(&$this, 'on_ajax_nopriv_tp_oht'));
// ajax actions in editor
// TODO - remove some for non translators
add_action('wp_ajax_tp_history', array(&$this, 'on_ajax_nopriv_tp_history'));
add_action('wp_ajax_nopriv_tp_history', array(&$this, 'on_ajax_nopriv_tp_history'));
add_action('wp_ajax_tp_translation', array(&$this, 'on_ajax_nopriv_tp_translation'));
add_action('wp_ajax_nopriv_tp_translation', array(&$this, 'on_ajax_nopriv_tp_translation'));
add_action('wp_ajax_tp_ohtcallback', array(&$this, 'on_ajax_nopriv_tp_ohtcallback'));
add_action('wp_ajax_nopriv_tp_ohtcallback', array(&$this, 'on_ajax_nopriv_tp_ohtcallback'));
add_action('wp_ajax_tp_trans_alts', array(&$this, 'on_ajax_nopriv_tp_trans_alts'));
add_action('wp_ajax_nopriv_tp_trans_alts', array(&$this, 'on_ajax_nopriv_tp_trans_alts'));
add_action('wp_ajax_tp_cookie', array(&$this, 'on_ajax_nopriv_tp_cookie'));
add_action('wp_ajax_nopriv_tp_cookie', array(&$this, 'on_ajax_nopriv_tp_cookie'));
add_action('wp_ajax_tp_cookie_bck', array(&$this, 'on_ajax_nopriv_tp_cookie_bck'));
add_action('wp_ajax_nopriv_tp_cookie_bck', array(&$this, 'on_ajax_nopriv_tp_cookie_bck'));
if (defined('FULL_VERSION')) { //** FULL VERSION
// For super proxy
add_action('superproxy_reg_event', array(&$this, 'superproxy_reg'));
if ($this->options->enable_superproxy) {
add_action('wp_ajax_proxy', array(&$this, 'on_ajax_nopriv_proxy'));
add_action('wp_ajax_nopriv_proxy', array(&$this, 'on_ajax_nopriv_proxy'));
}
}//** FULLSTOP
// comment_moderation_text - future filter TODO
// full post wrapping (should happen late)
add_filter('the_content', array(&$this, 'post_content_wrap'), 9999);
add_filter('the_excerpt', array(&$this, 'post_content_wrap'), 9999);
add_filter('the_title', array(&$this, 'post_wrap'), 9999, 2);
// allow to mark the language?
// add_action('admin_menu', array(&$this, 'transposh_post_language'));
// add_action('save_post', array(&$this, 'transposh_save_post_language'));
//TODO add_action('manage_comments_nav', array(&$this,'manage_comments_nav'));
//TODO comment_row_actions (filter)
// Intergrating with the gettext interface
if ($this->options->transposh_gettext_integration) {
add_filter('gettext', array(&$this, 'transposh_gettext_filter'), 10, 3);
add_filter('gettext_with_context', array(&$this, 'transposh_gettext_filter'), 10, 3);
add_filter('ngettext', array(&$this, 'transposh_ngettext_filter'), 10, 4);
add_filter('ngettext_with_context', array(&$this, 'transposh_ngettext_filter'), 10, 4);
add_filter('locale', array(&$this, 'transposh_locale_filter'));
}
// internal update mechnism - is disabled in wporg version unless user enabled this
//** WPORG VERSION
if (!defined('FULL_VERSION') && $this->options->allow_full_version_upgrade) {
//** WPORGSTOP
add_filter('http_request_args', array(&$this, 'filter_wordpress_org_update'), 10, 2);
add_filter('pre_set_site_transient_update_plugins', array(&$this, 'check_for_plugin_update'));
add_filter('plugins_api', array(&$this, 'plugin_api_call'), 10, 3);
//** WPORG VERSION
}
//** WPORGSTOP
// debug function for bad redirects
add_filter('wp_redirect', array(&$this, 'on_wp_redirect'), 10, 2);
add_filter('redirect_canonical', array(&$this, 'on_redirect_canonical'), 10, 2);
// support shortcodes
add_shortcode('tp', array(&$this, 'tp_shortcode'));
add_shortcode('tpe', array(&$this, 'tp_shortcode'));
//
// FUTURE add_action('update-custom_transposh', array(&$this, 'update'));
// CHECK TODO!!!!!!!!!!!!
$this->tgl = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('REQUEST_URI'), $this->home_url);
if (!$this->options->is_active_language($this->tgl)) {
$this->tgl = '';
}
register_activation_hook(__FILE__, array(&$this, 'plugin_activate'));
register_deactivation_hook(__FILE__, array(&$this, 'plugin_deactivate'));
}
/**
* Attempt to fix a wp_redirect being called by someone else to include the language
* hoping for no cycles
* @param string $location
* @param int $status
* @return string
*/
function on_wp_redirect($location, $status) {
// no point in mangling redirection if its our own or its the default language
if ($this->transposh_redirect || $this->options->is_default_language($this->target_language)) {
return $location;
}
tp_logger($status . ' ' . $location);
// $trace = debug_backtrace();
// tp_logger($trace);
// tp_logger($this->target_language);
$location = $this->rewrite_url($location);
return $location;
}
/**
* Internally used by transposh redirection, to avoid being rewritten by self
* assuming we know what we are doing when redirecting
* @param string $location
* @param int $status
*/
function tp_redirect($location, $status = 302) {
$this->transposh_redirect = true;
wp_redirect($location, $status);
}
/**
* Function to fix canonical redirection for some translated urls (such as tags with params)
* @param string $red - url wordpress assumes it will redirect to
* @param string $req - url that was originally requested
* @return mixed false if redirect unneeded - new url if we think we should
*/
function on_redirect_canonical($red, $req) {
tp_logger("$red .. $req", 4);
// if the urls are actually the same, don't redirect (same - if it had our proper take care of)
if ($this->rewrite_url($red) == urldecode($req)) {
return false;
}
// if this is not the default language, we need to make sure it redirects to what we believe is the proper url
if (!$this->options->is_default_language($this->target_language)) {
$red = str_replace(array('%2F', '%3A', '%3B', '%3F', '%3D', '%26'), array('/', ':', ';', '?', '=', '&'), urlencode($this->rewrite_url($red)));
}
return $red;
}
function get_clean_url() {
if (isset($this->clean_url)) {
return $this->clean_url;
}
//remove any language identifier and find the "clean" url, used for posting and calculating urls if needed
$this->clean_url = transposh_utils::cleanup_url(transposh_utils::get_clean_server_var('REQUEST_URI'), $this->home_url, true);
// we need this if we are using url translations
if ($this->options->enable_url_translate) {
$this->clean_url = transposh_utils::get_original_url($this->clean_url, '', $this->target_language, array($this->database, 'fetch_original'));
}
return $this->clean_url;
}
// function update() {file_location
// require_once('./admin-header.php');
/* $nonce = 'upgrade-plugin_' . $plugin;
$url = 'update.php?action=upgrade-plugin&plugin=' . $plugin;
$upgrader = new Plugin_Upgrader( new Plugin_Upgrader_Skin( compact('title', 'nonce', 'url', 'plugin') ) );
$upgrader->upgrade($plugin);
*/
// include('./admin-footer.php');
// }
/**
* Check if page is special (one that we normally should not touch
* @param string $url Url to check
* @return boolean Is it a special page?
*/
function is_special_page($url) {
return ( stripos($url, '/wp-login.php') !== FALSE ||
stripos($url, '/robots.txt') !== FALSE ||
stripos($url, '/wp-json/') !== FALSE ||
stripos($url, '/wp-admin/') !== FALSE ||
stripos($url, '/wp-comments-post') !== FALSE ||
stripos($url, '/main-sitemap.xsl') !== FALSE || //YOAST?
stripos($url, '.xsl') !== FALSE || //YOAST?
stripos($url, '.xml') !== FALSE || //YOAST?
stripos($url, '/xmlrpc.php') !== FALSE);
}
/**
* Called when the buffer containing the original page is flushed. Triggers the translation process.
* @param string $buffer Original page
* @return string Modified page buffer
*/
function process_page($buffer) { //php7?
/* if (!$this->target_language) {
global $wp;
$this->on_parse_request($wp);
} */
tp_logger('processing page hit with language:' . $this->target_language, 1);
$bad_content = false;
foreach (headers_list() as $header) {
if (stripos($header, 'Content-Type:') !== false) {
tp_logger($header);
if (stripos($header, 'text') === false && stripos($header, 'json') === false && stripos($header, 'rss') === false) {
tp_logger("won't do that - $header");
$bad_content = true;
}
}
}
$start_time = microtime(TRUE);
// Refrain from touching the administrative interface and important pages
if ($this->is_special_page(transposh_utils::get_clean_server_var('REQUEST_URI')) && !$this->attempt_json) {
tp_logger("Skipping translation for admin pages", 3);
} elseif ($bad_content) {
tp_logger("Seems like content we should not handle");
}
// This one fixed a bug transposh created with other pages (xml generator for other plugins - such as the nextgen gallery)
// TODO: need to further investigate (will it be needed?)
elseif ($this->target_language == '') {
tp_logger("Skipping translation where target language is unset", 3);
if (!$buffer) {
tp_logger("seems like we had a premature flushing");
$this->tried_buffer = true;
}
}
// Don't translate the default language unless specifically allowed to...
elseif ($this->options->is_default_language($this->target_language) && !$this->options->enable_default_translate) {
tp_logger("Skipping translation for default language {$this->target_language}", 3);
} else {
// This one allows to redirect to a static element which we can find, since the redirection will remove
// the target language, we are able to avoid nasty redirection loops
if (is_404()) {
global $wp;
if (isset($wp->query_vars['pagename']) && file_exists(ABSPATH . $wp->query_vars['pagename'])) { // Hmm
tp_logger('Redirecting a static file ' . $wp->query_vars['pagename'], 1);
$this->tp_redirect('/' . $wp->query_vars['pagename'], 301);
}
}
tp_logger("Translating " . transposh_utils::get_clean_server_var('REQUEST_URI') . " to: {$this->target_language} for: " . transposh_utils::get_clean_server_var('REMOTE_ADDR'), 1);
//translate the entire page
$parse = new tp_parser();
$parse->fetch_translate_func = array(&$this->database, 'fetch_translation');
$parse->prefetch_translate_func = array(&$this->database, 'prefetch_translations');
$parse->url_rewrite_func = array(&$this, 'rewrite_url');
$parse->split_url_func = array(&$this, 'split_url');
$parse->dir_rtl = (in_array($this->target_language, transposh_consts::$rtl_languages));
$parse->lang = $this->target_language;
$parse->default_lang = $this->options->is_default_language($this->target_language);
$parse->is_edit_mode = $this->edit_mode;
$parse->might_json = $this->attempt_json;
$parse->is_auto_translate = $this->is_auto_translate_permitted();
//** FULL VERSION
$parse->allow_ad = $this->options->widget_remove_logo;
//** FULLSTOP
// TODO - check this!
if (stripos(transposh_utils::get_clean_server_var('REQUEST_URI'), '/feed/') !== FALSE) {
tp_logger("in rss feed!", 2);
$parse->is_auto_translate = false;
$parse->is_edit_mode = false;
$parse->feed_fix = true;
}
$parse->change_parsing_rules(!$this->options->parser_dont_break_puncts, !$this->options->parser_dont_break_numbers, !$this->options->parser_dont_break_entities);
$buffer = $parse->fix_html($buffer);
$end_time = microtime(TRUE);
tp_logger('Translation completed in ' . ($end_time - $start_time) . ' seconds', 1);
}
return $buffer;
}
// function on_admin_init() {
// tp_logger("admin init called");
// }
/**
* Setup a buffer that will contain the contents of the html page.
* Once processing is completed the buffer will go into the translation process.
*/
function on_init() {
tp_logger('init ' . transposh_utils::get_clean_server_var('REQUEST_URI'), 4);
// the wp_rewrite is not available earlier so we can only set the enable_permalinks here
if (is_object($GLOBALS['wp_rewrite'])) {
if ($GLOBALS['wp_rewrite']->using_permalinks() && $this->options->enable_permalinks) {
tp_logger("enabling permalinks");
$this->enable_permalinks_rewrite = TRUE;
}
}
// this is an ajax special case, currently crafted and tested on buddy press, lets hope this won't make hell break loose.
// it basically sets language based on referred when accessing wp-load.php (which is the way bp does ajax)
tp_logger(substr(transposh_utils::get_clean_server_var('SCRIPT_FILENAME'), -11), 5);
if (substr(transposh_utils::get_clean_server_var('SCRIPT_FILENAME'), -11) == 'wp-load.php') {
$this->target_language = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url);
$this->attempt_json = true;
}
//buddypress old activity
if (isset($_POST['action']) && $_POST['action'] == 'activity_get_older_updates') {
$this->target_language = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url);
$this->attempt_json = true;
}
//alm news
if (isset($_GET['action']) && $_GET['action'] == 'alm_query_posts') {
$this->target_language = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url);
}
//woocommerce_update_order_review
if (isset($_POST['action']) && $_POST['action'] == 'woocommerce_update_order_review') {
$this->target_language = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url);
$this->attempt_json = true;
}
if (isset($_GET['wc-ajax']) && $_GET['wc-ajax'] == 'update_order_review') {
$this->target_language = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url);
$this->attempt_json = true;
}
//woocommerce_get_refreshed_fragments
if (isset($_POST['action']) && $_POST['action'] == 'woocommerce_get_refreshed_fragments') {
$this->target_language = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url);
$this->attempt_json = true;
}
if (isset($_POST['action']) && $_POST['action'] == 'woocommerce_add_to_cart') {
$this->target_language = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url);
$this->attempt_json = true;
}
tp_logger(transposh_utils::get_clean_server_var('REQUEST_URI'), 5);
if (strpos(transposh_utils::get_clean_server_var('REQUEST_URI'), '/wpv-ajax-pagination/') === true) {
tp_logger('wpv pagination', 5);
$this->target_language = transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url);
}
// load translation files for transposh
load_plugin_textdomain(TRANSPOSH_TEXT_DOMAIN, false, dirname(plugin_basename(__FILE__)) . '/langs');
//set the callback for translating the page when it's done
ob_start(array(&$this, "process_page"));
}
/**
* Page generation completed - flush buffer.
*/
function on_shutdown() {
//TODO !!!!!!!!!!!! ob_flush();
}
/**
* Update the url rewrite rules to include language identifier
* @param array $rules Old rewrite rules
* @return array New rewrite rules
*/
function update_rewrite_rules($rules) {
tp_logger("Enter update_rewrite_rules", 2);
if (!$this->options->enable_permalinks) {
tp_logger("Not touching rewrite rules - permalinks modification disabled by admin", 2);
return $rules;
}
$newRules = array();
$lang_prefix = "(" . str_replace(',', '|', $this->options->viewable_languages) . ")/";
$lang_parameter = "&" . LANG_PARAM . '=$matches[1]';
//catch the root url
$newRules[$lang_prefix . "?$"] = "index.php?lang=\$matches[1]";
tp_logger("\t {$lang_prefix} ?$ ---> index.php?lang=\$matches[1]", 4);
foreach ($rules as $key => $value) {
$original_key = $key;
$original_value = $value;
$key = $lang_prefix . $key;
//Shift existing matches[i] a step forward as we pushed new elements
//in the beginning of the expression
for ($i = 9; $i > 0; $i--) {
$value = str_replace('[' . $i . ']', '[' . ($i + 1) . ']', $value);
}
$value .= $lang_parameter;
tp_logger("\t $key ---> $value", 2);
$newRules[$key] = $value;
$newRules[$original_key] = $original_value;
tp_logger(": \t{$original_key} ---> {$original_value}", 4);
}
tp_logger("Exit update_rewrite_rules", 2);
return $newRules;
}
//function flush_transposh_rewrite_rules() {
//add_filter('rewrite_rules_array', array(&$this, 'update_rewrite_rules'));
// $GLOBALS['wp_rewrite']->flush_rules();
//}
/**
* Let WordPress know which parameters are of interest to us.
* @param array $vars Original queried variables
* @return array Modified array
*/
function parameter_queryvars($vars) {
tp_logger('inside query vars', 4);
$vars[] = LANG_PARAM;
$vars[] = EDIT_PARAM;
tp_logger($vars, 4);
return $vars;
}
/**
* Grabs and set the global language and edit params, they should be here
* @param WP $wp - here we get the WP class
*/
function on_parse_request($wp) {
tp_logger('on_parse_req', 3);
tp_logger($wp->query_vars);
// fix for custom-permalink (and others that might be double parsing?)
if ($this->target_language) {
return;
}
// first we get the target language
/* $this->target_language = (isset($wp->query_vars[LANG_PARAM])) ? $wp->query_vars[LANG_PARAM] : '';
if (!$this->target_language)
$this->target_language = $this->options->default_language;
tp_logger("requested language: {$this->target_language}"); */
// TODO TOCHECK!!!!!!!!!!!!!!!!!!!!!!!!!!1
$this->target_language = $this->tgl;
if (!$this->target_language) {
$this->target_language = $this->options->default_language;
}
tp_logger("requested language: {$this->target_language}", 3);
if ($this->tried_buffer) {
tp_logger("we will retrigger the output buffering");
ob_start(array(&$this, "process_page"));
}
// make themes that support rtl - go rtl http://wordpress.tv/2010/05/01/yoav-farhi-right-to-left-themes-sf10
if (in_array($this->target_language, transposh_consts::$rtl_languages)) {
global $wp_locale;
$wp_locale->text_direction = 'rtl';
}
// we'll go into this code of redirection only if we have options that need it (and no bot is involved, for the non-cookie)
// and this is not a special page or one that is refered by our site
// bots can skip this altogether
if (($this->options->enable_detect_redirect || $this->options->widget_allow_set_deflang || $this->options->enable_geoip_redirect) &&
!($this->is_special_page(transposh_utils::get_clean_server_var('REQUEST_URI')) || (transposh_utils::get_clean_server_var('HTTP_REFERER') != null && strpos(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url) !== false)) &&
!(transposh_utils::is_bot())) {
// we are starting a session if needed
if (!session_id()) {
session_start();
}
// no redirections if we already redirected in this session or we suspect cyclic redirections
if (!isset($_SESSION['TR_REDIRECTED']) && !(transposh_utils::get_clean_server_var('HTTP_REFERER') == transposh_utils::get_clean_server_var('REQUEST_URI'))) {
tp_logger('session redirection never happened (yet)', 2);
// we redirect once per session
$_SESSION['TR_REDIRECTED'] = true;
// redirect according to stored lng cookie, and than according to detection
if (isset($_COOKIE['TR_LNG']) && $this->options->widget_allow_set_deflang) {
if ($_COOKIE['TR_LNG'] != $this->target_language) {
$url = transposh_utils::rewrite_url_lang_param(transposh_utils::get_clean_server_var("REQUEST_URI"), $this->home_url, $this->enable_permalinks_rewrite, $_COOKIE['TR_LNG'], $this->edit_mode);
if ($this->options->is_default_language($_COOKIE['TR_LNG']))
//TODO - fix wrt translation
$url = transposh_utils::cleanup_url(transposh_utils::get_clean_server_var("REQUEST_URI"), $this->home_url);
tp_logger("redirected to $url because of cookie", 2);
$this->tp_redirect($url);
exit;
}
} else {
//**
if ($this->options->enable_detect_redirect) {
$bestlang = transposh_utils::prefered_language(explode(',', $this->options->viewable_languages), $this->options->default_language);
// we won't redirect if we should not, or this is a presumable bot
} elseif ($this->options->enable_geoip_redirect) {
$country = geoip_detect2_get_info_from_current_ip()->country->isoCode;
$bestlang = transposh_utils::language_from_country(explode(',', $this->options->viewable_languages), $country, $this->options->default_language);
}
if ($bestlang && $bestlang != $this->target_language) {
$url = transposh_utils::rewrite_url_lang_param(transposh_utils::get_clean_server_var('REQUEST_URI'), $this->home_url, $this->enable_permalinks_rewrite, $bestlang, $this->edit_mode);
if ($this->options->is_default_language($bestlang))
//TODO - fix wrt translation
$url = transposh_utils::cleanup_url(transposh_utils::get_clean_server_var('REQUEST_URI'), $this->home_url);
tp_logger("redirected to $url because of bestlang", 2);
$this->tp_redirect($url);
exit;
}
}
} else {
tp_logger('session was already redirected', 2);
}
}
// this method allows posts from the search box to maintain the language,
// TODO - it has a bug of returning to original language following search, which can be resolved by removing search from widget urls, but maybe later...
if (isset($wp->query_vars['s'])) {
if ($this->options->enable_search_translate) {
add_action('pre_get_posts', array(&$this, 'pre_post_search'));
add_action('posts_where_request', array(&$this, 'posts_where_request'));
}
if (transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url) && !transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('REQUEST_URI'), $this->home_url)) {
$this->tp_redirect(transposh_utils::rewrite_url_lang_param(transposh_utils::get_clean_server_var("REQUEST_URI"), $this->home_url, $this->enable_permalinks_rewrite, transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var('HTTP_REFERER'), $this->home_url), false)); //."&stop=y");
exit;
}
}
if (isset($wp->query_vars[EDIT_PARAM]) && $wp->query_vars[EDIT_PARAM] && $this->is_editing_permitted()) {
$this->edit_mode = true;
// redirect bots away from edit pages to avoid double indexing
if (transposh_utils::is_bot()) {
$this->tp_redirect(transposh_utils::rewrite_url_lang_param(transposh_utils::get_clean_server_var("REQUEST_URI"), $this->home_url, $this->enable_permalinks_rewrite, transposh_utils::get_language_from_url(transposh_utils::get_clean_server_var("REQUEST_URI"), $this->home_url), false), 301);
exit;
}
} else {
$this->edit_mode = false;
}
// We are removing our query vars since they are no longer needed and also make issues when a user select a static page as his home
unset($wp->query_vars[LANG_PARAM]);
unset($wp->query_vars[EDIT_PARAM]);
tp_logger("edit mode: " . (($this->edit_mode) ? 'enabled' : 'disabled'), 2);
}
// TODO ? move to options?
/**
* Determine if the current user is allowed to translate.
* @return boolean Is allowed to translate?
*/
function is_translator() {
//if anonymous translation is allowed - let anyone enjoy it
if ($this->options->allow_anonymous_translation) {
return TRUE;
}
if (is_user_logged_in() && current_user_can(TRANSLATOR)) {
return TRUE;
}
return FALSE;
}
/**
* Plugin activation
*/
function plugin_activate() {
tp_logger("plugin_activate enter: " . dirname(__FILE__), 1);
$this->database->setup_db();
// this handles the permalink rewrite
$GLOBALS['wp_rewrite']->flush_rules();
// attempt to remove old files
@unlink($this->transposh_plugin_dir . 'widgets/tpw_default.php');
@unlink($this->transposh_plugin_dir . 'core/globals.php');
//** FULL VERSION
// create directories in upload folder, for use with third party widgets
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$transposh_upload_dir = $upload_dir . '/' . TRANSPOSH_DIR_UPLOAD;
if (!is_dir($transposh_upload_dir)) {
mkdir($transposh_upload_dir, 0700);
}
$transposh_upload_widgets_dir = $transposh_upload_dir . '/' . TRANSPOSH_DIR_WIDGETS;
if (!is_dir($transposh_upload_widgets_dir)) {
mkdir($transposh_upload_widgets_dir, 0700);
}
//** FULLSTOP
tp_logger("plugin_activate exit: " . dirname(__FILE__), 1);
tp_logger("testing name:" . plugin_basename(__FILE__), 4);
// tp_logger("testing name2:" . $this->get_plugin_name(), 4);
//activate_plugin($plugin);
}
/**
* Plugin deactivation
*/
function plugin_deactivate() {
tp_logger("plugin_deactivate enter: " . dirname(__FILE__), 2);
// this handles the permalink rewrite
$GLOBALS['wp_rewrite']->flush_rules();
tp_logger("plugin_deactivate exit: " . dirname(__FILE__), 2);
}
/**
* Callback from admin_notices - display error message to the admin.
*/
function plugin_install_error() {
tp_logger("install error!", 1);
echo '<div class="updated"><p>';
echo 'Error has occured in the installation process of the translation plugin: <br>';
echo $this->admin_msg;
if (function_exists('deactivate_plugins')) {
// FIXME :wtf?
//deactivate_plugins(array(&$this, 'get_plugin_name'), "translate.php");
////!!! deactivate_plugins($this->transposh_plugin_basename, "translate.php");
echo '<br> This plugin has been automatically deactivated.';
}
echo '</p></div>';
}
/**
* Callback when all plugins have been loaded. Serves as the location
* to check that the plugin loaded successfully else trigger notification
* to the admin and deactivate plugin.
* TODO - needs revisiting!
*/
function plugin_loaded() {
tp_logger("Enter", 4);
//TODO: fix this...
$db_version = get_option(TRANSPOSH_DB_VERSION);
if ($db_version != DB_VERSION) {
$this->database->setup_db();
//$this->admin_msg = "Translation database version ($db_version) is not comptabile with this plugin (". DB_VERSION . ") <br>";
tp_logger("Updating database in plugin loaded", 1);
//Some error occured - notify admin and deactivate plugin
//add_action('admin_notices', 'plugin_install_error');
}
//TODO: fix this too...
$db_version = get_option(TRANSPOSH_DB_VERSION);
if ($db_version != DB_VERSION) {
$this->admin_msg = "Failed to locate the translation table <em> " . TRANSLATIONS_TABLE . "</em> in local database. <br>";
tp_logger("Messsage to admin: {$this->admin_msg}", 1);
//Some error occured - notify admin and deactivate plugin
add_action('admin_notices', array(&$this, 'plugin_install_error'));
}
}
/**
* Gets the plugin name to be used in activation/decativation hooks.
* Keep only the file name and its containing directory. Don't use the full
* path as it will break when using symbollic links.
* TODO - check!!!
* @return string
*/
/* function get_plugin_name() {
$file = __FILE__;
$file = str_replace('\\', '/', $file); // sanitize for Win32 installs
$file = preg_replace('|/+|', '/', $file); // remove any duplicate slash
//keep only the file name and its parent directory
$file = preg_replace('/.*\/([^\/]+\/[^\/]+)$/', '$1', $file);
tp_logger("Plugin path - $file", 4);
return $file;
} */
/**
* Add custom css, i.e. transposh.css
*/
function add_transposh_css() {
//translation not allowed - no need for the transposh.css
if (!$this->is_editing_permitted() && !$this->is_auto_translate_permitted())
return;
// actually - this is only needed when editing
if (!$this->edit_mode) {
return;
}
//include the transposh.css
wp_enqueue_style('transposh', $this->transposh_plugin_url . '/' . TRANSPOSH_DIR_CSS . '/transposh.css', array(), TRANSPOSH_PLUGIN_VER);
tp_logger('Added transposh_css', 4);
}
/**
* Insert references to the javascript files used in the translated version of the page.
*/
function add_transposh_js() {
//not in any translation mode - no need for any js.
if (!($this->edit_mode || $this->is_auto_translate_permitted() || is_admin() || $this->options->widget_allow_set_deflang))
// TODO: need to include if allowing of setting default language - but smaller!
return; // TODO, check just for settings page admin and pages with our translate
wp_register_script('transposh', $this->transposh_plugin_url . '/' . TRANSPOSH_DIR_JS . '/transposh.js', array('jquery'), TRANSPOSH_PLUGIN_VER, $this->options->enable_footer_scripts);
// true -> 1, false -> nothing
$script_params = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'plugin_url' => $this->transposh_plugin_url,
'lang' => $this->target_language,
'olang' => $this->options->default_language,
// those two options show if the script can support said engines
'prefix' => SPAN_PREFIX,
'preferred' => array_keys($this->options->get_sorted_engines())
);
$script_params['engines'] = new stdClass();
if (in_array($this->target_language, transposh_consts::$engines['a']['langs'])) {
$script_params['engines']->a = 1;
}
if (in_array($this->target_language, transposh_consts::$engines['b']['langs'])) {
$script_params['engines']->b = 1;
// $script_params['engines'][] = 'b';
if (isset(transposh_consts::$engines['b']['langconv'][$this->target_language])) {
$script_params['blang'] = transposh_consts::$engines['b']['langconv'][$this->target_language];
}
}
if (in_array($this->target_language, transposh_consts::$engines['g']['langs'])) {
$script_params['engines']->g = 1;
}
if (in_array($this->target_language, transposh_consts::$engines['y']['langs'])) {
$script_params['engines']->y = 1;
}
if (in_array($this->target_language, transposh_consts::$engines['u']['langs'])) {
$script_params['engines']->u = 1;
}
if ($this->options->oht_id && $this->options->oht_key && in_array($this->target_language, transposh_consts::$oht_languages) && current_user_can('manage_options')) {
$script_params['engines']->o = 1;
}
if (!$this->options->enable_autotranslate) {
$script_params['noauto'] = 1;
}
// load translations needed for edit interface
if ($this->edit_mode) {
$script_params['edit'] = 1;
if (file_exists($this->transposh_plugin_dir . TRANSPOSH_DIR_JS . '/l/' . $this->target_language . '.js')) {
$script_params['locale'] = 1;
}
}
// set theme when it is needed
if ($this->edit_mode) {
$script_params['theme'] = $this->options->widget_theme;
if ($this->options->jqueryui_override) {
$script_params['jQueryUI'] = '//ajax.googleapis.com/ajax/libs/jqueryui/' . $this->options->jqueryui_override . '/';
} else {
$script_params['jQueryUI'] = '//ajax.googleapis.com/ajax/libs/jqueryui/' . JQUERYUI_VER . '/';
}
}
// 'l10n_print_after' => 'try{convertEntities(inlineEditL10n);}catch(e){};'
wp_localize_script('transposh', 't_jp', $script_params);
// only enqueue on real pages, for real people, other admin scripts that need this will register a dependency
if (($this->edit_mode || $this->is_auto_translate_permitted() || $this->options->widget_allow_set_deflang) && !is_admin() && !transposh_utils::is_bot()) {
wp_enqueue_script('transposh');
}
tp_logger('Added transposh_js', 4);
}
/**
* Implements - http://googlewebmastercentral.blogspot.com/2010/09/unifying-content-under-multilingual.html
*/
function add_rel_alternate() {
if (is_404()) {
return;
}
$widget_args = $this->widget->create_widget_args($this->get_clean_url());
tp_logger($widget_args, 4);
foreach ($widget_args as $lang) {
if (!$lang['active']) {
echo '<link rel="alternate" hreflang="' . $lang['isocode'] . '" href="';
if (defined('FULL_VERSION')) { //** FULL VERSION
if ($this->options->full_rel_alternate) {
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . transposh_utils::get_clean_server_var('HTTP_HOST') . transposh_utils::get_clean_server_var('REQUEST_URI');
$url = transposh_utils::rewrite_url_lang_param($current_url, $this->home_url, $this->enable_permalinks_rewrite, $lang['isocode'], $this->edit_mode);
if ($this->options->is_default_language($lang['isocode'])) {
$url = transposh_utils::cleanup_url($url, $this->home_url);
}
echo $url;
} else {
echo $lang['url'];
}
} //** FULLSTOP
if (!defined('FULL_VERSION')) { //** WPORG VERSION
echo $lang['url'];
} // WPORGSTOP
echo '"/>';
}
}
}
/**
* Determine if the currently selected language (taken from the query parameters) is in the admin's list
* of editable languages and the current user is allowed to translate.
* @return boolean Is translation allowed?
*/
// TODO????
function is_editing_permitted() {
// editing is permitted for translators only
if (!$this->is_translator()) {
return false;
}
// and only on the non-default lang (unless strictly specified)
if (!$this->options->enable_default_translate && $this->options->is_default_language($this->target_language)) {
return false;
}
return $this->options->is_active_language($this->target_language);
}
/**
* Determine if the currently selected language (taken from the query parameters) is in the admin's list
* of editable languages and that automatic translation has been enabled.
* Note that any user can auto translate. i.e. ignore permissions.
* @return boolean Is automatic translation allowed?
* TODO: move to options
*/
function is_auto_translate_permitted() {
tp_logger("checking auto translatability", 4);
if (!$this->options->enable_autotranslate) {
return false;
}
// auto translate is not enabled for default target language when enable default is disabled
if (!$this->options->enable_default_translate && $this->options->is_default_language($this->target_language)) {
return false;
}
return $this->options->is_active_language($this->target_language);
}
/**