<?php
/*
 * $Id: icl_core.module,v 1.22.2.6 2010/10/20 09:39:46 brucepearson Exp $
 * 
 * @file This is the core ICanLocalize service. This provides the API for other modules
 * to access ICanLocalize services
 */

define ( 'ICL_PERM_ADMINISTER', 'administer icanlocalize' );

define ( 'ICL_STATUS_INQUEUE', 0 );
define ( 'ICL_STATUS_REQUESTED', 1 );
define ( 'ICL_STATUS_UNKNOWN_2', 2 );
define ( 'ICL_STATUS_UNKNOWN_3', 3 );
define ( 'ICL_STATUS_UNKNOWN_4', 4 );
define ( 'ICL_STATUS_READY', 5 );
define ( 'ICL_STATUS_SUCCESSFUL', 6 );
define ( 'ICL_STATUS_FAILED', 7 );

define ( 'ICL_STATUS_CANCEL', 99 ); // NOTE: this status doesn't get stored in the database
                                    // it is just used to communicate a cancel operation.  


define ( 'CMS_TARGET_LANGUAGE_CREATED', 0);
define ( 'CMS_TARGET_LANGUAGE_ASSIGNED', 1);
define ( 'CMS_TARGET_LANGUAGE_TRANSLATED', 2);
define ( 'CMS_TARGET_LANGUAGE_DONE', 3);

define ( 'ICL_USER_STATUS_NEW', 0); // just signed up
define ( 'ICL_USER_STATUS_REGISTERED', 1); // verified email address
define ( 'ICL_USER_STATUS_QUALIFIED', 2); // passed translator qualifications
define ( 'ICL_USER_STATUS_CLOSED', 3); // used deleted from the system
define ( 'ICL_USER_STATUS_PRIVATE_TRANSLATOR', 4); // private translator

define ( 'ICL_CORE_RECEIVE_XMLRPC', 'xmlrpc' );
define ( 'ICL_CORE_RECEIVE_POLL', 'poll' );

define ( 'ICL_CORE_SELECT_TRANSLATORS_ICANLOCALIZE', 'ican_translators');
define ( 'ICL_CORE_SELECT_TRANSLATORS_CLIENT', 'client_translators');
define ( 'ICL_CORE_SELECT_TRANSLATORS_PRIVATE', 'private_translators');

module_load_include('inc', 'icl_core', 'icl_core.wrapper');
module_load_include('inc', 'icl_content', 'icl_content.stats');

/**
 * Implementation of hook_perms()
 * @see http://api.drupal.org/api/function/hook_perm/6
 *
 * @return array The permissions in an array
 */
function icl_core_perm() {
  return array (
      ICL_PERM_ADMINISTER);
}

/**
 * Implementation of hook_menu().
 * @see http://api.drupal.org/api/function/hook_menu/6
 *
 * @return array
 */
function icl_core_menu() {
  /*
   $items [_icl_wrapper_get_drupal_menu('admin/settings/icl-core')] = array (
      'title' => 'ICanLocalize Setup', 
      'description' => 'Configure the ICanLocalize access parameters and available languages.', 
      'page callback' => 'drupal_get_form', 
      'page arguments' => array (
          'icl_core_admin_settings' ), 
      'access arguments' => array (
          ICL_PERM_ADMINISTER ), 
      'file' => 'icl_core.settings.inc' );
  */
  
  $items ['icl-core/retrieve-langs'] = array (
      'page callback' => 'icl_core_retrieve_langs_js', 
      'access arguments' => array (
          'administer site configuration' ), 
      'type' => MENU_CALLBACK, 
      'file' => 'icl_core.settings.inc' );
  $items ['icl_core/refresh'] = array (
      'page callback' => 'icl_core_fetch_languages', 
      'page arguments' => array (
          TRUE ),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK, 
      'file' => 'icl_core.webservices.inc' );
  
  $items ['icl_core/fetch_reminders'] = array (
      'page callback' => 'icl_core_fetch_reminders', 
      'page arguments' => array (
          TRUE ),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK, 
      'file' => 'icl_core.webservices.inc' );
  
  $items ['icl_core/delete_reminder'] = array (
      'page callback' => 'icl_core_delete_reminder', 
      'page arguments' => array (
          TRUE ),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK, 
      'file' => 'icl_core.webservices.inc' );
  
  $items ['icl_core/show_reminders'] = array (
      'page callback' => 'icl_core_show_reminders', 
      'page arguments' => array (
          TRUE ),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK, 
      'file' => 'icl_core.settings.inc' );
  
    $items[_icl_wrapper_get_drupal_menu('admin/settings/language/ican_localize')] = array(
      'title' => 'ICanLocalize',
      'description' => 'Configure custom language mapping for ICanLocalize.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('icl_core_custom_languages_form'),
      'access arguments' => array('administer site configuration'),
      'type' => MENU_LOCAL_TASK,
      'file' => 'icl_core.languages.inc',
      'weight' => 11,
    );
    
  $items ['icl-core/reminders'] = array (
      'page callback' => 'icl_core_reminders', 
      'access arguments' => array (
          ICL_PERM_ADMINISTER ), 
      'type' => MENU_CALLBACK, 
      'file' => 'icl_core.settings.inc' );
  
  return $items;
}

/**
* Implementation of hook_theme().
* @see http://api.drupal.org/api/function/hook_theme/6
*
* @return array
*/
function icl_core_theme() {
  return  _icl_wrapper_hook_theme(array (
    'icl_core_custom_languages_form' => array(
        'arguments' => array(
            'form' => NULL )
    ) ));
}

/**
 * Implementation of hook_cron()
 * @see http://api.drupal.org/api/function/hook_cron/6
 *
 */
function icl_core_cron() {
  
  // Poll if necessary
  $available_translation_services = module_invoke_all('translation_service');
  
  foreach ($available_translation_services as $module => $service) {
    module_invoke($module, 'poll_for_translations');
  }
  
  icl_core_post_process_translations();
}

/**
 *  process all translated content
 *  1) fixes links in translated content
 *  2) Syncs book structure
 *  3) Syncs blocks
 *  4) Syncs menus
 */

function icl_core_post_process_translations() {
  
  if(variable_get ( 'icl_content_update_links_options', ICL_CONTENT_UPDATE_LINKS ) == ICL_CONTENT_UPDATE_LINKS) {
    icl_content_fix_links_in_all_dirty_nodes();
  }

  module_load_include ( 'inc', 'icl_core', 'icl_core.webservices' );
  
  $comments = icl_core_comment_pickup();
  if ($comments !== FALSE) {
    icl_content_process_comments($comments);
  }
  
  icl_content_update_books();
  
  icl_content_sync_blocks();
  icl_content_update_links_in_blocks();
  
  module_load_include ( 'inc', 'icl_content', 'icl_content.menus' );
  
  icl_content_sync_menus_waiting();

  if (module_exists ( 'domain' )) {
    
    // There is a problem with the domain being lost when we create a translation.
    // As a last step we need to make sure the nodes we created have
    // the correct domains.

    global $_icl_domain;
    if (isset($_icl_domain)) {
      foreach($_icl_domain as $nid => $saved_node){
        $node = node_load($nid, NULL, TRUE);
        if ($node->domains != $saved_node->domains ||
              $node->domain_site != $saved_node->domain_site ||
              $node->subdomains != $saved_node->subdomains) {
          $node->domains = $saved_node->domains;
          $node->domain_site = $saved_node->domain_site;
          $node->subdomains = $saved_node->subdomains;
          node_save($node);
        }
          
      }
    }
  }
}

/**
 * Implementation of hook_help().
 */
function icl_core_help($path, $arg) {
  // @todo Review and remove
//  switch ($path) {
//    case 'node/%/translate':
//      $parts = split('/', $_GET['q']);
//      $nid = $parts[1];
//      $output = '<h1 class="title">ICanLocalize - Translation Manager</h1><p><div class="status"><b>'. t('Note: This page lets you enter translations manually. To send translation jobs to your translator(s), use the Translation dashboard.<br /><input class="form-submit" type="BUTTON" OnClick="location.href=\'@url\'" value="Translate using the Translation Dashboard"><br /><br />', array('@url' => _icl_wrapper_url(_icl_wrapper_get_root_menu('translation-management/dashboard'), array('query' => 'nid=' . $nid)))) .'</b></div></p>';
//      return $output;
//
//    case 'admin/settings/language/ican_localize':
//      $output = '<p>'. t("This page provides an overview of your site's enabled languages and how they are associated with languages on ICanLocalize. You can use this to map custom languages to ICanLocalize languages.") .'</p>';
//      $output .= '<p>'. t('eg. You may have created a custom english language with a code of en-US. You can use this page to map this to English on ICanLocalize.') .'</p>';
//      return $output;
//
//  }

   if ($path == _icl_wrapper_get_drupal_menu('node/%/translate')) {
      $parts = split('/', $_GET['q']);
      $nid = $parts[1];
      $output = '<h1 class="title">ICanLocalize - Translation Manager</h1><p><div class="status"><b>'. t('Note: This page lets you enter translations manually. To send translation jobs to your translator(s), use the Translation dashboard.<br /><input class="form-submit" type="BUTTON" OnClick="location.href=\'@url\'" value="Translate using the Translation Dashboard"><br /><br />', array('@url' => _icl_wrapper_url(_icl_wrapper_get_root_menu('translation-management/dashboard'), array('query' => 'nid=' . $nid)))) .'</b></div></p>';
      return $output;
   } else if ($path == _icl_wrapper_get_drupal_menu('admin/settings/language/ican_localize')) {
      $output = '<p>'. t("This page provides an overview of your site's enabled languages and how they are associated with languages on ICanLocalize. You can use this to map custom languages to ICanLocalize languages.") .'</p>';
      $output .= '<p>'. t('eg. You may have created a custom english language with a code of en-US. You can use this page to map this to English on ICanLocalize.') .'</p>';
      return $output;

  }
}

/* ============= [ API functions ] ============ */

/**
 * Add a translation request
 *
 * @param string $module The module name which requests notification when status changes and translations.
 * @param array $data The data which needs translation.
 * @param string $origin The language the data is currently. 
 * @param array $targets The target languages. 
 * @param bool $is_new Whether this is a new data to request or an update. 
 * @param string $linkTo The link to the data if exists. 
 * @return bool|int The request id if successful, FALSE otherwise.
 */
function icl_core_add_request($module, $data, $origin, $targets, $previous_id = FALSE, $linkTo = '', $title = '', $translators = NULL) {
  $target_names = array ();
  $target_codes = array ();
  foreach ( $targets as $lang ) {
    if ($lang->enabled) {
      $target_names [] = $lang->name;
      $target_codes [] = $lang->language;
    }
  }
  
  $result = FALSE;
  $service_rid = FALSE;

  // create a translation job  
  module_load_include ( 'inc', 'icl_translate', 'icl_translate.jobs' );
  $rid = icl_translate_create_translation_job($data,
                            $target_codes[0],
                            $previous_id);
  
  $translation_service = $translators[$target_codes[0]]['translation_service'];
  
  $available_translation_services = module_invoke_all('translation_service');
  
  module_load_include('inc', 'icl_translate', 'icl_translate.translation_services');
  foreach ($available_translation_services as $service_module => $service) {
    if ($translation_service == icl_translate_get_service_name_key($service['name'])) {
      // Found the service.
      
      $result = module_invoke($service_module, 'request_translation',
                            $rid,
                            $origin,
                            $targets,
                            $previous_id,
                            $translators[$target_codes[0]]['id'],
                            $linkTo,
                            $title );
      $service_rid = $result['service_rid'];
      $status = $result['status'];
      break;
    }
  }
  
  if ($service_rid !== FALSE) {
    $result['rid'] = $rid;
    foreach ( $target_codes as $target ) {
      $sql = "INSERT INTO {icl_core_status} (rid, service_rid, module, origin, target, status, translation_service) VALUES (%d, '%d', '%s', '%s', '%s', %d, '%s')";
      db_query ( $sql, $rid, $service_rid, $module, $origin->language, $target, $status, $translation_service );
      icl_core_notify_translation_status($rid, $target, $status);
    }
  }
  
  return $result;
}

function icl_core_send_content_for_translation($module, $data, $origin, $targets, $previous_rids, $linkTo = '', $title = '', $translators = NULL) {
  
  $languages = language_list('enabled');
  $languages = $languages[1];
  
  // create a separate cms_request for each language.
  
  $targets_sent = array();
  foreach($targets as $lang_target){
    
    // If this has a previous request we need to separate our lang targets that
    // point to the same langauge.
    
    if ( !is_array($lang_target)) {
      $lang_target = array($lang_target);
    }

    // If this has a previous request we need to separate our lang targets that
    // point to the same langauge.
    $found_langs = array();
    $duplicate_langs = array();
    foreach ($lang_target as $index => $test_target){
      if (in_array($test_target->name, $found_langs)) {
        $duplicate_langs[] = $test_target;
        unset($lang_target[$index]);
      } else {
        $found_langs[] = $test_target->name;
      }
    }
    

    $target_name = $lang_target[0]->name;
    
    // only send if we haven't sent to this target yet
    // this can happen if we have multiple Drupal languages mapping
    // to the one ICanLocalize language. eg. en and en-us are sent to "English" 
    if ( ! array_key_exists($target_name, $targets_sent) ) {
      
      if ( $previous_rids != NULL ) {
        if (isset($previous_rids[$lang_target[0]->language])) {
          $previous_rid = $previous_rids[$lang_target[0]->language];
        } else {
          $previous_rid = false;
        }
      } else {
        $previous_rid = false;
      }
      
      $result = icl_core_add_request ( 'icl_content', $data, $origin, $lang_target, $previous_rid, $linkTo, $title, $translators);
      
      if (isset($result['rid']) && $result['rid'] != FALSE) {
        $rid = $result['rid'];
        drupal_set_message($result['message']);
        
        foreach ($duplicate_langs as $dup_lang) {
          // we have sent to this ICanLocalize language already.
          // record it in the database for this new language code.
          $sql = "INSERT INTO {icl_core_status} (rid, module, origin, target, status) VALUES (%d, '%s', '%s', '%s', %d)";
          if ($translators[$drupal_lang->language]['translation_service'] == 'local') {
            db_query ( $sql, $rid, $module, $origin->code, $dup_lang->code, ICL_STATUS_INQUEUE );
            icl_core_notify_translation_status($rid, $dup_lang->code, ICL_STATUS_INQUEUE);
          } else {
            db_query ( $sql, $rid, $module, $origin->code, $dup_lang->code, ICL_STATUS_REQUESTED );
            icl_core_notify_translation_status($rid, $dup_lang->code, ICL_STATUS_REQUESTED);
          }
        }
      } else {
        drupal_set_message ( $result['message'], 'error');
      }
      
      $targets_sent[$target_name] = $rid;
    } else {
      // we have sent to this ICanLocalize language already.
      // record it in the database for this new language code.
      $sql = "INSERT INTO {icl_core_status} (rid, module, origin, target, status) VALUES (%d, '%s', '%s', '%s', %d)";
      if ($translators[$drupal_lang->language]['translation_service'] == 'local') {
        db_query ( $sql, $targets_sent[$target_name], $module, $origin->code, $lang_target[0]->code, ICL_STATUS_INQUEUE );
        icl_core_notify_translation_status($targets_sent[$target_name], $lang_target[0]->code, ICL_STATUS_INQUEUE);
      } else {
        db_query ( $sql, $targets_sent[$target_name], $module, $origin->code, $lang_target[0]->code, ICL_STATUS_REQUESTED );
        icl_core_notify_translation_status($targets_sent[$target_name], $lang_target[0]->code, ICL_STATUS_REQUESTED);
      }
    
      $drupal_lang = $languages[$lang_target[0]->code];
      drupal_set_message ( t ( 'The last translation (to %last) request will be used for : %lang', array (
          '%last' => $target_name,
          '%lang' => $drupal_lang->name ) ) );
    }
  }
  
  return $targets_sent;
}

/**
 * Retrieves the translation languages as an array of objects
 *
 * @param bool $cache_clear
 * @return array
 */
function icl_core_available_languages($cache_clear = FALSE, &$platform_info = NULL, $from_dashboard = FALSE) {
  static $enabled_langs = NULL;
  
  if ($enabled_langs == NULL) {
    $enabled_langs = array_flip ( locale_language_list () );
  }
  
  module_load_include ( 'inc', 'icl_core', 'icl_core.webservices' );
  $raw_langs = icl_core_fetch_languages ( $cache_clear, $from_dashboard );
  
  if (is_string ( $raw_langs )) {
    return $raw_langs;
  }

  if ($platform_info !== NULL) {
    $platform_info['platform'] = $raw_langs['platform'];
    $platform_info['pickup'] = $raw_langs['pickup'];
    $platform_info['name'] = $raw_langs['name'];
    $platform_info['description'] = $raw_langs['description'];
    $platform_info['balance'] = $raw_langs['balance'];
    $platform_info['userstatus'] = $raw_langs['userstatus'];
    $platform_info['free_usage'] = $raw_langs['free_usage'];
    $platform_info['support_ticket_id'] = $raw_langs['support_ticket_id'];
    $platform_info['accesskey'] = $raw_langs['accesskey'];
    $platform_info['url'] = $raw_langs['url'];
  }
  
  $langs = array ();
      
  foreach ( $raw_langs['langs'] as $from => $to ) {
    $lang_codes = icl_core_get_language_codes($from);
    
    foreach($lang_codes as $code) {
      $lang = new stdClass ( );
      $lang->name = $from;
      $lang->code = $code;
      $lang->id = icl_core_get_lang_id($code);
      $lang->enabled = in_array($code, $enabled_langs);
      $lang->targets = array ();
      
      foreach ( $to as $item ) {
        $target_codes = icl_core_get_language_codes($item);
        
        foreach($target_codes as $target_code) {
        
          $tlang = new stdClass ( );
          $tlang->name = $item;
          $tlang->code = $target_code;
          $tlang->id = icl_core_get_lang_id($target_code);
          $tlang->enabled = in_array($target_code, $enabled_langs);
          $tlang->have_translators = 0;
          if (isset($raw_langs['have_translators'][$from][$item])) {
            $tlang->have_translators = $raw_langs['have_translators'][$from][$item];
          }
    
          $tlang->pay_per_use = 0;
          if (isset($raw_langs['pay_per_use'][$from][$item])) {
            $tlang->pay_per_use = $raw_langs['pay_per_use'][$from][$item];
          }
          
          $tlang->cost_per_word = -1;
          if(isset($raw_langs['cost_per_word'][$from][$item])) {
            $tlang->cost_per_word = $raw_langs['cost_per_word'][$from][$item];
          }
          
          $tlang->applications = -1;
          if(isset($raw_langs['applications'][$from][$item])) {
            $tlang->applications = $raw_langs['applications'][$from][$item];
          }
          
          $tlang->available_translators = -1;
          if(isset($raw_langs['available_translators'][$from][$item])) {
            $tlang->available_translators = $raw_langs['available_translators'][$from][$item];
          }
          
          $tlang->contract_id = -1;
          if(isset($raw_langs['contract_id'][$from][$item])) {
            $tlang->contract_id = $raw_langs['contract_id'][$from][$item];
          }
          
          $tlang->offer_id = -1;
          if(isset($raw_langs['offer_id'][$from][$item])) {
            $tlang->offer_id = $raw_langs['offer_id'][$from][$item];
          }
          
          $lang->targets [$tlang->code] = $tlang;
        }
      }
      
      $langs [$lang->code] = $lang;
    }
  }  
  return $langs;
}

/* ================ [ Helpers ] =================== */

function icl_create_icl_popup_link($link, $title = null) {
  if (strpos($link, '?') !== FALSE) {
    $add = '&amp;TB_iframe=true';
  } else {
    $add = '?icl_param=0&amp;TB_iframe=true';  // need to add the dummy param so javascript will process the &TA_iframe properly.
  }
  $reminder_url = _icl_wrapper_url("icl-core/reminders");
  if (strpos($reminder_url, '?') === FALSE) {
    $glue = '?';
  } else {
    $glue = '&amp;';
  }
  if ($title) {
    return '<a class="icl_thickbox" title="' . $title . '" href="' . _icl_wrapper_url("icl-core/reminders") . $glue .  "target=" . urlencode($link) . $add . '">';
  } else {
    return '<a class="icl_thickbox" href="' . _icl_wrapper_url("icl-core/reminders") . $glue .  "target=" . urlencode($link) . $add . '">';
  }
}

function icl_core_add_thickbox() {
  $js_settings = array(
    'close' => t('Close'),
    'next' => t('Next >'),
    'prev' => t('< Prev'),
    'esc_key' => t('or Esc Key'),
    'next_close' => t('Next / Close on last'),
    'image_count' => t('Image !current of !total')
  );
  drupal_add_js(array('thickbox' => $js_settings), 'setting');

  drupal_add_js(drupal_get_path('module', 'icl_core') . '/js/thickbox.js');
  drupal_add_css(drupal_get_path('module', 'icl_core').'/css/thickbox.css');
  drupal_add_css(drupal_get_path('module', 'icl_core').'/css/thickbox_ie.css');
}

function icl_get_language_status_text($ican_languages, $platform_info, $from_lang, $to_lang) {
  $response = '';
  $website_id = variable_get ( 'icl_core_website_id', '' );
  
  if ( $website_id != '' || variable_get ( 'icl_core_accesskey', '' ) != '') {
    // check we can access with this info.
    
    foreach ($ican_languages as $lang) {
      if ($from_lang == $lang->code && isset($lang->targets[$to_lang])) {
        if (isset($lang->targets[$to_lang]->available_translators)) {
          if (!$lang->targets[$to_lang]->available_translators) {
              if ($platform_info['icl_support_ticket_id'] == '') {
                // No translators available on icanlocalize for this language pair.
                $response = sprintf( t('- (No translators available - please %sprovide more information about your site%s)'),
                                    icl_create_icl_popup_link('/websites/' . $website_id . '/explain?after=refresh_langs', 'ICanLocalize'),
                                    '</a>');
              } else {
                $response = sprintf( t('- (No translators available - %scheck progress%s)'),
                                    icl_create_icl_popup_link('/support/show/' . $this->settings['icl_support_ticket_id'] . '?after=refresh_langs', 'ICanLocalize'),
                                    '</a>');
              }
              
          } else if (!$lang->targets[$to_lang]->applications) {
            // No translators have applied for this language pair.
            $response = sprintf( t('- (Translators available)'));
          } else if (!$lang->targets[$to_lang]->have_translators) {
            // translators have applied but none selected yet
            $response = sprintf( t('- (%s translators applied - %schoose your translator%s)'),
                                $lang->targets[$to_lang]->applications,
                                icl_create_icl_popup_link('/websites/' . $website_id . '/website_translation_offers/' .  $lang->targets[$to_lang]->offer_id, 'ICanLocalize'),
                                '</a>');
          } else {
            // there are translators ready to translate
            $response = sprintf( t('- (Translator selected - %scommunicate with your translator%s)'),
                                icl_create_icl_popup_link('/websites/' . $website_id . '/website_translation_offers/' .  $lang->targets[$to_lang]->offer_id . '/website_translation_contracts/' . $lang->targets[$to_lang]->contract_id, 'ICanLocalzie'),
                                '</a>');
          }

          return $response;
          
        }
      break;
      }
                                   
    }
  }
  // no status found        
  return '';
}


function _icl_core_available_targets($cache_clear = FALSE, $source_lang = NULL) {
  static $targets = array ();
  
  $langs = icl_core_available_languages ( $cache_clear );

  if (! count ( $targets ) && is_array($langs)) {
    foreach ( $langs as $lang ) {
      if ($source_lang == NULL || $source_lang == $lang->code) {
        foreach ( $lang->targets as $target ) {
          $target->origin = $lang;
          $targets [$target->code] = $target;
        }
      }
    }
  }
  
  return $targets;
}

function _icl_core_available_targets_for_origin($origin_code, $cache_clear = FALSE) {
  $targets = array ();
  foreach ( _icl_core_available_targets ( $cache_clear, $origin_code ) as $target_code => $target ) {
    if ($target->origin->code == $origin_code) {
      $targets [$target_code] = $target;
    }
  }
  
  return $targets;
}

function _icl_core_fetch_translation_wrapper($rid, $language = null) {
  $data = array ();
  
  if ($language == null) {
    $langs = _icl_core_available_targets ();
    $query = db_query ( "SELECT target FROM {icl_core_status} WHERE rid = %d", $rid );
    while ( $target = _icl_wrapper_db_result( $query ) ) {
      $data [$target] = icl_core_fetch_translation ( $rid, $langs [$target] );
    }
  } else {
    $data [$language->code] = icl_core_fetch_translation ( $rid, $language );
  }
  
  return $data;
}


/**
 * Poll for status changes
 *
 */
function _icl_core_poll_status() {
  module_load_include ( 'inc', 'icl_core', 'icl_core.webservices' );
  
  $request_status_changes = icl_core_fetch_translation_statuses ();
  if (is_string ( $request_status_changes )) {
    watchdog ( 'icanlocalize', 'Error pulling translation statuses %data', array (
        '%data' => $request_status_changes ), WATCHDOG_ERROR );
    return;
  }
  
  foreach ($request_status_changes as $rid) {
    $request = icl_core_fetch_translation_status($rid);
    if (is_string ( $request )) {
      watchdog ( 'icanlocalize', 'Error pulling translation statuses %data', array ( '%data' => $request ), WATCHDOG_ERROR );
    }
    else {
      foreach ($request as $langcode => $status) {
        db_query ( "UPDATE {icl_core_status} SET status = %d WHERE service_rid = %d AND target = '%s'", $status, $rid, $langcode );

        icl_core_notify_translation_status($rid, $langcode, $status);
        /*
        if (db_affected_rows () == 0) {
          // data not in table so we need to insert it.

          $original_language = icl_core_fetch_original_language_code($rid);
          if (is_string ( $original_language )) {
            watchdog ( 'icanlocalize', 'Error getting original language %data', array ( '%data' => $original_language ), WATCHDOG_ERROR );
          }
          else {
            $sql = "INSERT INTO {icl_core_status} (rid, module, origin, target, status) VALUES (%d, '%s', '%s', '%s', %d)";
            db_query ( $sql, $rid, 'icl_content', $original_language['code'], $langcode, $status);
          }
          
        }
        */
        
        if (module_exists ( 'icl_debug' )) {
          $variables = array (
              '%request' => $rid, 
              '%language' => $langcode, 
              '%status' => $status );
          icl_debug_watchdog_debug ( 'icl_core', 'Status update by polling: RID: %request, LANG: %language, STATUS: %status', $variables );
        }
      }
        
    }
  }
}


/**
 * Sets the status in the local database.
 *
 * @param int $request_id
 * @param int $status
 * @param array $target
 * @return bool
 */
function icl_core_set_local_status($request_id, $status, $target = array()) {
  $sql = "UPDATE {icl_core_status} SET status = %d WHERE rid = %d";
  if (count ( $target )) {
    $langs = array ();
    foreach ( $target as $item ) {
      $langs [] = "'" . $item->language . "'";
      icl_core_notify_translation_status($request_id, $item->language, $status);
      
    }
    $sql .= " AND target IN (" . implode ( ', ', $langs ) . ")";
  } else {
    $site_languages = language_list('enabled', TRUE);
    foreach ($site_languages[1] as $code => $value) {
      icl_core_notify_translation_status($request_id, $code, $status);
    }
  }
  $result = db_query ( $sql, $status, $request_id );
  if ($result === FALSE) {
    return FALSE;
  } else {
    return db_affected_rows () > 0;
  }
}

function icl_core_notify_translation_status($rid, $langcode, $status) {
  $nid = _icl_wrapper_db_result(_icl_wrapper_db_query("SELECT nid FROM {icl_content_status} WHERE rid=%d", $rid));
  
  if ($nid) {
  
    module_invoke_all("translation_status", $nid, $langcode, $status);
  }
  
  if (variable_get('icl_translate_reports_enabled', FALSE) && variable_get('icl_report_on_status_change', FALSE)) {
    icl_content_do_translation_status_report();
  }
  
}

/**
 * Returns the statuses for the given request
 *
 * @param int $rid
 */
function icl_core_get_statuses($rid) {
  $query = db_query ( "SELECT target, status FROM {icl_core_status} WHERE rid = %d", $rid );
  $result = array ();
  while ( $item = db_fetch_object ( $query ) ) {
    $result [$item->target] = $item->status;
  }
  
  return $result;
}

/**
 * Get the ICanLocalize language name from the code.
 */
 
function icl_core_get_language_name($code) {
  return _icl_wrapper_db_result(db_query("SELECT icl_name FROM {icl_languages} WHERE code='%s'", $code));
}

/**
 * Get the drupal language name from the code.
 */
 
function icl_core_get_drupal_language_name($code) {
  
  return _icl_wrapper_db_result(db_query("SELECT name FROM {languages} WHERE language='%s'", $code));
}

/**
 * Get the drupal language name from the code.
 */
 
function icl_core_get_drupal_language_names_from_ican_language($name) {
  
  $names = "";

  $codes = icl_core_get_language_codes($name);
  
  foreach($codes as $code) {
    if ( $names == "" ) {
      $names = icl_core_get_drupal_language_name($code);
    } else {
      $names .= '/' . icl_core_get_drupal_language_name($code);
    }
  }
  
  return $names;
}

/**
 * Get the language codes from the ICanLocalize name.
 */
 
function icl_core_get_language_codes($name) {

  // Get the drupal languages.  
  $languages = language_list('enabled');
  $languages = array_keys($languages[1]);
  
  $codes = array();
  
  $result = db_query("SELECT code FROM {icl_languages} WHERE icl_name='%s'", $name);
  
  while($code = db_fetch_object($result)) {
    // add to list if it is enabled in drupal.
    if (in_array($code->code, $languages)) {
      $codes[] = $code->code;
    }
  }
  
  return $codes;
}

/**
 * Get the language id from the code.
 */
 
function icl_core_get_lang_id($code) {
  
  return _icl_wrapper_db_result(db_query("SELECT icl_id FROM {icl_languages} WHERE code='%s'", $code));
}


/*
 * Fetches all languages to an array.
 *
 * @return array The all language list
 *
 * The 'key' is the drupal name
 * 'code' = drupal code
 * 'name' = icanlocalize name
 * 'id' = icanloclaize id
 */
function _icl_core_get_all_languages() {
  return array (
      'Afar' => array (
          'code' => 'aa', 
          'name' => 'Afar', 
          'id' => 0 ), 
      'Abkhazian' => array (
          'code' => 'ab', 
          'name' => 'Abkhazian', 
          'id' => 0 ), 
      'Avestan' => array (
          'code' => 'ae', 
          'name' => 'Avestan', 
          'id' => 0 ), 
      'Afrikaans' => array (
          'code' => 'af', 
          'name' => 'Afrikaans', 
          'id' => 0 ), 
      'Akan' => array (
          'code' => 'ak', 
          'name' => 'Akan', 
          'id' => 0 ), 
      'Amharic' => array (
          'code' => 'am', 
          'name' => 'Amharic', 
          'id' => 0 ), 
      'Arabic' => array (
          'code' => 'ar', 
          'name' => 'Arabic', 
          'id' => '5' ), 
      'Assamese' => array (
          'code' => 'as', 
          'name' => 'Assamese', 
          'id' => 0 ), 
      'Avar' => array (
          'code' => 'av', 
          'name' => 'Avar', 
          'id' => 0 ), 
      'Aymara' => array (
          'code' => 'ay', 
          'name' => 'Aymara', 
          'id' => 0 ), 
      'Azerbaijani' => array (
          'code' => 'az', 
          'name' => 'Azerbaijani', 
          'id' => 0 ), 
      'Bashkir' => array (
          'code' => 'ba', 
          'name' => 'Bashkir', 
          'id' => 0 ), 
      'Belarusian' => array (
          'code' => 'be', 
          'name' => 'Belarusian', 
          'id' => 0 ), 
      'Bulgarian' => array (
          'code' => 'bg', 
          'name' => 'Bulgarian', 
          'id' => '7' ), 
      'Bihari' => array (
          'code' => 'bh', 
          'name' => 'Bihari', 
          'id' => 0 ), 
      'Bislama' => array (
          'code' => 'bi', 
          'name' => 'Bislama', 
          'id' => 0 ), 
      'Bambara' => array (
          'code' => 'bm', 
          'name' => 'Bambara', 
          'id' => 0 ), 
      'Bengali' => array (
          'code' => 'bn', 
          'name' => 'Bengali', 
          'id' => 0 ), 
      'Tibetan' => array (
          'code' => 'bo', 
          'name' => 'Tibetan', 
          'id' => 0 ), 
      'Breton' => array (
          'code' => 'br', 
          'name' => 'Breton', 
          'id' => 0 ), 
      'Bosnian' => array (
          'code' => 'bs', 
          'name' => 'Bosnian', 
          'id' => '6' ), 
      'Catalan' => array (
          'code' => 'ca', 
          'name' => 'Catalan', 
          'id' => '8' ), 
      'Chechen' => array (
          'code' => 'ce', 
          'name' => 'Chechen', 
          'id' => 0 ), 
      'Chamorro' => array (
          'code' => 'ch', 
          'name' => 'Chamorro', 
          'id' => 0 ), 
      'Corsican' => array (
          'code' => 'co', 
          'name' => 'Corsican', 
          'id' => 0 ), 
      'Cree' => array (
          'code' => 'cr', 
          'name' => 'Cree', 
          'id' => 0 ), 
      'Czech' => array (
          'code' => 'cs', 
          'name' => 'Czech', 
          'id' => '9' ), 
      'Old Slavonic' => array (
          'code' => 'cu', 
          'name' => 'Old Slavonic', 
          'id' => 0 ), 
      'Chuvash' => array (
          'code' => 'cv', 
          'name' => 'Chuvash', 
          'id' => 0 ), 
      'Welsh' => array (
          'code' => 'cy', 
          'name' => 'Welsh', 
          'id' => '11' ), 
      'Danish' => array (
          'code' => 'da', 
          'name' => 'Danish', 
          'id' => '12' ), 
      'German' => array (
          'code' => 'de', 
          'name' => 'German', 
          'id' => '3' ), 
      'Maldivian' => array (
          'code' => 'dv', 
          'name' => 'Maldivian', 
          'id' => 0 ), 
      'Bhutani' => array (
          'code' => 'dz', 
          'name' => 'Bhutani', 
          'id' => 0 ), 
      'Ewe' => array (
          'code' => 'ee', 
          'name' => 'Ewe', 
          'id' => 0 ), 
      'Greek' => array (
          'code' => 'el', 
          'name' => 'Greek', 
          'id' => '13' ), 
      'English' => array (
          'code' => 'en', 
          'name' => 'English', 
          'id' => '1' ), 
      'Esperanto' => array (
          'code' => 'eo', 
          'name' => 'Esperanto', 
          'id' => '14' ), 
      'Spanish' => array (
          'code' => 'es', 
          'name' => 'Spanish', 
          'id' => '2' ), 
      'Estonian' => array (
          'code' => 'et', 
          'name' => 'Estonian', 
          'id' => '15' ), 
      'Basque' => array (
          'code' => 'eu', 
          'name' => 'Basque', 
          'id' => '16' ), 
      'Persian' => array (
          'code' => 'fa', 
          'name' => 'Persian', 
          'id' => '17' ), 
      'Fulah' => array (
          'code' => 'ff', 
          'name' => 'Fulah', 
          'id' => 0 ), 
      'Finnish' => array (
          'code' => 'fi', 
          'name' => 'Finnish', 
          'id' => '18' ), 
      'Fiji' => array (
          'code' => 'fj', 
          'name' => 'Fiji', 
          'id' => 0 ), 
      'Faeroese' => array (
          'code' => 'fo', 
          'name' => 'Faeroese', 
          'id' => 0 ), 
      'French' => array (
          'code' => 'fr', 
          'name' => 'French', 
          'id' => '4' ), 
      'Frisian' => array (
          'code' => 'fy', 
          'name' => 'Frisian', 
          'id' => 0 ), 
      'Irish' => array (
          'code' => 'ga', 
          'name' => 'Irish', 
          'id' => '19' ), 
      'Scots Gaelic' => array (
          'code' => 'gd', 
          'name' => 'Scots Gaelic', 
          'id' => 0 ), 
      'Galician' => array (
          'code' => 'gl', 
          'name' => 'Galician', 
          'id' => 0 ), 
      'Guarani' => array (
          'code' => 'gn', 
          'name' => 'Guarani', 
          'id' => 0 ), 
      'Gujarati' => array (
          'code' => 'gu', 
          'name' => 'Gujarati', 
          'id' => 0 ), 
      'Manx' => array (
          'code' => 'gv', 
          'name' => 'Manx', 
          'id' => 0 ), 
      'Hausa' => array (
          'code' => 'ha', 
          'name' => 'Hausa', 
          'id' => 0 ), 
      'Hebrew' => array (
          'code' => 'he', 
          'name' => 'Hebrew', 
          'id' => '20' ), 
      'Hindi' => array (
          'code' => 'hi', 
          'name' => 'Hindi', 
          'id' => '21' ), 
      'Hiri Motu' => array (
          'code' => 'ho', 
          'name' => 'Hiri Motu', 
          'id' => 0 ), 
      'Croatian' => array (
          'code' => 'hr', 
          'name' => 'Croatian', 
          'id' => '22' ), 
      'Hungarian' => array (
          'code' => 'hu', 
          'name' => 'Hungarian', 
          'id' => '23' ), 
      'Armenian' => array (
          'code' => 'hy', 
          'name' => 'Armenian', 
          'id' => '24' ), 
      'Herero' => array (
          'code' => 'hz', 
          'name' => 'Herero', 
          'id' => 0 ), 
      'Interlingua' => array (
          'code' => 'ia', 
          'name' => 'Interlingua', 
          'id' => 0 ), 
      'Indonesian' => array (
          'code' => 'id', 
          'name' => 'Indonesian', 
          'id' => '25' ), 
      'Interlingue' => array (
          'code' => 'ie', 
          'name' => 'Interlingue', 
          'id' => 0 ), 
      'Igbo' => array (
          'code' => 'ig', 
          'name' => 'Igbo', 
          'id' => 0 ), 
      'Inupiak' => array (
          'code' => 'ik', 
          'name' => 'Inupiak', 
          'id' => 0 ), 
      'Icelandic' => array (
          'code' => 'is', 
          'name' => 'Icelandic', 
          'id' => '26' ), 
      'Italian' => array (
          'code' => 'it', 
          'name' => 'Italian', 
          'id' => '27' ), 
      'Inuktitut' => array (
          'code' => 'iu', 
          'name' => 'Inuktitut', 
          'id' => 0 ), 
      'Japanese' => array (
          'code' => 'ja', 
          'name' => 'Japanese', 
          'id' => '28' ), 
      'Javanese' => array (
          'code' => 'jv', 
          'name' => 'Javanese', 
          'id' => 0 ), 
      'Georgian' => array (
          'code' => 'ka', 
          'name' => 'Georgian', 
          'id' => 0 ), 
      'Kongo' => array (
          'code' => 'kg', 
          'name' => 'Kongo', 
          'id' => 0 ), 
      'Kikuyu' => array (
          'code' => 'ki', 
          'name' => 'Kikuyu', 
          'id' => 0 ), 
      'Kwanyama' => array (
          'code' => 'kj', 
          'name' => 'Kwanyama', 
          'id' => 0 ), 
      'Kazakh' => array (
          'code' => 'kk', 
          'name' => 'Kazakh', 
          'id' => 0 ), 
      'Greenlandic' => array (
          'code' => 'kl', 
          'name' => 'Greenlandic', 
          'id' => 0 ), 
      'Cambodian' => array (
          'code' => 'km', 
          'name' => 'Cambodian', 
          'id' => 0 ), 
      'Kannada' => array (
          'code' => 'kn', 
          'name' => 'Kannada', 
          'id' => 0 ), 
      'Korean' => array (
          'code' => 'ko', 
          'name' => 'Korean', 
          'id' => '29' ), 
      'Kanuri' => array (
          'code' => 'kr', 
          'name' => 'Kanuri', 
          'id' => 0 ), 
      'Kashmiri' => array (
          'code' => 'ks', 
          'name' => 'Kashmiri', 
          'id' => 0 ), 
      'Kurdish' => array (
          'code' => 'ku', 
          'name' => 'Kurdish', 
          'id' => '30' ), 
      'Komi' => array (
          'code' => 'kv', 
          'name' => 'Komi', 
          'id' => 0 ), 
      'Cornish' => array (
          'code' => 'kw', 
          'name' => 'Cornish', 
          'id' => 0 ), 
      'Kirghiz' => array (
          'code' => 'ky', 
          'name' => 'Kirghiz', 
          'id' => 0 ), 
      'Latin' => array (
          'code' => 'la', 
          'name' => 'Latin', 
          'id' => '31' ), 
      'Luxembourgish' => array (
          'code' => 'lb', 
          'name' => 'Luxembourgish', 
          'id' => 0 ), 
      'Luganda' => array (
          'code' => 'lg', 
          'name' => 'Luganda', 
          'id' => 0 ), 
      'Lingala' => array (
          'code' => 'ln', 
          'name' => 'Lingala', 
          'id' => 0 ), 
      'Laothian' => array (
          'code' => 'lo', 
          'name' => 'Laothian', 
          'id' => 0 ), 
      'Lithuanian' => array (
          'code' => 'lt', 
          'name' => 'Lithuanian', 
          'id' => '33' ), 
      'Latvian' => array (
          'code' => 'lv', 
          'name' => 'Latvian', 
          'id' => '32' ), 
      'Malagasy' => array (
          'code' => 'mg', 
          'name' => 'Malagasy', 
          'id' => 0 ), 
      'Marshallese' => array (
          'code' => 'mh', 
          'name' => 'Marshallese', 
          'id' => 0 ), 
      'Maori' => array (
          'code' => 'mi', 
          'name' => 'Maori', 
          'id' => 0 ), 
      'Macedonian' => array (
          'code' => 'mk', 
          'name' => 'Macedonian', 
          'id' => '34' ), 
      'Malayalam' => array (
          'code' => 'ml', 
          'name' => 'Malayalam', 
          'id' => 0 ), 
      'Mongolian' => array (
          'code' => 'mn', 
          'name' => 'Mongolian', 
          'id' => '37' ), 
      'Moldavian' => array (
          'code' => 'mo', 
          'name' => 'Moldavian', 
          'id' => '36' ), 
      'Marathi' => array (
          'code' => 'mr', 
          'name' => 'Marathi', 
          'id' => 0 ), 
      'Malay' => array (
          'code' => 'ms', 
          'name' => 'Malay', 
          'id' => 0 ), 
      'Maltese' => array (
          'code' => 'mt', 
          'name' => 'Maltese', 
          'id' => '35' ), 
      'Burmese' => array (
          'code' => 'my', 
          'name' => 'Burmese', 
          'id' => 0 ), 
      'Nauru' => array (
          'code' => 'na', 
          'name' => 'Nauru', 
          'id' => 0 ), 
      'North Ndebele' => array (
          'code' => 'nd', 
          'name' => 'North Ndebele', 
          'id' => 0 ), 
      'Nepali' => array (
          'code' => 'ne', 
          'name' => 'Nepali', 
          'id' => '38' ), 
      'Ndonga' => array (
          'code' => 'ng', 
          'name' => 'Ndonga', 
          'id' => 0 ), 
      'Dutch' => array (
          'code' => 'nl', 
          'name' => 'Dutch', 
          'id' => '39' ), 
      'Norwegian Bokmål' => array (
          'code' => 'nb', 
          'name' => 'Norwegian', 
          'id' => 40 ), 
      'Norwegian Nynorsk' => array (
          'code' => 'nn', 
          'name' => 'Norwegian', 
          'id' => 40 ), 
      'South Ndebele' => array (
          'code' => 'nr', 
          'name' => 'South Ndebele', 
          'id' => 0 ), 
      'Navajo' => array (
          'code' => 'nv', 
          'name' => 'Navajo', 
          'id' => 0 ), 
      'Chichewa' => array (
          'code' => 'ny', 
          'name' => 'Chichewa', 
          'id' => 0 ), 
      'Occitan' => array (
          'code' => 'oc', 
          'name' => 'Occitan', 
          'id' => 0 ), 
      'Oromo' => array (
          'code' => 'om', 
          'name' => 'Oromo', 
          'id' => 0 ), 
      'Oriya' => array (
          'code' => 'or', 
          'name' => 'Oriya', 
          'id' => 0 ), 
      'Ossetian' => array (
          'code' => 'os', 
          'name' => 'Ossetian', 
          'id' => 0 ), 
      'Punjabi' => array (
          'code' => 'pa', 
          'name' => 'Punjabi', 
          'id' => 0 ), 
      'Pali' => array (
          'code' => 'pi', 
          'name' => 'Pali', 
          'id' => 0 ), 
      'Polish' => array (
          'code' => 'pl', 
          'name' => 'Polish', 
          'id' => '42' ), 
      'Pashto' => array (
          'code' => 'ps', 
          'name' => 'Pashto', 
          'id' => 0 ), 
      'Portuguese, Portugal' => array (
          'code' => 'pt-pt', 
          'name' => 'Portugal Portuguese', 
          'id' => 63 ), 
      'Portuguese, Brazil' => array (
          'code' => 'pt-br', 
          'name' => 'Portuguese', 
          'id' => 43 ), 
      'Quechua' => array (
          'code' => 'qu', 
          'name' => 'Quechua', 
          'id' => '44' ), 
      'Rhaeto-Romance' => array (
          'code' => 'rm', 
          'name' => 'Rhaeto-Romance', 
          'id' => 0 ), 
      'Kirundi' => array (
          'code' => 'rn', 
          'name' => 'Kirundi', 
          'id' => 0 ), 
      'Romanian' => array (
          'code' => 'ro', 
          'name' => 'Romanian', 
          'id' => '45' ), 
      'Russian' => array (
          'code' => 'ru', 
          'name' => 'Russian', 
          'id' => '46' ), 
      'Kinyarwanda' => array (
          'code' => 'rw', 
          'name' => 'Kinyarwanda', 
          'id' => 0 ), 
      'Sanskrit' => array (
          'code' => 'sa', 
          'name' => 'Sanskrit', 
          'id' => 0 ), 
      'Sardinian' => array (
          'code' => 'sc', 
          'name' => 'Sardinian', 
          'id' => 0 ), 
      'Sindhi' => array (
          'code' => 'sd', 
          'name' => 'Sindhi', 
          'id' => 0 ), 
      'Northern Sami' => array (
          'code' => 'se', 
          'name' => 'Northern Sami', 
          'id' => 0 ), 
      'Sango' => array (
          'code' => 'sg', 
          'name' => 'Sango', 
          'id' => 0 ), 
      'Serbo-Croatian' => array (
          'code' => 'sh', 
          'name' => 'Serbo-Croatian', 
          'id' => 0 ), 
      'Singhalese' => array (
          'code' => 'si', 
          'name' => 'Singhalese', 
          'id' => 0 ), 
      'Slovak' => array (
          'code' => 'sk', 
          'name' => 'Slovak', 
          'id' => 0 ), 
      'Slovenian' => array (
          'code' => 'sl', 
          'name' => 'Slovenian', 
          'id' => '47' ), 
      'Samoan' => array (
          'code' => 'sm', 
          'name' => 'Samoan', 
          'id' => 0 ), 
      'Shona' => array (
          'code' => 'sn', 
          'name' => 'Shona', 
          'id' => 0 ), 
      'Somali' => array (
          'code' => 'so', 
          'name' => 'Somali', 
          'id' => '48' ), 
      'Albanian' => array (
          'code' => 'sq', 
          'name' => 'Albanian', 
          'id' => '49' ), 
      'Serbian' => array (
          'code' => 'sr', 
          'name' => 'Serbian', 
          'id' => '50' ), 
      'Siswati' => array (
          'code' => 'ss', 
          'name' => 'Siswati', 
          'id' => 0 ), 
      'Sesotho' => array (
          'code' => 'st', 
          'name' => 'Sesotho', 
          'id' => 0 ), 
      'Sudanese' => array (
          'code' => 'su', 
          'name' => 'Sudanese', 
          'id' => 0 ), 
      'Swedish' => array (
          'code' => 'sv', 
          'name' => 'Swedish', 
          'id' => '51' ), 
      'Swahili' => array (
          'code' => 'sw', 
          'name' => 'Swahili', 
          'id' => 0 ), 
      'Tamil' => array (
          'code' => 'ta', 
          'name' => 'Tamil', 
          'id' => '52' ), 
      'Telugu' => array (
          'code' => 'te', 
          'name' => 'Telugu', 
          'id' => 0 ), 
      'Tajik' => array (
          'code' => 'tg', 
          'name' => 'Tajik', 
          'id' => 0 ), 
      'Thai' => array (
          'code' => 'th', 
          'name' => 'Thai', 
          'id' => '53' ), 
      'Tigrinya' => array (
          'code' => 'ti', 
          'name' => 'Tigrinya', 
          'id' => 0 ), 
      'Turkmen' => array (
          'code' => 'tk', 
          'name' => 'Turkmen', 
          'id' => 0 ), 
      'Tagalog' => array (
          'code' => 'tl', 
          'name' => 'Tagalog', 
          'id' => 0 ), 
      'Setswana' => array (
          'code' => 'tn', 
          'name' => 'Setswana', 
          'id' => 0 ), 
      'Tonga' => array (
          'code' => 'to', 
          'name' => 'Tonga', 
          'id' => 0 ), 
      'Turkish' => array (
          'code' => 'tr', 
          'name' => 'Turkish', 
          'id' => '54' ), 
      'Tsonga' => array (
          'code' => 'ts', 
          'name' => 'Tsonga', 
          'id' => 0 ), 
      'Tatar' => array (
          'code' => 'tt', 
          'name' => 'Tatar', 
          'id' => 0 ), 
      'Twi' => array (
          'code' => 'tw', 
          'name' => 'Twi', 
          'id' => 0 ), 
      'Tahitian' => array (
          'code' => 'ty', 
          'name' => 'Tahitian', 
          'id' => 0 ), 
      'Uighur' => array (
          'code' => 'ug', 
          'name' => 'Uighur', 
          'id' => 0 ), 
      'Ukrainian' => array (
          'code' => 'uk', 
          'name' => 'Ukrainian', 
          'id' => '55' ), 
      'Urdu' => array (
          'code' => 'ur', 
          'name' => 'Urdu', 
          'id' => '56' ), 
      'Uzbek' => array (
          'code' => 'uz', 
          'name' => 'Uzbek', 
          'id' => '57' ), 
      'Venda' => array (
          'code' => 've', 
          'name' => 'Venda', 
          'id' => 0 ), 
      'Vietnamese' => array (
          'code' => 'vi', 
          'name' => 'Vietnamese', 
          'id' => '58' ), 
      'Wolof' => array (
          'code' => 'wo', 
          'name' => 'Wolof', 
          'id' => 0 ), 
      'Xhosa' => array (
          'code' => 'xh', 
          'name' => 'Xhosa', 
          'id' => 0 ), 
      'Yiddish' => array (
          'code' => 'yi', 
          'name' => 'Yiddish', 
          'id' => '59' ), 
      'Yoruba' => array (
          'code' => 'yo', 
          'name' => 'Yoruba', 
          'id' => 0 ), 
      'Zhuang' => array (
          'code' => 'za', 
          'name' => 'Zhuang', 
          'id' => 0 ), 
      'Chinese, Simplified' => array (
          'code' => 'zh-hans', 
          'name' => 'Chinese (Simplified)', 
          'id' => '60' ), 
      'Chinese, Traditional' => array (
          'code' => 'zh-hant', 
          'name' => 'Chinese (Traditional)', 
          'id' => '62' ), 
      'Zulu' => array (
          'code' => 'zu', 
          'name' => 'Zulu', 
          'id' => '61' ) );
}

function icl_core_initialize_languages() {
  
  $icl_langs = _icl_core_get_all_languages();
  
  foreach ($icl_langs as $drupal_lang => $lang) {
    db_query("INSERT INTO {icl_languages} (code, icl_name, icl_id) VALUES ('%s', '%s', '%d')", $lang['code'], $lang['name'], $lang['id']);
  }
}

function icl_core_get_icl_support() {
  if (variable_get ('icl_core_setup_wizard_complete', FALSE) == TRUE) {
    return sprintf( t("For help with your site's translation, use the %ssupport center%s"), icl_create_icl_popup_link('/support', 'support center') , '</a>');
  } else {
    return sprintf( t("For help with your site's translation, use the %ssupport center%s"), icl_create_icl_popup_link('/site/about-us/contact-us/', 'Contact ICanLocalize') , '</a>');
  }
}

function icl_core_get_support_help() {    
  global $base_url;

  $wid = variable_get ( 'icl_core_website_id', 0 );
  $icl_core_languages = variable_get('icl_core_languages', array());
  $support_message = t( 'To see the status of pending translations or to cancel translation requests, go to the !link in ICanLocalize', array('!link' => icl_create_icl_popup_link('/websites/'. $wid ) . t('project page') . '</a>'));
  $question_image = $base_url . '/' . drupal_get_path('module', 'icl_content') . '/images/question1.png';
  $doc_image = $base_url . '/' . drupal_get_path('module', 'icl_content') . '/images/documents.png';
  $dollar_image = $base_url . '/' . drupal_get_path('module', 'icl_content') . '/images/dollar1.png';
  if (!isset($icl_core_languages['balance'])) {
    $icl_core_languages['balance'] = '0';
  }
  $finance_message = t('Your balance with ICanLocalize is $!balance. Visit your !finance page to deposit additional funds.', array('!balance' => $icl_core_languages['balance'], '!finance' => icl_create_icl_popup_link(ICL_FINANCE_LINK) . 'ICanLocalize finance</a>'));
  
  if ($wid > 0) {
    $icl_support = '<img src="' . $dollar_image . '"> ' . $finance_message;
    $icl_support .= '<br /><br />'. '<img src="' . $question_image . '"> ' . icl_core_get_icl_support();
    $icl_support .= '<br /><br /><img src="' . $doc_image . '"> ' . $support_message;
  } else {
    $icl_support = '<img src="' . $question_image . '"> ' . icl_core_get_icl_support();
  }
  
  return $icl_support;
}

/**
 *
 * check to see if the url on the site is the same as stored on ICanLocalize
 *
 * @return a message
 */


function icl_core_is_icl_stored_url_ok($platform_info) {
  global $base_url;
  if (!isset($platform_info['url'])) {
    // We are not setup for ICL translation.
    return TRUE;
  }
  if ( $base_url == $platform_info['url'] ) {
    return TRUE;
  } else {
    // see if we should ignore this one.
    $icl_url_ignore = variable_get('icl_current_url_ignore', "");
    $ignore_md5 = md5($base_url . $platform_info['url']);
    return $ignore_md5 == $icl_url_ignore;
  }
}

function icl_core_get_url_changed_message(&$form_item, $platform_info) {
  global $base_url;
  
  $message = t("We’ve detected a change in your site’s URL. <br />Before: <b>@before</b><br />Now: <b>@now</b>", array('@before' => $platform_info['url'], '@now' => $base_url));
  $message .= '<br />';
  $message .= t("If this change is permanent, we need to update the site’s address in ICanLocalize. All translation will be sent to the new address.");
  $message .= '<br />';

  $form_item ['#value'] = $message;
  
  $form_item ['icl_update_url'] = array(
        '#type' => 'submit',
        '#value' => t ( 'Update now' ),
        '#submit' => array('icl_core_update_url_submit'),
        '#validate' => array('icl_core_update_url_validate'),
  );

  $form_item ['icl_ignore_url'] = array(
        '#type' => 'submit', 
        '#value' => t ( 'Ignore' ),
        '#submit' => array('icl_core_ignore_url_submit'),
        '#validate' => array('icl_core_update_url_validate'),
  );
  
  $form_item ['icl_old_url'] = array(
        '#type' => 'hidden',
        '#value' => $platform_info['url'],
        );
    
  
}

function icl_core_update_url_validate($form, &$form_state) {
  // do nothing.
}

function icl_core_update_url_submit($form, &$form_state) {
  global $base_url;
  $accesskey = variable_get ( 'icl_core_accesskey', 0 );
  $wid = variable_get ( 'icl_core_website_id', 0 );
  
  icl_core_update_url_by_cms($accesskey, $wid, $base_url);

  variable_set('icl_current_url_ignore', '');

  _icl_wrapper_drupal_goto($_GET['q'], 'icl_refresh_langs=1');
}

function icl_core_ignore_url_submit($form, &$form_state) {
  global $base_url;
  
  $icl_url_ignore = md5($base_url.$form['icl_url_changed']['icl_old_url']['#value']);
  variable_set('icl_current_url_ignore', $icl_url_ignore);
  _icl_wrapper_drupal_goto($_GET['q']);
}
