| [ Index ] |
PHP Cross Reference of GlotPress |
[Summary view] [Print] [Text view]
1 <?php 2 3 function google_translate_batch( $locale, $strings ) { 4 if ( !$locale->google_code ) { 5 return new WP_Error( 'google_translate', sprintf( "The locale %s isn't supported by Google Translate.", $locale->slug ) ); 6 } 7 $url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=' . urlencode( 'en|'.$locale->google_code ); 8 foreach ( $strings as $string ) { 9 $url .= '&q=' . urlencode( $string ); 10 } 11 if ( count( $strings ) == 1 ) $url .= '&q='; 12 $response = wp_remote_get( $url ); 13 if ( is_wp_error( $response ) ) { 14 return $response; 15 } 16 $json = json_decode( wp_remote_retrieve_body( $response ) ); 17 if ( !$json ) { 18 return new WP_Error( 'google_translate', 'Error decoding JSON from Google Translate.' ); 19 } 20 if ( $json->responseStatus != 200 ) { 21 return new WP_Error( 'google_translate', sprintf( 'Error auto-translating: %1$s (%2$s)', $json->responseDetails, $json->responseStatus ) ); 22 } 23 $translations = array(); 24 if ( !is_array( $json->responseData ) ) $json->responseData = array( $json->responseData ); 25 foreach( gp_array_zip( $strings, $json->responseData ) as $item ) { 26 list( $string, $translation ) = $item; 27 if ( $translation->responseStatus == 200 ) { 28 $translations[] = google_translate_fix( $translation->responseData->translatedText ); 29 } else { 30 $max_len = 20; 31 $excerpt = strlen( $string ) > $max_len? substr( $string, 0, $max_len - 3 ).'...' : $string; 32 $message = sprintf( 'Error auto-translating string "$1$s": %2$s (%3$s)', $excerpt, $translation->responseDetails, $translation->responseStatus ); 33 $translations[] = new WP_Error( 'google_translate', $message ); 34 } 35 } 36 return $translations; 37 } 38 39 function google_translate_fix( $string ) { 40 $string = preg_replace_callback( '/% (s|d)/i', lambda( '$m', '"%".strtolower($m[1])' ), $string ); 41 $string = preg_replace_callback( '/% (\d+) \$ (s|d)/i', lambda( '$m', '"%".$m[1]."\\$".strtolower($m[2])' ), $string ); 42 return $string; 43 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated: Thu May 24 03:59:35 2012 | Hosted by follow the white rabbit. |