/**
* script to replace dynamically added strings with their translation.
*/
function trp_translator(){
this.is_editor = false;
var _this = this;
var observer = null;
var observerconfig = {
attributes: true,
childlist: true,
characterdata: false,//this could be cdata so i set it to false in v 1.4.5
subtree: true
};
var translate_numerals_opt = trp_data.trp_translate_numerals_opt;
var custom_ajax_url = trp_data.trp_custom_ajax_url;
var wp_ajax_url = trp_data.trp_wp_ajax_url;
var language_to_query;
this.except_characters = " \t\n\r �.,/`~!@#$€£%^&*():;-_=+[]{}\\|?/<>1234567890'";
var trim_characters = " \t\n\r �\x0a\x0b" + "\302" + "\240";
var already_detected = [];
var duplicate_detections_allowed = parseint( trp_data.duplicate_detections_allowed )
/**
* ajax request to get translations for strings
*/
this.ajax_get_translation = function( nodesinfo, string_originals, url, skip_machine_translation ) {
jquery.ajax({
url: url,
type: 'post',
datatype: 'json',
data: {
action : 'trp_get_translations_regular',
all_languages : 'false',
security : trp_data['gettranslationsnonceregular'],
language : language_to_query,
original_language : original_language, // used for trp custom ajax
originals : json.stringify( string_originals ),
skip_machine_translation : json.stringify( skip_machine_translation ),
dynamic_strings : 'true',
translate_numerals_opt : translate_numerals_opt
},
success: function( response ) {
if ( response === 'error' ) {
_this.ajax_get_translation( nodesinfo, string_originals, wp_ajax_url, skip_machine_translation );
console.log( 'notice: translatepress trp-ajax request uses fall back to admin ajax.' );
}else{
_this.update_strings( response, nodesinfo );
}
},
error: function( errorthrown ){
if ( url == custom_ajax_url && custom_ajax_url != wp_ajax_url ){
_this.ajax_get_translation( nodesinfo, string_originals, wp_ajax_url, skip_machine_translation );
console.log( 'notice: translatepress trp-ajax request uses fall back to admin ajax.' );
}else{
_this.update_strings( null, nodesinfo );
console.log( 'translatepress ajax request error' );
}
}
});
};
/**
* return given text converted to html.
*
* useful for decoding special characters into displayable form.
*
* @param html
* @returns {*}
*/
this.decode_html = function( html ) {
var txt = document.createelement( "textarea" );
txt.innerhtml = html;
return txt.value;
};
/**
* replace original strings with translations if found.
*/
this.update_strings = function( response, nodesinfo ) {
_this.pause_observer();
if ( response != null && response.length > 0 ){
var newentries = [];
for (var j = 0 ; j < nodesinfo.length; j++){
var nodeinfo = nodesinfo[j];
var translation_found = false;
var initial_value = nodeinfo.original;
for( var i = 0; i < response.length; i++ ) {
var response_string = response[i].translationsarray[language_to_query];
if (response[i].original.trim() == nodeinfo.original.trim()) {
// the nodeinfo can contain duplicates and response cannot. we need duplicates to refer to different jquery objects where the same string appears in different places on the page.
var entry = response[i]
entry.selector = 'data-trp-translate-id'
entry.attribute = ''
newentries.push( entry )
if ( _this.is_editor ) {
var jquery_object;
var trp_translate_id = 'data-trp-translate-id'
var trp_node_group = 'data-trp-node-group'
if ( nodeinfo.attribute ) {
jquery_object = jquery(nodeinfo.node)
trp_translate_id = trp_translate_id + '-' + nodeinfo.attribute
trp_node_group = trp_node_group + '-' + nodeinfo.attribute
}else{
jquery_object = jquery(nodeinfo.node).parent('translate-press');
}
jquery_object.attr( trp_translate_id, response[i].dbid );
jquery_object.attr( trp_node_group, response[i].group );
}
if (response_string.translated != '' && language_to_query == current_language ) {
var text_to_set = _this.decode_html( initial_value.replace(initial_value.trim(), response_string.translated));
if ( nodeinfo.attribute ){
nodeinfo.node.setattribute( nodeinfo.attribute, text_to_set )
if ( nodeinfo.attribute == 'src' ){
nodeinfo.node.setattribute( 'srcset', '' )
nodeinfo.node.setattribute( 'data-src', text_to_set )
}
}else {
nodeinfo.node.textcontent = text_to_set;
}
translation_found = true;
}
break;
}
}
already_detected[ initial_value ] = (initial_value in already_detected ) ? already_detected[ initial_value ] + 1 : 0
if ( ! translation_found ){
if ( nodeinfo.attribute ){
if ( nodeinfo.attribute != 'src' ) {
nodeinfo.node.setattribute(nodeinfo.attribute, initial_value)
}
}else {
nodeinfo.node.textcontent = initial_value;
}
}
}
// this should always be outside the for loop
if ( _this.is_editor ) {
window.parent.dispatchevent( new event( 'trp_iframe_page_updated' ) );
window.dispatchevent( new event( 'trp_iframe_page_updated' ) );
}
}else{
for (var j = 0 ; j < nodesinfo.length; j++){
if ( nodesinfo[j].attribute ){
if ( nodesinfo[j].attribute != 'src' ) {
nodesinfo[j].node.setattribute(nodesinfo[j].attribute, nodesinfo[j].original)
}
}else {
nodesinfo[j].node.textcontent = nodesinfo[j].original;
}
already_detected[ nodesinfo[j].original ] = (nodesinfo[j].original in already_detected ) ? already_detected[ nodesinfo[j].original ] + 1 : 0
}
}
_this.resume_observer();
};
/*
* separated from the detect_new_strings function to allow disconnecting observer.
*/
this.detect_new_strings_callback = function( mutations ){
// calling disconnect directly instead of calling pause_observer because we don't need to takerecords() (called from pause_observer) because we would duplicate mutations
observer.disconnect()
_this.detect_new_strings( mutations );
_this.resume_observer();
}
/**
* detect and remember added strings.
*/
this.detect_new_strings = function( mutations ){
var string_originals = [];
var nodesinfo = [];
var skip_machine_translation = [];
var translateable;
mutations.foreach( function (mutation) {
for (var i = 0; i < mutation.addednodes.length; i++) {
var node = mutation.addednodes[i]
/* if it is an anchor add the trp-edit-translation=preview parameter to it */
if ( _this.is_editor ){
var anchor_tags = jquery(node).find('a')
if ( typeof anchor_tags.context !== 'undefined' )
anchor_tags.context.href = _this.update_query_string('trp-edit-translation', 'preview', anchor_tags.context.href);
}
if ( _this.skip_string(node) ){
continue;
}
// search for innertext modifications or newly added nodes with innertext
translateable = _this.get_translateable_textcontent( node )
string_originals = string_originals.concat( translateable.string_originals );
nodesinfo = nodesinfo.concat( translateable.nodesinfo );
skip_machine_translation = skip_machine_translation.concat( translateable.skip_machine_translation );
// search for text inside attributes of newly added nodes
translateable = _this.get_translateable_attributes( node )
string_originals = string_originals.concat( translateable.string_originals );
nodesinfo = nodesinfo.concat( translateable.nodesinfo );
skip_machine_translation = skip_machine_translation.concat( translateable.skip_machine_translation );
}
if ( mutation.attributename ){
if ( ! _this.in_array( mutation.attributename, trp_data.trp_attributes_accessors ) ){
return
}
if ( _this.skip_string_attribute( mutation.target, mutation.attributename ) || _this.skip_string(mutation.target) ){
return
}
// search for modified text inside attributes of existing nodes
translateable = _this.get_translateable_attributes( mutation.target )
string_originals = string_originals.concat( translateable.string_originals );
nodesinfo = nodesinfo.concat( translateable.nodesinfo );
skip_machine_translation = skip_machine_translation.concat( translateable.skip_machine_translation );
}
});
if ( nodesinfo.length > 0 ) {
var ajax_url_to_call = (_this.is_editor) ? wp_ajax_url : custom_ajax_url;
_this.ajax_get_translation( nodesinfo, string_originals, ajax_url_to_call, skip_machine_translation );
}
};
this.skip_string = function(node){
// skip nodes containing these attributes
var selectors = trp_data.trp_skip_selectors;
for (var i = 0; i < selectors.length ; i++ ){
if ( jquery(node).closest( selectors[ i ] ).length > 0 ){
return true;
}
}
return false;
};
this.skip_string_from_auto_translation = function(node){
// nodes containing these attributes will not be automatically translated
var selectors = trp_data.trp_no_auto_translation_selectors;
for (var i = 0; i < selectors.length ; i++ ){
if ( jquery(node).closest( selectors[ i ] ).length > 0 ){
return true;
}
}
return false;
};
this.contains_substring_that_needs_skipped = function ( string, attribute ){
for (var attribute_to_skip in trp_data.skip_strings_from_dynamic_translation_for_substrings ){
if (trp_data.skip_strings_from_dynamic_translation_for_substrings.hasownproperty(attribute_to_skip) && attribute === attribute_to_skip) {
for ( var i = 0 ; i < trp_data.skip_strings_from_dynamic_translation_for_substrings[attribute_to_skip].length; i++ ){
if ( string.indexof(trp_data.skip_strings_from_dynamic_translation_for_substrings[attribute_to_skip][i]) !== -1 ){
return true
}
}
}
}
return false
};
/*
* skip string based on original string text
*/
this.skip_string_original = function ( string, attribute ){
return (
( already_detected[string] > duplicate_detections_allowed ) ||
_this.in_array( string, trp_data.skip_strings_from_dynamic_translation ) ||
_this.contains_substring_that_needs_skipped( string, attribute)
)
}
this.skip_string_attribute = function(node, attribute){
// skip nodes containing these attributes
var selectors = trp_data.trp_base_selectors;
for (var i = 0; i < selectors.length ; i++ ){
if ( typeof jquery(node).attr( selectors[ i ] + '-' + attribute ) !== 'undefined' ){
return true;
}
}
return false;
};
this.in_array = function (needle, array ) {
var i
var length = array.length
for( i = length - 1; i >= 0; i-- ){
if ( array[i] === needle ){
return true
}
}
return false
}
this.get_translateable_textcontent = function( node ){
var string_originals = [];
var nodesinfo = [];
var skip_machine_translation = []
if ( node.textcontent && _this.trim( node.textcontent.trim(), _this.except_characters ) != '' ) {
var direct_string = get_string_from_node( node );
if ( direct_string ) {
// a text without html was added
if ( _this.trim( direct_string.textcontent, _this.except_characters ) != '' ) {
var extracted_original = _this.trim(direct_string.textcontent, trim_characters);
if ( ! _this.skip_string_original( extracted_original, false )) {
nodesinfo.push({node: node, original: extracted_original, attribute: ''});
string_originals.push(extracted_original)
if ( _this.skip_string_from_auto_translation(node)){
skip_machine_translation.push( extracted_original )
}
direct_string.textcontent = '';
if (_this.is_editor) {
jquery(node).wrap('');
}
}
}
}else{
// node contains html
var all_nodes = jquery( node ).find( '*').addback();
var all_strings = all_nodes.contents().filter(function(){
if( this.nodetype === 3 && /\s/.test(this.nodevalue) ){
if ( ! _this.skip_string(this) ){
return this;
}
}});
if ( _this.is_editor ) {
all_strings.wrap('');
}
var all_strings_length = all_strings.length;
for (var j = 0; j < all_strings_length; j++ ) {
if ( _this.trim( all_strings[j].textcontent, _this.except_characters ) != '' ) {
if ( ! _this.skip_string_original( all_strings[j].textcontent, false )) {
nodesinfo.push({node: all_strings[j], original: all_strings[j].textcontent, attribute: ''});
string_originals.push(all_strings[j].textcontent)
if ( _this.skip_string_from_auto_translation(all_strings[j])){
skip_machine_translation.push( all_strings[j].textcontent )
}
if (trp_data ['showdynamiccontentbeforetranslation'] == false) {
all_strings[j].textcontent = '';
}
}
}
}
}
}
return { 'string_originals': string_originals, 'nodesinfo': nodesinfo, 'skip_machine_translation': skip_machine_translation };
}
this.get_translateable_attributes = function ( node ) {
var nodesinfo = []
var string_originals = []
var skip_attr_machine_translation = [ 'href', 'src' ]
var skip_machine_translation = []
for (var trp_attribute_key in trp_data.trp_attributes_selectors) {
if (trp_data.trp_attributes_selectors.hasownproperty(trp_attribute_key)) {
var attribute_selector_item = trp_data.trp_attributes_selectors[trp_attribute_key]
if ( typeof attribute_selector_item['selector'] !== 'undefined' ){
var all_nodes = jquery( node ).find( attribute_selector_item.selector ).addback( attribute_selector_item.selector )
var all_nodes_length = all_nodes.length
for (var j = 0; j < all_nodes_length; j++ ) {
if ( _this.skip_string( all_nodes[j] ) || _this.skip_string_attribute( all_nodes[j], attribute_selector_item.accessor ) ){
continue;
}
var attribute_content = all_nodes[j].getattribute( attribute_selector_item.accessor )
if ( _this.skip_string_original( attribute_content, attribute_selector_item.accessor )){
continue;
}
if ( attribute_content && _this.trim( attribute_content.trim(), _this.except_characters ) != '' ) {
nodesinfo.push({node: all_nodes[j], original: attribute_content, attribute: attribute_selector_item.accessor });
string_originals.push( attribute_content )
if ( trp_data ['showdynamiccontentbeforetranslation'] == false && ( attribute_selector_item.accessor != 'src' ) && ( attribute_selector_item.accessor != 'href' ) ) {
all_nodes[j].setattribute( attribute_selector_item.accessor, '' );
}
if ( _this.skip_string_from_auto_translation(all_nodes[j])){
skip_machine_translation.push( attribute_content )
}else{
for ( var s = 0; s < skip_attr_machine_translation.length; s++ ) {
if ( attribute_selector_item.accessor === skip_attr_machine_translation[ s ] ){
skip_machine_translation.push( attribute_content )
break
}
}
}
}
}
}
}
}
return { 'string_originals': string_originals, 'nodesinfo': nodesinfo, 'skip_machine_translation': skip_machine_translation };
}
function get_string_from_node( node ){
if( node.nodetype === 3 && /\s/.test(node.nodevalue) ){
if ( ! _this.skip_string(node) ){
return node;
}
}
}
// cleans the gettext wrappers
this.cleanup_gettext_wrapper = function(){
jquery('trp-gettext').contents().unwrap();
};
/**
* update url with query string.
*
*/
this.update_query_string = function(key, value, url) {
if (!url) return url;
if ( url.startswith('#') ){
return url;
}
var re = new regexp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
hash;
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null)
return url.replace(re, '$1' + key + "=" + value + '$2$3');
else {
hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
}
else {
if (typeof value !== 'undefined' && value !== null ) {
var separator = url.indexof('?') !== -1 ? '&' : '?';
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
else
return url;
}
};
/**
* initialize and configure observer.
*/
this.initialize = function() {
this.is_editor = (typeof window.parent.tpeditorapp !== 'undefined' )
if ( this.is_editor ) {
trp_data['gettranslationsnonceregular'] = window.parent.trp_dynamic_nonce;
}
current_language = trp_data.trp_current_language;
original_language = trp_data.trp_original_language;
language_to_query = trp_data.trp_language_to_query;
translate_numerals_opt = trp_data.trp_translate_numerals_opt;
if ( typeof translate_numerals_opt !== "undefined" && translate_numerals_opt !== '' && translate_numerals_opt === "yes") {
_this.except_characters = " \t\n\r �.,/`~!@#$€£%^&*():;-_=+[]{}\\|?/<>'";
}
// create an observer instance
observer = new mutationobserver( _this.detect_new_strings_callback );
_this.resume_observer();
jquery( document ).ajaxcomplete(function( event, request, settings ) {
if( typeof window.parent.jquery !== "undefined" && window.parent.jquery('#trp-preview-iframe').length != 0 ) {
var settingsdata = "" + settings.data;
if( typeof settings.data == 'undefined' || jquery.isemptyobject( settings.data ) || settingsdata.indexof('action=trp_') === -1 ) {
window.parent.dispatchevent( new event( 'trp_iframe_page_updated' ) );
}
}
});
//try a final attempt at cleaning the gettext wrappers
_this.cleanup_gettext_wrapper();
};
/**
* resume observing new strings added.
*/
this.resume_observer = function(){
if ( language_to_query === '' ) {
// no translation languages are set other than default language
return;
}
observer.observe(document.body, observerconfig);
};
/**
* pause observing new strings added.
*/
this.pause_observer = function(){
/*
disconnect will delete the existing mutations detected prior to being passed to callback function.
so we are calling takerecords to save them first, disconnect, then detect the strings
disconnect happens before detect_new_strings to avoid detecting mutations from within detect new strings functions
*/
if ( language_to_query === '' ) {
// no translation languages are set other than default language
return;
}
var mutations = observer.takerecords()
observer.disconnect()
if ( mutations.length > 0 ) {
_this.detect_new_strings(mutations)
}
};
this.trim = function (str, charlist) {
// discuss at: http://locutus.io/php/trim/
// original by: kevin van zonneveld (http://kvz.io)
// improved by: mdsjack (http://www.mdsjack.bo.it)
// improved by: alexander ermolaev (http://snippets.dzone.com/user/alexanderermolaev)
// improved by: kevin van zonneveld (http://kvz.io)
// improved by: steven levithan (http://blog.stevenlevithan.com)
// improved by: jack
// input by: erkekjetter
// input by: dxgx
// bugfixed by: onno marsman (https://twitter.com/onnomarsman)
// example 1: trim(' kevin van zonneveld ')
// returns 1: 'kevin van zonneveld'
// example 2: trim('hello world', 'hdle')
// returns 2: 'o wor'
// example 3: trim(16, 1)
// returns 3: '6'
var whitespace = [
' ',
'\n',
'\r',
'\t',
'\f',
'\x0b',
'\xa0',
'\u2000',
'\u2001',
'\u2002',
'\u2003',
'\u2004',
'\u2005',
'\u2006',
'\u2007',
'\u2008',
'\u2009',
'\u200a',
'\u200b',
'\u2028',
'\u2029',
'\u3000'
].join('');
var l = 0;
var i = 0;
str += '';
if (charlist) {
whitespace += (charlist + '').replace(/([[\]().?/*{}+$^:])/g, '$1');
}
l = str.length;
for (i = 0; i < l; i++) {
if (whitespace.indexof(str.charat(i)) === -1) {
str = str.substring(i);
break;
}
}
l = str.length;
for (i = l - 1; i >= 0; i--) {
if (whitespace.indexof(str.charat(i)) === -1) {
str = str.substring(0, i + 1);
break;
}
}
return whitespace.indexof(str.charat(0)) === -1 ? str : '';
};
_this.initialize();
}
var trptranslator;
var current_language;
var original_language;
function trp_get_ie_version() {
var sagent = window.navigator.useragent;
var idx = sagent.indexof("msie");
// if ie, return version number.
if (idx > 0)
return parseint(sagent.substring(idx+ 5, sagent.indexof(".", idx)));
// if ie 11 then look for updated user agent string.
else if (!!navigator.useragent.match(/trident\/7\./))
return 11;
else
return 0; //it is not ie
}
function trp_allow_detect_dom_changes_to_run(){
var ie_version = trp_get_ie_version();
if ( ie_version != 0 && ie_version <= 11 ){
return false;
}
return true;
}
// initialize the translate press editor when the script loads
if ( trp_allow_detect_dom_changes_to_run() ) {
trptranslator = new trp_translator();
}