Skip to content

Instantly share code, notes, and snippets.

@warenhaus
Last active May 25, 2017 20:21
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save warenhaus/10990386 to your computer and use it in GitHub Desktop.
Save warenhaus/10990386 to your computer and use it in GitHub Desktop.
qtranslate with the new Visual editor in Wordpress 3.9
<?php // encoding: utf-8
/*Copyright 2008Qian Qin(email : mail@qianqin.de)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA02110-1301USA
*/
/* qTranslate Hooks */
function qtrans_header(){
global $q_config;
echo "\n<meta http-equiv=\"Content-Language\" content=\"".str_replace('_','-',$q_config['locale'][$q_config['language']])."\" />\n";
$css = "<style type=\"text/css\" media=\"screen\">\n";
$css .=".qtrans_flag span { display:none }\n";
$css .=".qtrans_flag { height:12px; width:18px; display:block }\n";
$css .=".qtrans_flag_and_text { padding-left:20px }\n";
$baseurl = WP_CONTENT_URL;
if(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == '1' || $_SERVER['HTTPS'] == 'on')) {
$baseurl = preg_replace('#^http://#','https://', $baseurl);
}
foreach($q_config['enabled_languages'] as $language) {
$css .=".qtrans_flag_".$language." { background:url(".$baseurl.'/'.$q_config['flag_location'].$q_config['flag'][$language].") no-repeat }\n";
}
$css .="</style>\n";
echo apply_filters('qtranslate_header_css',$css);
// skip the rest if 404
if(is_404()) return;
// set links to translations of current page
foreach($q_config['enabled_languages'] as $language) {
if($language != qtrans_getLanguage())
echo '<link hreflang="'.$language.'" href="'.qtrans_convertURL('',$language).'" rel="alternate" />'."\n";
}
}
function qtrans_localeForCurrentLanguage($locale){
global $q_config;
// try to figure out the correct locale
$locale = array();
$locale[] = $q_config['locale'][$q_config['language']].".utf8";
$locale[] = $q_config['locale'][$q_config['language']]."@euro";
$locale[] = $q_config['locale'][$q_config['language']];
$locale[] = $q_config['windows_locale'][$q_config['language']];
$locale[] = $q_config['language'];
// return the correct locale and most importantly set it (wordpress doesn't, which is bad)
// only set LC_TIME as everyhing else doesn't seem to work with windows
setlocale(LC_TIME, $locale);
return $q_config['locale'][$q_config['language']];
}
function qtrans_optionFilter($do='enable') {
$options = array( 'option_widget_pages',
'option_widget_archives',
'option_widget_meta',
'option_widget_calendar',
'option_widget_text',
'option_widget_categories',
'option_widget_recent_entries',
'option_widget_recent_comments',
'option_widget_rss',
'option_widget_tag_cloud'
);
foreach($options as $option) {
if($do!='disable') {
add_filter($option, 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
} else {
remove_filter($option, 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage');
}
}
}
function qtrans_adminHeader() {
echo "<style type=\"text/css\" media=\"screen\">\n";
echo ".qtrans_title_input { border:0pt none; font-size:1.7em; outline-color:invert; outline-style:none; outline-width:medium; padding:0pt; width:100%; }\n";
echo ".qtrans_title_wrap { border-color:#CCCCCC; border-style:solid; border-width:1px; padding:2px 3px; }\n";
echo "#qtrans_textarea_content { padding:6px; border:0 none; line-height:150%; outline: none; margin:0pt; width:100%; -moz-box-sizing: border-box;";
echo "-webkit-box-sizing: border-box; -khtml-box-sizing: border-box; box-sizing: border-box; }\n";
echo ".qtrans_title { -moz-border-radius: 6px 6px 0 0;";
echo "-webkit-border-top-right-radius: 6px; -webkit-border-top-left-radius: 6px; -khtml-border-top-right-radius: 6px; -khtml-border-top-left-radius: 6px;";
echo "border-top-right-radius: 6px; border-top-left-radius: 6px; }\n";
echo ".hide-if-no-js.wp-switch-editor.switch-tmce { margin-left:6px !important;}";
echo "#qtranslate_debug { width:100%; height:200px }";
echo "#postexcerpt textarea { height:4em; margin:0; width:98% }";
echo ".qtranslate_lang_div { float:right; height:12px; width:18px; padding:6px 5px 8px 5px; cursor:pointer }";
echo ".qtranslate_lang_div.active { background: #DFDFDF; border-left:1px solid #D0D0D0; border-right: 1px solid #F7F7F7; padding:6px 4px 8px 4px }";
do_action('qtranslate_css');
echo "</style>\n";
return qtrans_optionFilter('disable');
}
function qtrans_useCurrentLanguageIfNotFoundShowAvailable($content) {
global $q_config;
return qtrans_use($q_config['language'], $content, true);
}
function qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($content) {
global $q_config;
return qtrans_use($q_config['language'], $content, false);
}
function qtrans_useDefaultLanguage($content) {
global $q_config;
return qtrans_use($q_config['default_language'], $content, false);
}
function qtrans_excludeUntranslatedPosts($where) {
global $q_config, $wpdb;
if($q_config['hide_untranslated'] && !is_singular()) {
$where .= " AND $wpdb->posts.post_content LIKE '%<!--:".qtrans_getLanguage()."-->%'";
}
return $where;
}
function qtrans_excludePages($pages) {
global $wpdb, $q_config;
static $exclude = 0;
if(!$q_config['hide_untranslated']) return $pages;
if(is_array($exclude)) return array_merge($exclude, $pages);
$query = "SELECT id FROM $wpdb->posts WHERE post_type = 'page' AND post_status = 'publish' AND NOT ($wpdb->posts.post_content LIKE '%<!--:".qtrans_getLanguage()."-->%')" ;
$hide_pages = $wpdb->get_results($query);
$exclude = array();
foreach($hide_pages as $page) {
$exclude[] = $page->id;
}
return array_merge($exclude, $pages);
}
function qtrans_postsFilter($posts) {
if(is_array($posts)) {
foreach($posts as $post) {
$post->post_content = qtrans_useCurrentLanguageIfNotFoundShowAvailable($post->post_content);
$post = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($post);
}
}
return $posts;
}
function qtrans_links($links, $file){ // copied from Sociable Plugin
//Static so we don't call plugin_basename on every plugin row.
static $this_plugin;
if (!$this_plugin) $this_plugin = plugin_basename(dirname(__FILE__).'/qtranslate.php');
if ($file == $this_plugin){
$settings_link = '<a href="options-general.php?page=qtranslate">' . __('Settings', 'qtranslate') . '</a>';
array_unshift( $links, $settings_link ); // before other links
}
return $links;
}
function qtrans_languageColumnHeader($columns){
$new_columns = array();
if(isset($columns['cb'])) $new_columns['cb'] = '';
if(isset($columns['title'])) $new_columns['title'] = '';
if(isset($columns['author'])) $new_columns['author'] = '';
if(isset($columns['categories'])) $new_columns['categories'] = '';
if(isset($columns['tags'])) $new_columns['tags'] = '';
$new_columns['language'] = __('Languages', 'qtranslate');
return array_merge($new_columns, $columns);;
}
function qtrans_languageColumn($column) {
global $q_config, $post;
if ($column == 'language') {
$available_languages = qtrans_getAvailableLanguages($post->post_content);
$missing_languages = array_diff($q_config['enabled_languages'], $available_languages);
$available_languages_name = array();
$missing_languages_name = array();
foreach($available_languages as $language) {
$available_languages_name[] = $q_config['language_name'][$language];
}
$available_languages_names = join(", ", $available_languages_name);
echo apply_filters('qtranslate_available_languages_names',$available_languages_names);
do_action('qtranslate_languageColumn', $available_languages, $missing_languages);
}
return $column;
}
function qtrans_versionLocale() {
return 'en_US';
}
function qtrans_esc_html($text) {
return qtrans_useDefaultLanguage($text);
}
function qtrans_useRawTitle($title, $raw_title = '', $context = 'save') {
if($raw_title=='') $raw_title = $title;
if('save'==$context) {
$raw_title = qtrans_useDefaultLanguage($raw_title);
$title = remove_accents($raw_title);
}
return $title;
}
function qtrans_checkCanonical($redirect_url, $requested_url) {
// fix canonical conflicts with language urls
if(qtrans_convertURL($redirect_url)==qtrans_convertURL($requested_url))
return false;
return $redirect_url;
}
function qtrans_fixSearchForm($form) {
$form = preg_replace('#action="[^"]*"#','action="'.trailingslashit(qtrans_convertURL(get_home_url())).'"',$form);
return $form;
}
function qtrans_fixAdminBar($wp_admin_bar) {
global $wp_admin_bar;
foreach($wp_admin_bar->get_nodes() as $node) {
$wp_admin_bar->add_node(qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($node));
}
}
// Hooks for Plugin compatibility
function wpsupercache_supercache_dir($uri) {
global $q_config;
if(isset($q_config['url_info']['original_url'])) {
$uri = $q_config['url_info']['original_url'];
} else {
$uri = $_SERVER['REQUEST_URI'];
}
$uri = preg_replace('/[ <>\'\"\r\n\t\(\)]/', '', str_replace( '/index.php', '/', str_replace( '..', '', preg_replace("/(\?.*)?$/", '', $uri ) ) ) );
$uri = str_replace( '\\', '', $uri );
$uri = strtolower(preg_replace('/:.*$/', '', $_SERVER["HTTP_HOST"])) . $uri; // To avoid XSS attacs
return $uri;
}
add_filter('supercache_dir', 'wpsupercache_supercache_dir',0);
// Hooks (Actions)
add_action('wp_head', 'qtrans_header');
add_action('category_edit_form', 'qtrans_modifyTermFormFor');
add_action('post_tag_edit_form', 'qtrans_modifyTermFormFor');
add_action('link_category_edit_form', 'qtrans_modifyTermFormFor');
add_action('category_add_form', 'qtrans_modifyTermFormFor');
add_action('post_tag_add_form', 'qtrans_modifyTermFormFor');
add_action('link_category_add_form', 'qtrans_modifyTermFormFor');
add_action('widgets_init', 'qtrans_widget_init');
add_action('plugins_loaded', 'qtrans_init', 2);
add_action('admin_head', 'qtrans_adminHeader');
add_action('admin_menu', 'qtrans_adminMenu');
add_action('wp_before_admin_bar_render', 'qtrans_fixAdminBar');
add_action('wp_tiny_mce_init', 'qtrans_TinyMCE_init');
// Hooks (execution time critical filters)
add_filter('the_content', 'qtrans_useCurrentLanguageIfNotFoundShowAvailable', 0);
add_filter('the_excerpt', 'qtrans_useCurrentLanguageIfNotFoundShowAvailable', 0);
add_filter('the_excerpt_rss', 'qtrans_useCurrentLanguageIfNotFoundShowAvailable', 0);
add_filter('sanitize_title', 'qtrans_useRawTitle',0, 3);
add_filter('comment_moderation_subject', 'qtrans_useDefaultLanguage',0);
add_filter('comment_moderation_text', 'qtrans_useDefaultLanguage',0);
add_filter('get_comment_date', 'qtrans_dateFromCommentForCurrentLanguage',0,2);
add_filter('get_comment_time', 'qtrans_timeFromCommentForCurrentLanguage',0,4);
add_filter('get_post_modified_time', 'qtrans_timeModifiedFromPostForCurrentLanguage',0,3);
add_filter('get_the_time', 'qtrans_timeFromPostForCurrentLanguage',0,3);
add_filter('get_the_date', 'qtrans_dateFromPostForCurrentLanguage',0,4);
add_filter('locale', 'qtrans_localeForCurrentLanguage',99);
add_filter('the_title', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage', 0);
add_filter('term_name', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('tag_rows', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('list_cats', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('wp_list_categories', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('wp_dropdown_cats', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('wp_title', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('single_post_title', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('bloginfo', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('get_others_drafts', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('get_bloginfo_rss', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('get_wp_title_rss', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('wp_title_rss', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('the_title_rss', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('the_content_rss', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('gettext', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('get_pages', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('category_description', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('bloginfo_rss', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('the_category_rss', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('wp_generate_tag_cloud', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('term_links-post_tag', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('link_name', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('link_description', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('pre_option_rss_language', 'qtrans_getLanguage',0);
add_filter('the_author', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter( "_wp_post_revision_field_post_title", 'qtrans_showAllSeperated', 0);
add_filter( "_wp_post_revision_field_post_content", 'qtrans_showAllSeperated', 0);
add_filter( "_wp_post_revision_field_post_excerpt", 'qtrans_showAllSeperated', 0);
// Hooks (execution time non-critical filters)
add_filter('author_feed_link', 'qtrans_convertURL');
add_filter('author_link', 'qtrans_convertURL');
add_filter('author_feed_link', 'qtrans_convertURL');
add_filter('day_link', 'qtrans_convertURL');
add_filter('get_comment_author_url_link', 'qtrans_convertURL');
add_filter('month_link', 'qtrans_convertURL');
add_filter('page_link', 'qtrans_convertURL');
add_filter('post_link', 'qtrans_convertURL');
add_filter('year_link', 'qtrans_convertURL');
add_filter('category_feed_link', 'qtrans_convertURL');
add_filter('category_link', 'qtrans_convertURL');
add_filter('tag_link', 'qtrans_convertURL');
add_filter('term_link', 'qtrans_convertURL');
add_filter('the_permalink', 'qtrans_convertURL');
add_filter('feed_link', 'qtrans_convertURL');
add_filter('post_comments_feed_link', 'qtrans_convertURL');
add_filter('tag_feed_link', 'qtrans_convertURL');
add_filter('get_pagenum_link', 'qtrans_convertURL');
add_filter('get_search_form', 'qtrans_fixSearchForm', 10, 1);
add_filter('manage_posts_columns', 'qtrans_languageColumnHeader');
add_filter('manage_posts_custom_column', 'qtrans_languageColumn');
add_filter('manage_pages_columns', 'qtrans_languageColumnHeader');
add_filter('manage_pages_custom_column', 'qtrans_languageColumn');
add_filter('wp_list_pages_excludes', 'qtrans_excludePages');
add_filter('comment_notification_text', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage');
add_filter('comment_notification_headers', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage');
add_filter('comment_notification_subject', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage');
add_filter('the_editor', 'qtrans_modifyRichEditor');
add_filter('admin_footer', 'qtrans_modifyExcerpt');
add_filter('bloginfo_url', 'qtrans_convertBlogInfoURL',10,2);
add_filter('plugin_action_links', 'qtrans_links', 10, 2);
add_filter('manage_language_columns', 'qtrans_language_columns');
add_filter('core_version_check_locale', 'qtrans_versionLocale');
add_filter('redirect_canonical', 'qtrans_checkCanonical', 10, 2);
// skip this filters if on backend
if(!defined('WP_ADMIN')) {
add_filter('the_posts', 'qtrans_postsFilter');
add_filter('wp_setup_nav_menu_item', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage');
// Compability with Default Widgets
qtrans_optionFilter();
add_filter('widget_title', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('widget_text', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
// filter options
add_filter('esc_html', 'qtrans_esc_html', 0);
// don't filter untranslated posts in admin
add_filter('posts_where_request', 'qtrans_excludeUntranslatedPosts');
// leave terms in default language
add_filter('cat_row', 'qtrans_useTermLib',0);
add_filter('cat_rows', 'qtrans_useTermLib',0);
add_filter('wp_get_object_terms', 'qtrans_useTermLib',0);
add_filter('single_tag_title', 'qtrans_useTermLib',0);
add_filter('single_cat_title', 'qtrans_useTermLib',0);
add_filter('the_category', 'qtrans_useTermLib',0);
add_filter('get_term', 'qtrans_useTermLib',0);
add_filter('get_terms', 'qtrans_useTermLib',0);
add_filter('get_category', 'qtrans_useTermLib',0);
add_filter('get_comment_author', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
add_filter('the_author', 'qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage',0);
}
?>
<?php // encoding: utf-8
/* Copyright 2008 Qian Qin (email : mail@qianqin.de)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
// qTranslate Javascript functions
function qtrans_initJS() {
global $q_config;
$q_config['js']['qtrans_xsplit'] = "
String.prototype.xsplit = function(_regEx){
// Most browsers can do this properly, so let them — they'll do it faster
if ('a~b'.split(/(~)/).length === 3) { return this.split(_regEx); }
if (!_regEx.global)
{ _regEx = new RegExp(_regEx.source, 'g' + (_regEx.ignoreCase ? 'i' : '')); }
// IE (and any other browser that can't capture the delimiter)
// will, unfortunately, have to be slowed down
var start = 0, arr=[];
var result;
while((result = _regEx.exec(this)) != null){
arr.push(this.slice(start, result.index));
if(result.length > 1) arr.push(result[1]);
start = _regEx.lastIndex;
}
if(start < this.length) arr.push(this.slice(start));
if(start == this.length) arr.push(''); //delim at the end
return arr;
};
";
$q_config['js']['qtrans_is_array'] = "
qtrans_isArray = function(obj) {
if (obj.constructor.toString().indexOf('Array') == -1)
return false;
else
return true;
}
";
$q_config['js']['qtrans_split'] = "
qtrans_split = function(text) {
var split_regex = /(<!--.*?-->)/gi;
var lang_begin_regex = /<!--:([a-z]{2})-->/gi;
var lang_end_regex = /<!--:-->/gi;
var morenextpage_regex = /(<!--more-->|<!--nextpage-->)+$/gi;
var matches = null;
var result = new Object;
var matched = false;
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_split'].= "
result['".$language."'] = '';
";
$q_config['js']['qtrans_split'].= "
var blocks = text.xsplit(split_regex);
if(qtrans_isArray(blocks)) {
for (var i = 0;i<blocks.length;i++) {
if((matches = lang_begin_regex.exec(blocks[i])) != null) {
matched = matches[1];
} else if(lang_end_regex.test(blocks[i])) {
matched = false;
} else {
if(matched) {
result[matched] += blocks[i];
} else {
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_split'].= "
result['".$language."'] += blocks[i];
";
$q_config['js']['qtrans_split'].= "
}
}
}
}
for (var i = 0;i<result.length;i++) {
result[i] = result[i].replace(morenextpage_regex,'');
}
return result;
}
";
$q_config['js']['qtrans_use'] = "
qtrans_use = function(lang, text) {
var result = qtrans_split(text);
return result[lang];
}
";
$q_config['js']['qtrans_integrate'] = "
qtrans_integrate = function(lang, lang_text, text) {
var texts = qtrans_split(text);
var moreregex = /<!--more-->/i;
var text = '';
var max = 0;
var morenextpage_regex = /(<!--more-->|<!--nextpage-->)+$/gi;
texts[lang] = lang_text;
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_integrate'].= "
texts['".$language."'] = texts['".$language."'].split(moreregex);
if(!qtrans_isArray(texts['".$language."'])) {
texts['".$language."'] = [texts['".$language."']];
}
if(max < texts['".$language."'].length) max = texts['".$language."'].length;
";
$q_config['js']['qtrans_integrate'].= "
for(var i=0; i<max; i++) {
if(i >= 1) {
text += '<!--more-->';
}
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_integrate'].= "
if(texts['".$language."'][i] && texts['".$language."'][i]!=''){
text += '<!--:".$language."-->';
text += texts['".$language."'][i];
text += '<!--:-->';
}
";
$q_config['js']['qtrans_integrate'].= "
}
text = text.replace(morenextpage_regex,'');
return text;
}
";
$q_config['js']['qtrans_save'] = "
qtrans_save = function(text) {
var ta = document.getElementById('content');
ta.value = qtrans_integrate(qtrans_get_active_language(),text,ta.value);
return ta.value;
}
";
$q_config['js']['qtrans_integrate_category'] = "
qtrans_integrate_category = function() {
var t = document.getElementById('cat_name');
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_integrate_category'].= "
if(document.getElementById('qtrans_category_".$language."').value!='')
t.value = qtrans_integrate('".$language."',document.getElementById('qtrans_category_".$language."').value,t.value);
";
$q_config['js']['qtrans_integrate_category'].= "
}
";
$q_config['js']['qtrans_integrate_tag'] = "
qtrans_integrate_tag = function() {
var t = document.getElementById('name');
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_integrate_tag'].= "
if(document.getElementById('qtrans_tag_".$language."').value!='')
t.value = qtrans_integrate('".$language."',document.getElementById('qtrans_tag_".$language."').value,t.value);
";
$q_config['js']['qtrans_integrate_tag'].= "
}
";
$q_config['js']['qtrans_integrate_link_category'] = "
qtrans_integrate_link_category = function() {
var t = document.getElementById('name');
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_integrate_link_category'].= "
if(document.getElementById('qtrans_link_category_".$language."').value!='')
t.value = qtrans_integrate('".$language."',document.getElementById('qtrans_link_category_".$language."').value,t.value);
";
$q_config['js']['qtrans_integrate_link_category'].= "
}
";
$q_config['js']['qtrans_integrate_title'] = "
qtrans_integrate_title = function() {
var t = document.getElementById('title');
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_integrate_title'].= "
t.value = qtrans_integrate('".$language."',document.getElementById('qtrans_title_".$language."').value,t.value);
";
$q_config['js']['qtrans_integrate_title'].= "
}
";
$q_config['js']['qtrans_assign'] = "
qtrans_assign = function(id, text) {
var inst = tinyMCE.get(id);
var ta = document.getElementById(id);
if(inst && ! inst.isHidden()) {
text = switchEditors.wpautop(text);
inst.execCommand('mceSetContent', null, text);
} else {
ta.value = text;
}
}
";
$q_config['js']['qtrans_tinyMCEOverload'] = "
tinyMCE.get2 = tinyMCE.get;
tinyMCE.get = function(id) {
if(id=='content'&&this.get2('qtrans_textarea_'+id)!=undefined)
return this.get2('qtrans_textarea_'+id);
return this.get2(id);
}
";
$q_config['js']['qtrans_wpActiveEditorOverload'] = "
jQuery('.wp-editor-wrap').unbind('mousedown');
jQuery('.wp-editor-wrap').mousedown(function(e){
wpActiveEditor = 'qtrans_textarea_'+this.id.slice(3, -5);
});
";
$q_config['js']['qtrans_updateTinyMCE'] = "
(function() {
for (var i in tinyMCEPreInit.qtInit) {
var tmp = tinyMCEPreInit.qtInit[i];
tmp.id = 'qtrans_textarea_'+tmp.id;
tinyMCEPreInit.qtInit[tmp.id] = tmp;
delete tinyMCEPreInit.qtInit[i];
jQuery('#ed_toolbar').hide();
}
var hook = tinyMCEPreInit.mceInit['content'];
hook.elements='hook-to-nothing';
hook.selector = '#qtrans_textarea_content';
delete tinyMCEPreInit.mceInit['content'];
tinyMCEPreInit.mceInit['qtrans_textarea_content'] = hook;
var wrap = jQuery('#wp-content-wrap');
var html = '<div id=\"wp-qtrans_textarea_content-wrap\" class=\"' + wrap.prop('className') + '\"></div>';
jQuery('body').append(html);
}());
";
$q_config['js']['qtrans_wpOnload'] = "
jQuery(document).ready(function() {
qtrans_editorInit();
});
";
$q_config['js']['qtrans_editorInit'] = "
qtrans_editorInit = function() {
qtrans_editorInit1();
qtrans_editorInit2();
jQuery('#qtrans_imsg').hide();
qtrans_editorInit3();
var h = getUserSetting( 'ed_size' );
if(h<300) h = 300;
jQuery('#content').hide();
if ( getUserSetting( 'editor' ) == 'html' ) {
if ( h )
jQuery('#qtrans_textarea_content').css('height', h - 20 + 'px');
jQuery('#qtrans_textarea_content').show();
} else {
// Activate TinyMCE if it's the user's default editor
jQuery('#qtrans_textarea_content').show();
// correct p for tinymce
jQuery('#qtrans_textarea_content').val(switchEditors.wpautop(jQuery('#qtrans_textarea_content').val()))
// let wp3.5 autohook take care of init
qtrans_hook_on_tinyMCE('qtrans_textarea_content', false);
}
}
";
$q_config['js']['qtrans_hook_on_tinyMCE'] = "
qtrans_hook_on_tinyMCE = function(id, initEditor) {
tinyMCEPreInit.mceInit[id].setup = function(ed) {
ed.on('SaveContent', function(e) {
if (!ed.isHidden())
qtrans_save(switchEditors.pre_wpautop(e.content));
});
};
if (initEditor)
tinymce.init(tinyMCEPreInit.mceInit[id]);
}
";
$q_config['js']['qtrans_get_active_language'] = "
qtrans_get_active_language = function() {
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_get_active_language'].= "
if(document.getElementById('qtrans_select_".$language."').className=='wp-switch-editor switch-tmce switch-html')
return '".$language."';
";
$q_config['js']['qtrans_get_active_language'].= "
}
";
$q_config['js']['qtrans_switch_postbox'] = "
function qtrans_switch_postbox(parent, target, lang, focus) {
if(typeof(focus)==='undefined') focus = true;
";
foreach($q_config['enabled_languages'] as $language)
$q_config['js']['qtrans_switch_postbox'].= "
jQuery('#'+target).val(qtrans_integrate('".$language."', jQuery('#qtrans_textarea_'+target+'_'+'".$language."').val(), jQuery('#'+target).val()));
jQuery('#'+parent+' .qtranslate_lang_div').removeClass('switch-html');
jQuery('#'+parent+' .qtranslate_lang_div').removeClass('switch-tmce');
if(lang!=false) jQuery('#qtrans_textarea_'+target+'_'+'".$language."').hide();
";
$q_config['js']['qtrans_switch_postbox'].= "
if(lang!=false) {
jQuery('#qtrans_switcher_'+parent+'_'+lang).addClass('switch-tmce');
jQuery('#qtrans_switcher_'+parent+'_'+lang).addClass('switch-html');
jQuery('#qtrans_textarea_'+target+'_'+lang).show();
if(focus)
jQuery('#qtrans_textarea_'+target+'_'+lang).focus();
}
}
";
$q_config['js']['qtrans_switch'] = "
switchEditors.go = function(id, lang) {
id = id || 'qtrans_textarea_content';
lang = lang || 'toggle';
if ( 'toggle' == lang ) {
if ( ed && !ed.isHidden() )
lang = 'html';
else
lang = 'tmce';
} else if( 'tinymce' == lang )
lang = 'tmce';
var inst = tinyMCE.get('qtrans_textarea_' + id);
var vta = document.getElementById('qtrans_textarea_' + id);
var ta = document.getElementById(id);
var dom = tinymce.DOM;
var wrap_id = 'wp-'+id+'-wrap';
var wrap_id2 = 'wp-qtrans_textarea_content-wrap';
// update merged content
if(inst && ! inst.isHidden()) {
tinyMCE.triggerSave();
} else {
qtrans_save(vta.value);
}
// check if language is already active
if(lang!='tmce' && lang!='html' && document.getElementById('qtrans_select_'+lang).className=='wp-switch-editor switch-tmce switch-html') {
return;
}
if(lang!='tmce' && lang!='html') {
document.getElementById('qtrans_select_'+qtrans_get_active_language()).className='wp-switch-editor';
document.getElementById('qtrans_select_'+lang).className='wp-switch-editor switch-tmce switch-html';
}
if(lang=='html') {
if ( inst && inst.isHidden() )
return false;
if ( inst ) {
vta.style.height = inst.getContentAreaContainer().offsetHeight + 20 + 'px';
inst.hide();
}
dom.removeClass(wrap_id, 'tmce-active');
dom.addClass(wrap_id, 'html-active');
dom.removeClass(wrap_id2, 'tmce-active');
dom.addClass(wrap_id2, 'html-active'); setUserSetting( 'editor', 'html' );
setUserSetting( 'editor', 'html' );
} else if(lang=='tmce') {
if(inst && ! inst.isHidden())
return false;
if ( typeof(QTags) != 'undefined' )
QTags.closeAllTags('qtrans_textarea_' + id);
if ( tinyMCEPreInit.mceInit['qtrans_textarea_'+id] && tinyMCEPreInit.mceInit['qtrans_textarea_'+id].wpautop )
vta.value = this.wpautop(qtrans_use(qtrans_get_active_language(),ta.value));
if (inst) {
inst.show();
} else {
qtrans_hook_on_tinyMCE('qtrans_textarea_'+id, true);
}
dom.removeClass(wrap_id, 'html-active');
dom.addClass(wrap_id, 'tmce-active');
dom.removeClass(wrap_id2, 'html-active');
dom.addClass(wrap_id2, 'tmce-active'); setUserSetting('editor', 'tinymce');
setUserSetting('editor', 'tinymce');
} else {
// switch content
qtrans_assign('qtrans_textarea_'+id,qtrans_use(lang,ta.value));
}
}
";
}
?>
<?php // encoding: utf-8
/* Copyright 2008 Qian Qin (email : mail@qianqin.de)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Modifications Hacks to get Wordpress work the way it should */
// modifys term form to support multilingual content
function qtrans_modifyTermForm($id, $name, $term) {
global $q_config;
echo "<script type=\"text/javascript\">\n// <![CDATA[\r\n";
// ' workaround
if(is_object($term)&&isset($term->name)) {
$termname = $term->name;
} else {
$termname = "";
}
// create input fields for each language
foreach($q_config['enabled_languages'] as $language) {
if(isset($_GET['action']) && $_GET['action']=='edit') {
echo qtrans_insertTermInput2($id, $name, $termname, $language);
} else {
echo qtrans_insertTermInput($id, $name, $termname, $language);
}
}
// hide real category text
echo "ins.style.display='none';\n";
echo "// ]]>\n</script>\n";
}
function qtrans_modifyTermFormFor($term) {
qtrans_modifyTermForm('name', __('Name'), $term);
qtrans_modifyTermForm('tag-name', __('Name'), $term);
}
function qtrans_TinyMCE_init() {
global $q_config;
echo "<script type=\"text/javascript\">\n// <![CDATA[\n";
echo $q_config['js']['qtrans_updateTinyMCE'];
echo "</script>\n";
}
// Modifys TinyMCE to edit multilingual content
function qtrans_modifyRichEditor($old_content) {
global $q_config;
$init_editor = true;
if($GLOBALS['wp_version'] != QT_SUPPORTED_WP_VERSION) {
if(!(isset($_REQUEST['qtranslateincompatiblemessage'])&&$_REQUEST['qtranslateincompatiblemessage']=="shown")) {
echo '<div class="updated" id="qtrans_imsg">'.__('The qTranslate Editor has disabled itself because it hasn\'t been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by <a href="javascript:qtrans_editorInit();" title="Activate qTranslate" id="qtrans_imsg_link">clicking here</a> (may cause <b>data loss</b>! Use at own risk!). To remove this message permanently, please update qTranslate to the <a href="http://www.qianqin.de/qtranslate/download/">corresponding version</a>.', 'qtranslate').'</div>';
}
$init_editor = false;
}
// save callback hook
preg_match("/<textarea[^>]*id=\"([^']+)\"/",$old_content,$matches);
$id = $matches[1];
preg_match("/cols=\"([^\"]+)\"/",$old_content,$matches);
$cols = $matches[1];
// don't do anything if not editing the content
if($id!="content") return $old_content;
// don't do anything to the editor if it's not rich
if(!user_can_richedit()) {
//echo '<p class="updated">'.__('The qTranslate Editor could not be loaded because WYSIWYG/TinyMCE is not activated in your profile.').'</p>';
return $old_content;
}
// remove wpautop
if('html' != wp_default_editor()) {
remove_filter('the_editor_content', 'wp_richedit_pre');
}
$content = "";
$content_append = "";
// create editing field for selected languages
$qt_textarea = '<textarea id="qtrans_textarea_'.$id.'" name="qtrans_textarea_'.$id.'" tabindex="2" cols="'.$cols.'" style="display:none" onblur="qtrans_save(this.value);"></textarea>';
$old_content = preg_replace('#(<textarea[^>]*>.*</textarea>)#', '$1'.$qt_textarea, $old_content);
// do some crazy js to alter the admin view
$content .="<script type=\"text/javascript\">\n// <![CDATA[\n";
// include needed js functions
$content .= $q_config['js']['qtrans_is_array'];
$content .= $q_config['js']['qtrans_xsplit'];
$content .= $q_config['js']['qtrans_split'];
$content .= $q_config['js']['qtrans_integrate'];
$content .= $q_config['js']['qtrans_use'];
$content .= $q_config['js']['qtrans_assign'];
$content .= $q_config['js']['qtrans_save'];
$content .= $q_config['js']['qtrans_integrate_title'];
$content .= $q_config['js']['qtrans_get_active_language'];
$content .= $q_config['js']['qtrans_hook_on_tinyMCE'];
$content .="function qtrans_editorInit1() {\n";
$content .= $q_config['js']['qtrans_switch'];
// insert language, visual and html buttons
$el = qtrans_getSortedLanguages();
foreach($el as $language) {
$content .= qtrans_insertTitleInput($language);
}
$el = qtrans_getSortedLanguages(true);
foreach($el as $language) {
$content .= qtrans_createEditorToolbarButton($language, $id);
}
$content = apply_filters('qtranslate_toolbar', $content);
// hide old title bar
$content .= "document.getElementById('titlediv').style.display='none';\n";
$content .="}\n";
$content .="// ]]>\n</script>\n";
$content_append .="<script type=\"text/javascript\">\n// <![CDATA[\n";
$content_append .="function qtrans_editorInit2() {\n";
// show default language tab
$content_append .="document.getElementById('qtrans_select_".$q_config['default_language']."').className='wp-switch-editor switch-tmce switch-html';\n";
// show default language
$content_append .="var text = document.getElementById('".$id."').value;\n";
$content_append .="qtrans_assign('qtrans_textarea_".$id."',qtrans_use('".$q_config['default_language']."',text));\n";
$content_append .="}\n";
$content_append .="function qtrans_editorInit3() {\n";
// make tinyMCE and mediauploader get the correct data
$content_append .=$q_config['js']['qtrans_tinyMCEOverload'];
$content_append .=$q_config['js']['qtrans_wpActiveEditorOverload'];
$content_append .="}\n";
$content_append .=$q_config['js']['qtrans_editorInit'];
if($init_editor) {
$content_append .=$q_config['js']['qtrans_wpOnload'];
} else {
$content_append .="var qtmsg = document.getElementById('qtrans_imsg');\n";
$content_append .="var et = document.getElementById('wp-".$id."-editor-tools');\n";
$content_append .="et.parentNode.insertBefore(qtmsg, et);\n";
}
$content_append = apply_filters('qtranslate_modify_editor_js', $content_append);
$content_append .="// ]]>\n</script>\n";
return $content.$old_content.$content_append;
}
function qtrans_modifyExcerpt() {
global $q_config;
echo "<script type=\"text/javascript\">\n// <![CDATA[\n";
echo "if(jQuery('#excerpt').size()>0) {";
echo $q_config['js']['qtrans_is_array'];
echo $q_config['js']['qtrans_xsplit'];
echo $q_config['js']['qtrans_split'];
echo $q_config['js']['qtrans_integrate'];
echo $q_config['js']['qtrans_switch_postbox'];
echo $q_config['js']['qtrans_use'];
$el = qtrans_getSortedLanguages();
foreach($el as $language) {
echo qtrans_createTitlebarButton('postexcerpt', $language, 'excerpt', 'qtrans_switcher_postexcerpt_'.$language);
echo qtrans_createTextArea('postexcerpt', $language, 'excerpt', 'qtrans_switcher_postexcerpt_'.$language);
}
echo "qtrans_switch_postbox('postexcerpt','excerpt','".$q_config['default_language']."', false);";
echo "jQuery('#excerpt').hide();";
echo "}";
echo "// ]]>\n</script>\n";
}
function qtrans_createTitlebarButton($parent, $language, $target, $id) {
global $q_config;
$html = "
jQuery('#".$parent." .handlediv').after('<div class=\"qtranslate_lang_div\" id=\"".$id."\"><img alt=\"".$language."\" title=\"".$q_config['language_name'][$language]."\" src=\"".WP_CONTENT_URL.'/'.$q_config['flag_location'].$q_config['flag'][$language]."\" /></div>');
jQuery('#".$id."').click(function() {qtrans_switch_postbox('".$parent."','".$target."','".$language."');});
";
return $html;
}
function qtrans_createTextArea($parent, $language, $target, $id) {
global $q_config;
$html = "
jQuery('#".$target."').after('<textarea name=\"qtrans_textarea_".$target."_".$language."\" id=\"qtrans_textarea_".$target."_".$language."\"></textarea>');
jQuery('#qtrans_textarea_".$target."_".$language."').attr('cols', jQuery('#".$target."').attr('cols'));
jQuery('#qtrans_textarea_".$target."_".$language."').attr('rows', jQuery('#".$target."').attr('rows'));
jQuery('#qtrans_textarea_".$target."_".$language."').attr('tabindex', jQuery('#".$target."').attr('tabindex'));
jQuery('#qtrans_textarea_".$target."_".$language."').blur(function() {qtrans_switch_postbox('".$parent."','".$target."',false);});
jQuery('#qtrans_textarea_".$target."_".$language."').val(qtrans_use('".$language."',jQuery('#".$target."').val()));
";
return $html;
}
function qtrans_insertTermInput($id,$name,$term,$language){
global $q_config;
$html ="
var il = document.getElementsByTagName('input');
var d = document.createElement('div');
var l = document.createTextNode('".$name." (".$q_config['language_name'][$language].")');
var ll = document.createElement('label');
var i = document.createElement('input');
var ins = null;
for(var j = 0; j < il.length; j++) {
if(il[j].id=='".$id."') {
ins = il[j];
break;
}
}
i.type = 'text';
i.id = i.name = ll.htmlFor ='qtrans_term_".$language."';
";
if(isset($q_config['term_name'][$term][$language])) {
$html .="
i.value = '".addslashes(htmlspecialchars_decode($q_config['term_name'][$term][$language], ENT_NOQUOTES))."';
";
} else {
$html .="
i.value = ins.value;
";
}
if($language == $q_config['default_language']) {
$html .="
i.onchange = function() {
var il = document.getElementsByTagName('input');
var ins = null;
for(var j = 0; j < il.length; j++) {
if(il[j].id=='".$id."') {
ins = il[j];
break;
}
}
ins.value = document.getElementById('qtrans_term_".$language."').value;
};
";
}
$html .="
ins = ins.parentNode;
d.className = 'form-field form-required';
ll.appendChild(l);
d.appendChild(ll);
d.appendChild(i);
ins.parentNode.insertBefore(d,ins);
";
return $html;
}
function qtrans_insertTermInput2($id,$name,$term,$language){
global $q_config;
$html ="
var tr = document.createElement('tr');
var th = document.createElement('th');
var ll = document.createElement('label');
var l = document.createTextNode('".$name." (".$q_config['language_name'][$language].")');
var td = document.createElement('td');
var i = document.createElement('input');
var ins = document.getElementById('".$id."');
i.type = 'text';
i.id = i.name = ll.htmlFor ='qtrans_term_".$language."';
";
if(isset($q_config['term_name'][$term][$language])) {
$html .="
i.value = '".addslashes(htmlspecialchars_decode($q_config['term_name'][$term][$language], ENT_QUOTES))."';
";
} else {
$html .="
i.value = ins.value;
";
}
if($language == $q_config['default_language']) {
$html .="
i.onchange = function() {
var il = document.getElementsByTagName('input');
var ins = null;
for(var j = 0; j < il.length; j++) {
if(il[j].id=='".$id."') {
ins = il[j];
break;
}
}
ins.value = document.getElementById('qtrans_term_".$language."').value;
};
";
}
$html .="
ins = ins.parentNode.parentNode;
tr.className = 'form-field form-required';
th.scope = 'row';
th.vAlign = 'top';
ll.appendChild(l);
th.appendChild(ll);
tr.appendChild(th);
td.appendChild(i);
tr.appendChild(td);
ins.parentNode.insertBefore(tr,ins);
";
return $html;
}
function qtrans_insertTitleInput($language){
global $q_config;
$html ="
var td = document.getElementById('titlediv');
var qtd = document.createElement('div');
var h = document.createElement('h3');
var l = document.createTextNode('".__("Title", 'qtranslate')." (".$q_config['language_name'][$language].")');
var tw = document.createElement('div');
var ti = document.createElement('input');
var slug = document.getElementById('edit-slug-box');
ti.type = 'text';
ti.id = 'qtrans_title_".$language."';
ti.tabIndex = '1';
ti.value = qtrans_use('".$language."', document.getElementById('title').value);
ti.onchange = qtrans_integrate_title;
ti.className = 'qtrans_title_input';
h.className = 'qtrans_title';
tw.className = 'qtrans_title_wrap';
qtd.className = 'postarea';
h.appendChild(l);
tw.appendChild(ti);
qtd.appendChild(h);
qtd.appendChild(tw);";
if($q_config['default_language'] == $language)
$html.="if(slug) qtd.appendChild(slug);";
$html.="
td.parentNode.insertBefore(qtd,td);
";
return $html;
}
function qtrans_createEditorToolbarButton($language, $id, $js_function = 'switchEditors.go', $label = ''){
global $q_config;
$html = "
var bc = document.getElementById('wp-".$id."-editor-tools');
var mb = document.getElementById('wp-".$id."-media-buttons');
var ls = document.createElement('a');
var l = document.createTextNode('".(($label==='')?$q_config['language_name'][$language]:$label)."');
ls.id = 'qtrans_select_".$language."';
ls.className = 'wp-switch-editor';
ls.onclick = function() { ".$js_function."('".$id."','".$language."'); };
ls.appendChild(l);
bc.insertBefore(ls,mb);
";
return $html;
}
?>
@vince-roy
Copy link

Very helpful! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment