You are here

globallink_settings.inc in GlobalLink Connect for Drupal 7.7

Same filename and directory in other branches
  1. 7.5 globallink_settings.inc
  2. 7.6 globallink_settings.inc

File

globallink_settings.inc
View source
<?php

/**
 * @file
 */

/**
 * Returns form for globallink_pd_settings page.
 */

/**
 *
 */
function globallink_settings_page() {
  $array = array();
  $array[] = drupal_get_form('globallink_pd_settings');
  $array[] = drupal_get_form('globallink_adaptor_settings');
  $array[] = drupal_get_form('globallink_useful_tools');
  return $array;
}

/**
 * Renders form for globallink_pd_settings.
 */
function globallink_pd_settings() {
  $module_path = drupal_get_path('module', 'globallink');
  drupal_add_css($module_path . '/css/globallink.css');
  $form = array();
  $variables = array(
    'path' => $module_path . '/css/anchor.png',
    'title' => 'PD Link',
    'attributes' => array(),
  );
  $img = theme_image($variables);
  $form['globallink_pd_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('GlobalLink Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['globallink_pd_settings']['globallink_pd_url'] = array(
    '#type' => 'textfield',
    '#title' => t('URL'),
    '#default_value' => variable_get('globallink_pd_url', ''),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['globallink_pd_link'] = array(
    '#markup' => l($img, variable_get('globallink_pd_url', ''), array(
      'attributes' => array(
        'target' => '_blank',
        'class' => array(
          'globallink_pd_link',
        ),
      ),
      'html' => TRUE,
    )),
  );
  $form['globallink_pd_settings']['globallink_pd_username'] = array(
    '#type' => 'textfield',
    '#title' => t('User Id'),
    '#default_value' => variable_get('globallink_pd_username', ''),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['globallink_pd_password'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['globallink_pd_projectid'] = array(
    '#type' => 'textfield',
    '#title' => t('Project Short Code(s)'),
    '#description' => t('Enter comma separated codes for multiple projects.'),
    '#default_value' => variable_get('globallink_pd_projectid', ''),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['globallink_pd_submissionprefix'] = array(
    '#type' => 'textfield',
    '#title' => t('Submission Name Prefix'),
    '#default_value' => variable_get('globallink_pd_submissionprefix', 'DRU_'),
    '#required' => FALSE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['globallink_pd_classifier'] = array(
    '#type' => 'textfield',
    '#title' => t('Classifier'),
    '#default_value' => variable_get('globallink_pd_classifier', 'XML'),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['globallink_pd_max_target'] = array(
    '#type' => 'textfield',
    '#title' => t('Max Target Count'),
    '#default_value' => variable_get('globallink_pd_max_target', '99999'),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['globallink_batch'] = array(
    '#type' => 'textfield',
    '#title' => t('Max documents before new submission'),
    '#default_value' => variable_get('globallink_batch', 4999),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['globallink_unique_identifier'] = array(
    '#type' => 'textfield',
    '#title' => t('Unique Instance Identifier'),
    '#default_value' => variable_get('globallink_unique_identifier', $_SERVER['SERVER_NAME']),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_pd_settings']['submit_pd_test'] = array(
    '#type' => 'submit',
    '#value' => t('Save and Test Settings'),
    '#suffix' => '</div>',
  );
  return $form;
}

/**
 * Handles validation of globallink_pd_settings form.
 */
function globallink_pd_settings_validate(&$form, &$form_state) {
  module_load_include('inc', 'globallink', 'gl_ws/gl_ws_common');
  $project_short_code_char_arr = str_split(str_replace(' ', '', $form_state['values']['globallink_pd_projectid']));
  foreach ($project_short_code_char_arr as $val) {
    if (!preg_match('/[a-zA-Z0-9\\,_]/', $val)) {
      form_set_error('', t('Only enter comma seperated GlobalLink Project Short Code.'));
      return FALSE;
    }
    if ($val === strtolower($val) && !is_numeric($val) && $val != ',' && $val != '_' && $val != '') {
      form_set_error('', t('GlobalLink Project Short Code is in lowercase.'));
      return FALSE;
    }
  }
  $project_short_code_arr = explode(',', str_replace(' ', '', $form_state['values']['globallink_pd_projectid']));
  foreach ($project_short_code_arr as $val) {
    if (count(array_keys($project_short_code_arr, $val)) > 1) {
      form_set_error('', t('GlobalLink Project Short Code has duplicates.'));
      return FALSE;
    }
  }
  $value = $form_state['values']['globallink_pd_max_target'];
  if (!is_numeric($value)) {
    form_set_error('globallink_pd_max_target', t('Max Target Count is not a number.'));
    return FALSE;
  }
  elseif ($value < 1) {
    form_set_error('globallink_pd_max_target', t('Max Target Count should be greater than 1.'));
    return FALSE;
  }
  $max_batch = $form_state['values']['globallink_batch'];
  if (!is_numeric($max_batch)) {
    form_set_error('globallink_batch', t('Max documents before submission is not a number'));
    return FALSE;
  }
  elseif ($max_batch < 1) {
    form_set_error('globallink_batch', t('Max documents before submission should be greater than 1'));
    return FALSE;
  }
  $prefix_len = strlen($form_state['values']['globallink_pd_submissionprefix']);
  if ($prefix_len > 118) {
    form_set_error('globallink_pd_max_target', t('Submission Name cannot be longer than 118 characters. Currently ' . $prefix_len . ' characters long.'));
    return FALSE;
  }
  if (isset($form_state['values']['globallink_pd_password']) && $form_state['values']['globallink_pd_password'] != '') {
    try {
      $pd_obj = new ProjectDirector();
      $url = strrev($form_state['values']['globallink_pd_url']);
      if (ord($url) == 47) {
        $url = substr($url, 1);
      }
      $r_url = strrev($url);
      $pd_obj->url = $r_url;
      $pd_obj->username = $form_state['values']['globallink_pd_username'];
      $pd_obj->password = $form_state['values']['globallink_pd_password'];
      $pd_obj->projectShortCode = $form_state['values']['globallink_pd_projectid'];
      $pd_obj->submissionPrefix = $form_state['values']['globallink_pd_submissionprefix'];
      $pd_obj->classifier = $form_state['values']['globallink_pd_classifier'];
      $pd_obj->maxTargetCount = $form_state['values']['globallink_pd_max_target'];
      $pd_obj->userAgent = $form_state['values']['globallink_unique_identifier'];
      $success = globallink_test_pd_connectivity($pd_obj);
      if (!is_bool($success)) {
        form_set_error('', t($success));
      }
    } catch (SoapFault $se) {
      watchdog(GLOBALLINK_MODULE, 'SOAP Exception - %function - Code[%faultcode], Message[%faultstring]', array(
        '%function' => __FUNCTION__,
        '%faultcode' => $se->faultcode,
        '%faultstring' => $se->faultstring,
      ), WATCHDOG_ERROR);
      form_set_error('', t('Web Services Error: @faultcode - @faultstring', array(
        '@faultcode' => $se->faultcode,
        '@faultstring' => $se->faultstring,
      )));
    } catch (Exception $e) {
      watchdog(GLOBALLINK_MODULE, 'Exception - %function - File[%file], Line[%line], Code[%code], Message[%message]', array(
        '%function' => __FUNCTION__,
        '%file' => $e
          ->getFile(),
        '%line' => $e
          ->getLine(),
        '%code' => $e
          ->getCode(),
        '%message' => $e
          ->getMessage(),
      ), WATCHDOG_ERROR);
      form_set_error('', t('Error: @message', array(
        '@message' => $e
          ->getMessage(),
      )));
    }
  }
}

/**
 * Handles submission of globallink_pd_settings form.
 */
function globallink_pd_settings_submit($form, &$form_state) {
  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
  variable_set('globallink_cron_type', 1);
  switch ($op) {
    case t('Save PD Settings'):
      foreach ($form_state['values'] as $key => $value) {
        if (is_array($value) && isset($form_state['values']['array_filter'])) {
          $value = array_keys(array_filter($value));
        }
        variable_set($key, $value);
      }
      globallink_save_project_names();
      drupal_set_message(t('The configuration options have been saved.'));
      break;
    case t('Save and Test Settings'):
      try {
        foreach ($form_state['values'] as $key => $value) {
          if (is_array($value) && isset($form_state['values']['array_filter'])) {
            $value = array_keys(array_filter($value));
          }
          variable_set($key, $value);
        }
        globallink_save_project_names();
        drupal_set_message(t('Settings Saved and Connection Test Successful.'));
      } catch (SoapFault $se) {
        watchdog(GLOBALLINK_MODULE, 'SOAP Exception - %function - Code[%faultcode], Message[%faultstring]', array(
          '%function' => __FUNCTION__,
          '%faultcode' => $se->faultcode,
          '%faultstring' => $se->faultstring,
        ), WATCHDOG_ERROR);
        form_set_error('', t('Web Services Error: @faultcode - @faultstring', array(
          '@faultcode' => $se->faultcode,
          '@faultstring' => $se->faultstring,
        )));
      } catch (Exception $e) {
        watchdog(GLOBALLINK_MODULE, 'Exception - %function - File[%file], Line[%line], Code[%code], Message[%message]', array(
          '%function' => __FUNCTION__,
          '%file' => $e
            ->getFile(),
          '%line' => $e
            ->getLine(),
          '%code' => $e
            ->getCode(),
          '%message' => $e
            ->getMessage(),
        ), WATCHDOG_ERROR);
        form_set_error('', t('Error: @message', array(
          '@message' => $e
            ->getMessage(),
        )));
      }
      break;
  }
}

/**
 * Renders form for globallink_adaptor_settings.
 */
function globallink_adaptor_settings() {
  $form = array();
  $form['globallink_adaptor_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Adaptor Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['globallink_adaptor_settings']['globallink_pager_limit'] = array(
    '#type' => 'textfield',
    '#title' => t('Dashboard Pager Limit'),
    '#default_value' => variable_get('globallink_pager_limit', 10),
    '#required' => TRUE,
    '#size' => 50,
  );
  $form['globallink_adaptor_settings']['globallink_enable_preview'] = array(
    '#type' => 'radios',
    '#title' => t('Enable Preview For Receive Translations'),
    '#default_value' => variable_get('globallink_enable_preview', 1),
    '#options' => array(
      t('No'),
      t('Yes'),
    ),
  );
  $form['globallink_adaptor_settings']['globallink_publish_node'] = array(
    '#type' => 'radios',
    '#title' => t('Publish Translated Content'),
    '#default_value' => variable_get('globallink_publish_node', 0),
    '#options' => array(
      t('No'),
      t('Yes'),
      t('Use Source Content Setting'),
    ),
  );
  $form['globallink_adaptor_settings']['globallink_cron_type'] = array(
    '#type' => 'radios',
    '#title' => t('Automatic Update Status'),
    '#default_value' => variable_get('globallink_cron_type', 0),
    '#options' => array(
      t('Disabled'),
      t('Drupal Cron'),
    ),
  );
  $form['globallink_adaptor_settings']['globallink_proxy_url'] = array(
    '#type' => 'textfield',
    '#title' => t('Proxy URL'),
    '#default_value' => variable_get('globallink_proxy_url', ''),
    '#required' => FALSE,
    '#size' => 50,
  );
  $form['globallink_adaptor_settings']['globallink_entity_create_revisions'] = array(
    '#type' => 'radios',
    '#title' => t('Create Revisions for Entities'),
    '#default_value' => variable_get('globallink_entity_create_revisions', 0),
    '#options' => array(
      t('No'),
      t('Yes'),
    ),
  );
  $form['globallink_adaptor_settings']['globallink_enable_debug'] = array(
    '#type' => 'radios',
    '#title' => t('Enable Debug Mode'),
    '#default_value' => variable_get('globallink_enable_debug', 0),
    '#options' => array(
      t('No'),
      t('Yes'),
    ),
  );
  $entity_version = system_get_info('module', 'entity_translation');
  if ($entity_version['version'] == '7.x-1.0-beta5') {
    $form['globallink_adaptor_settings']['globallink_override_localize'] = array(
      '#type' => 'radios',
      '#title' => t('Override Localize with Translate for Taxonomy'),
      '#default_value' => variable_get('globallink_override_localize', 0),
      '#options' => array(
        t('No'),
        t('Yes'),
      ),
    );
  }
  $form['globallink_adaptor_settings']['submit_general_save'] = array(
    '#type' => 'submit',
    '#value' => t('Save Adaptor Settings'),
  );
  return $form;
}

/**
 * Exports log.
 */
function globallink_view_log_submit($form, &$form_state) {
  $from_date = $form_state['input']['log_view_date'];
  $from_date = globallink_convert_date_to_timestamp($from_date) / 1000;
  $destination = 'temporary://' . 'globallink_log.html';
  $my_file_obj = file_unmanaged_save_data(globallink_get_log_data($from_date), $destination, FILE_EXISTS_REPLACE);
  file_transfer($my_file_obj, array(
    'Content-Type' => 'application/htm',
    'Content-Disposition' => 'inline; filename="' . 'globallink_log.html' . '"',
    'Content-Length' => filesize($my_file_obj),
  ));
}

/**
 * Gets log data from specific date in the form of HTML.
 *
 * @param string $from_date
 *   The timestamp.
 *
 * @return string
 *   HTML representation of log data.
 */
function globallink_get_log_data($from_date) {
  $html = '<html><head><title>GlobalLink Log</title><style>.datagrid table { border-collapse: collapse; text-align: left; width: 100%; } .datagrid {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #006699; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; }.datagrid table td, .datagrid table th { padding: 3px 10px; }.datagrid table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #006699), color-stop(1, #00557F) );background:-moz-linear-gradient( center top, #006699 5%, #00557F 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#006699", endColorstr="#00557F");background-color:#006699; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #0070A8; } .datagrid table thead th:first-child { border: none; }.datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4;font-size: 12px;font-weight: normal; }.datagrid table tbody .alt td { background: #E1EEF4; color: #00496B; }.datagrid table tbody td:first-child { border-left: none; }.datagrid table tbody tr:last-child td { border-bottom: none; }</style></head><body>';
  $result = db_select('globallink_log', 'tl')
    ->fields('tl')
    ->condition('timestamp', $from_date, '>=')
    ->execute();
  $html .= '<div class="datagrid"><table>';
  $html .= '<thead><tr><th>Date Time</th><th>Log Severity</th><th>Type</th><th>Message</th></tr></thead><tbody>';
  $i = 0;
  foreach ($result as $row) {
    $date = format_date($row->timestamp, 'custom', 'Y-m-d H:i:s');
    $mod = $i % 2;
    if ($mod == 0) {
      $html .= '<tr><td style="width:10%;">' . $date . '</td><td style="width:10%;">' . $row->severity . '</td><td style="width:10%;">' . $row->type . '</td><td style="width:70%; text-style:justify;">' . $row->message . '</td></tr>';
    }
    else {
      $html .= '<tr class="alt"><td style="width:10%;">' . $date . '</td><td style="width:10%;">' . $row->severity . '</td><td style="width:10%;">' . $row->type . '</td><td style="width:70%; text-style:justify;">' . $row->message . '</td></tr>';
    }
    $i++;
  }
  $html .= '</tbody></table></div>';
  $html .= '</body></html>';
  return $html;
}

/**
 * Validates adaptor settings.
 */
function globallink_adaptor_settings_validate($form, &$form_state) {
  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
  if ($op == t('Save Adaptor Settings')) {
    $value = $form_state['values']['globallink_pager_limit'];
    if (!is_numeric($value)) {
      form_set_error('globallink_pager_limit', t('Dahsboard Pager Limit is not a number.'));
    }
    elseif ($value < 1) {
      form_set_error('globallink_pager_limit', t('Dahsboard Pager Limit should be greater than 1.'));
    }
  }
}

/**
 * Submits adaptor settings.
 */
function globallink_adaptor_settings_submit($form, &$form_state) {
  $old_preview = variable_get('globallink_enable_preview', 1);
  $op = isset($form_state['values']['op']) ? $form_state['values']['op'] : '';
  if ($op == t('Save Adaptor Settings')) {
    foreach ($form_state['values'] as $key => $value) {
      if (is_array($value) && isset($form_state['values']['array_filter'])) {
        $value = array_keys(array_filter($value));
      }
      variable_set($key, $value);
    }
    $pvalue = $form_state['values']['globallink_enable_preview'];
    if ($pvalue != $old_preview) {
      $_SESSION['globallink_globalLink_arr'] = array();
      unset($_SESSION['globallink_globalLink_arr_last_refreshed']);
    }
  }
  drupal_set_message(t('The configuration options have been saved.'));
}

/**
 * Gets project director details.
 *
 * @return object
 *   The project director object.
 */
function globallink_get_project_director_details() {
  $pd4 = new ProjectDirector();
  $url = strrev(variable_get('globallink_pd_url', ''));
  if (ord($url) == 47) {
    $url = substr($url, 1);
  }
  $r_url = strrev($url);
  $pd4->url = $r_url;
  $pd4->username = variable_get('globallink_pd_username', '');
  $pd4->password = variable_get('globallink_pd_password', '');
  $pd4->projectShortCode = variable_get('globallink_pd_projectid', '');
  $pd4->submissionPrefix = variable_get('globallink_pd_submissionprefix', '');
  $pd4->classifier = variable_get('globallink_pd_classifier', 'XML');
  $pd4->maxTargetCount = variable_get('globallink_pd_max_target', '99999');
  $pd4->userAgent = variable_get('globallink_unique_identifier', $_SERVER['SERVER_NAME']);
  return $pd4;
}

/**
 * Saves project names.
 */
function globallink_save_project_names() {
  $pd4 = globallink_get_project_director_details();
  $projects_arr = globallink_get_user_pd_projects($pd4);
  $project_short_code = $pd4->projectShortCode;
  $var_arr = array();
  if ($project_short_code != '') {
    $proj_code_arr = explode(',', $project_short_code);
    foreach ($proj_code_arr as $proj_code) {
      if (isset($projects_arr[$proj_code])) {
        $var_arr[$proj_code] = $projects_arr[$proj_code];
      }
    }
  }
  variable_set('globallink_pd_projects', $var_arr);
}

/**
 * Validates project director details.
 *
 * @param object $pd4
 *   The project director object.
 *
 * @return bool
 *   TRUE if the project director details are valid.  FALSE otherwise.
 */
function globallink_validate_project_director_details($pd4) {
  if (empty($pd4->url)) {
    form_set_error('', t('GlobalLink URL is undefined.'));
    return FALSE;
  }
  elseif (empty($pd4->username)) {
    form_set_error('', t('GlobalLink User Id is undefined.'));
    return FALSE;
  }
  elseif (empty($pd4->password)) {
    form_set_error('', t('GlobalLink Password is undefined.'));
    return FALSE;
  }
  elseif (empty($pd4->projectShortCode)) {
    form_set_error('', t('GlobalLink Project Code is undefined.'));
    return FALSE;
  }
  elseif (empty($pd4->classifier)) {
    form_set_error('', t('GlobalLink Classifier is undefined.'));
    return FALSE;
  }
  elseif (empty($pd4->maxTargetCount)) {
    form_set_error('', t('GlobalLink Max Target Count is undefined.'));
    return FALSE;
  }
  elseif (!is_numeric($pd4->maxTargetCount)) {
    form_set_error('', t('GlobalLink Max Target Count is not a number.'));
    return FALSE;
  }
  return TRUE;
}

/**
 * Wraps globallink_convert_date_to_timestamp.
 *
 * @param string $from_date
 *   The desired log date.
 */
function globallink_view_log($from_date) {
  $from_date = globallink_convert_date_to_timestamp($from_date);
}

/**
 * Globallink Useful Tools form.
 */
function globallink_useful_tools() {
  $form = array();
  $form['globallink_useful_tools'] = array(
    '#type' => 'fieldset',
    '#title' => t('Useful Tools'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['globallink_useful_tools']['export_csv'] = array(
    '#markup' => '<label for="export_csv_button">Export GlobalLink tables to CSV</label><div>Exports the data from the GlobalLink tables to a CSV and makes it available for download. Use this utility whenever you need to debug under the hood.</div>',
  );
  $form['globallink_useful_tools']['export_csv_button'] = array(
    '#type' => 'submit',
    '#value' => t('Export'),
    '#submit' => array(
      'export_csv_button_submit',
    ),
    '#name' => 'submit_export',
    '#attributes' => array(
      'onclick' => 'if (!confirm("RUNNING TOOL: Export CSV. Confirm this operation.")){return false;}',
    ),
  );
  $form['globallink_useful_tools']['prepare_nodes'] = array(
    '#markup' => '<label for="prepare_nodes_button">Prepare Nodes</label><div>Sets all language neutral nodes and underlying fields and path aliases to this site\'s source locale.</div>',
  );
  $form['globallink_useful_tools']['prepare_nodes_button'] = array(
    '#type' => 'submit',
    '#value' => t('Run Tool'),
    '#name' => 'submit_nodes',
    '#submit' => array(
      'prepare_nodes_button_submit',
    ),
    '#attributes' => array(
      'onclick' => 'if (!confirm("RUNNING TOOL: Prepare Nodes. This action is irreversible. Confirm this operation.")){return false;}',
    ),
  );
  $form['globallink_useful_tools']['prepare_blocks'] = array(
    '#markup' => '<label for="prepare_blocks_button">Prepare Blocks</label><div>Updates all blocks to be translatable in the Language Settings.</div>',
  );
  $form['globallink_useful_tools']['prepare_blocks_button'] = array(
    '#type' => 'submit',
    '#value' => t('Run Tool'),
    '#name' => 'submit_blocks',
    '#submit' => array(
      'prepare_blocks_button_submit',
    ),
    '#attributes' => array(
      'onclick' => 'if (!confirm("RUNNING TOOL: Prepare Blocks. This action is irreversible. Confirm this operation.")){return false;}',
    ),
  );
  $form['globallink_useful_tools']['prepare_taxonomy'] = array(
    '#markup' => '<label for="prepare_taxonomy_button">Prepare Taxonomy</label><div>Updates all taxonomy vocabularies that are currently not enabled for multilingual, to use a translation mode from the Multilingual Options available.</div>',
  );
  $form['globallink_useful_tools']['prepare_taxonomy_button'] = array(
    '#type' => 'submit',
    '#value' => t('Run Tool'),
    '#name' => 'submit_taxonomy',
    '#submit' => array(
      'prepare_taxonomy_custom_submit_redirect',
    ),
    '#attributes' => array(
      'onclick' => 'if (!confirm("You can select the Multilingual option to be used for all taxonomies.")){return false;}',
    ),
  );
  $form['globallink_useful_tools']['prepare_menus'] = array(
    '#markup' => '<label for="prepare_menus_button">Prepare Menus</label><div>Updates all Menus to use the \'Translate and Localize\' Multilingual option, and updates the language of all menu links to the site\'s source locale.</div>',
  );
  $form['globallink_useful_tools']['prepare_menus_button'] = array(
    '#type' => 'submit',
    '#value' => t('Run Tool'),
    '#name' => 'submit_menus',
    '#submit' => array(
      'prepare_menus_button_submit',
    ),
    '#attributes' => array(
      'onclick' => 'if (!confirm("RUNNING TOOL: Prepare Menus. This action is irreversible. Confirm this operation.")){return false;}',
    ),
  );
  $form['globallink_useful_tools']['prepare_field_collections'] = array(
    '#markup' => '<label for="prepare_field_collections_button">Prepare Field Collections</label><div>Sets all Field Collections to be translatable, allowing all the underlying fields to be enabled for multilingual use.</div>',
  );
  $form['globallink_useful_tools']['prepare_field_collections_button'] = array(
    '#type' => 'submit',
    '#value' => t('Run Tool'),
    '#name' => 'submit_field_collections',
    '#submit' => array(
      'prepare_field_collections_button_submit',
    ),
    '#attributes' => array(
      'onclick' => 'if (!confirm("RUNNING TOOL: Prepare Field Collections. This action is irreversible. Confirm this operation.")){return false;}',
    ),
  );
  $form['globallink_useful_tools']['prepare_beans'] = array(
    '#markup' => '<label for="prepare_beans_button">Prepare Beans</label><div>Sets all bean fields to be translatable and will set language of the bean field data to site source language</div>',
  );
  $form['globallink_useful_tools']['prepare_beans_button'] = array(
    '#type' => 'submit',
    '#value' => t('Run Tool'),
    '#name' => 'submit_beans',
    '#submit' => array(
      'prepare_beans_button_submit',
    ),
    '#attributes' => array(
      'onclick' => 'if (!confirm("RUNNING TOOL: Prepare Beans. This action is irreversible. Confirm this operation.")){return false;}',
    ),
  );
  return $form;
}

/**
 * Block batch sets .
 */
function prepare_blocks_button_submit($form, &$form_state) {
  $batch = array(
    'operations' => array(),
    'finished' => 'globallink_settings_blocks_batch_finished',
    'title' => t('Updating Blocks'),
    'init_message' => t('Update blocks is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Update blocks has encountered an error.'),
    'file' => drupal_get_path('module', 'globallink') . '/globallink_settings.inc',
  );
  $progress = 0;
  $limit = 5;
  $result = db_query("SELECT * FROM {block} WHERE  i18n_mode = :i18n_mode", array(
    ':i18n_mode' => 0,
  ))
    ->fetchAll();
  $max = count($result);
  while ($progress <= $max) {
    $batch['operations'][] = array(
      'globallink_settings_blocks_process',
      array(
        $progress,
        $limit,
        $result,
      ),
    );
    $progress = $progress + $limit;
  }
  batch_set($batch);
}

/**
 * Block batch process start  .
 */
function globallink_settings_blocks_process($progress, $limit, $result, &$context) {
  foreach ($result as $key => $value) {
    $update = db_query("UPDATE {block} SET i18n_mode = :i18n_mode WHERE bid = :bid", array(
      ':bid' => $value->bid,
      ':i18n_mode' => 1,
    ));
    $block_arr = array(
      'module' => $value->module,
      'delta' => $value->delta,
      'title' => $value->title,
    );
    i18n_block_update_strings($block_arr, 1);
  }
  $progress = $progress + $limit;
  $context['message'] = 'Now processing ' . $progress . ' - ' . $context['results'][0] . ' Updated';
}

/**
 * Blocks batch process finishe.
 */
function globallink_settings_blocks_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('Updated settings of all blocks to be translatable successfully.');
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ));
    drupal_set_message($message, 'error');
  }
}

/**
 * Menu batch sets .
 */
function prepare_menus_button_submit($form, &$form_state) {
  $batch = array(
    'operations' => array(),
    'finished' => 'globallink_settings_menus_batch_finished',
    'title' => t('Updating Menus'),
    'init_message' => t('Update Menus is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Update Menus has encountered an error.'),
    'file' => drupal_get_path('module', 'globallink') . '/globallink_settings.inc',
  );
  $progress = 0;
  $limit = 200;
  $result = db_query("SELECT * FROM {menu_custom}")
    ->fetchAll();
  $resultLinks = db_query("SELECT * FROM {menu_links}")
    ->fetchAll();
  if ($result > $resultLinks) {
    $totalResult = $result;
  }
  else {
    $totalResult = $resultLinks;
  }
  $max = count($totalResult);
  while ($progress <= $max) {
    $batch['operations'][] = array(
      'globallink_settings_menus_process_batch1',
      array(
        $progress,
        $limit,
        $result,
        $resultLinks,
      ),
    );
    $progress = $progress + $limit;
  }
  batch_set($batch);
}

/**
 * Menu batch process start.
 */
function globallink_settings_menus_process_batch1($progress, $limit, $result, $resultLinks, &$context) {
  foreach ($result as $key => $value) {
    $update = db_query("UPDATE {menu_custom} SET i18n_mode = :i18n_mode WHERE  menu_name = :menu_name", array(
      ':menu_name' => $value->menu_name,
      ':i18n_mode' => 5,
    ));
  }
  foreach ($resultLinks as $key => $value) {
    $updateLinks = db_query("UPDATE {menu_links} SET language = :language WHERE  menu_name = :menu_name", array(
      ':menu_name' => $value->menu_name,
      ':language' => "en",
    ));
  }
  $progress = $progress + $limit;
  $context['message'] = 'Now processing ' . $progress . ' - ' . $context['results'][0] . ' Updated';
}

/**
 * Menu batch process finish.
 */
function globallink_settings_menus_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('Updated all menu links to use the site\'s source locale and Menus to use Translate and Localize option successfully.');
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ));
    drupal_set_message($message, 'error');
  }
}

/**
 * Export csv batch set.
 */
function export_csv_button_submit($form, &$form_state) {
  $db_tables = array(
    'globallink_core',
    'globallink_core_block',
    'globallink_core_entity',
    'globallink_core_fieldable_panels',
    'globallink_core_interface',
    'globallink_core_menu',
    'globallink_core_taxonomy',
    'globallink_core_webform',
    'globallink_field_config',
    'globallink_locale',
  );
  $batch = array(
    'operations' => array(),
    'finished' => 'globallink_settings_export_batch_finished',
    'title' => t('Export Csv'),
    'init_message' => t('Export Csv is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Export Csv has encountered an error.'),
    'file' => drupal_get_path('module', 'globallink') . '/globallink_settings.inc',
  );
  $progress = 0;
  $limit = 10;
  $resultCore = db_query("SELECT * FROM {globallink_core}")
    ->fetchAll();
  $resultSubmission = db_query("SELECT * FROM {globallink_submission}")
    ->fetchAll();
  $resultDocument = db_query("SELECT * FROM {globallink_document}")
    ->fetchAll();
  $resultFieldConfig = db_query("SELECT * FROM {globallink_field_config}")
    ->fetchAll();
  $resultLocale = db_query("SELECT * FROM {globallink_locale}")
    ->fetchAll();
  $countArray = array(
    count($resultCore),
    count($resultSubmission),
    count($resultDocument),
    count($resultFieldConfig),
    count($resultLocale),
  );
  $resultArray = array(
    'resultCore' => $resultCore,
    'resultCoreSubmission' => $resultSubmission,
    'resultCoreDocument' => $resultDocument,
    'resultFieldConfig' => $resultFieldConfig,
    'resultLocale' => $resultLocale,
  );
  $max = max($countArray);
  while ($progress <= $max) {
    $batch['operations'][] = array(
      'globallink_settings_export_process',
      array(
        $progress,
        $limit,
        $resultArray,
      ),
    );
    $progress = $progress + $limit;
  }
  batch_set($batch);
}

/**
 * Export csv batch process start.
 */
function globallink_settings_export_process($progress, $limit, $resultArray, &$context) {
  $publicPath = variable_get('file_public_path', conf_path() . '/files/');
  $defaultPath = $publicPath . 'export/';
  if (!is_dir($defaultPath)) {
    drupal_mkdir($defaultPath, NULL, TRUE);
  }
  $fileNameCore = $defaultPath . 'globallink_core.csv';
  $filePathCore = fopen($fileNameCore, 'w') or die('Cant open file!');
  fputcsv($filePathCore, array(
    'rid',
    'nid',
    'vid',
    'source',
    'target',
    'last modified',
    'changed',
  ));
  foreach ($resultArray['resultCore'] as $record) {
    fputcsv($filePathCore, array(
      $record->rid,
      $record->nid,
      $record->vid,
      $record->source,
      $record->target,
      $record->last_modified,
      $record->changed,
    ));
  }
  fclose($filePathCore);
  $fileNameSubmission = $defaultPath . 'globallink_submission.csv';
  $filePathSubmission = fopen($fileNameSubmission, 'w') or die('Cant open file!');
  fputcsv($filePathSubmission, array(
    'rid',
    'submission',
    'submission_ticket',
    'source_lang_code',
    'source_lang_name',
    'sub_target_lang_code',
    'sub_target_lang_name',
    'project_code',
    'project_name',
    'due_date',
    'status',
    'created',
    'updated',
  ));
  foreach ($resultArray['resultCoreSubmission'] as $record) {
    fputcsv($filePathSubmission, array(
      $record->rid,
      $record->submission,
      $record->submission_ticket,
      $record->souce_lang_code,
      $record->source_lang_name,
      $record->sub_target_lang_code,
      $record->sub_target_lang_name,
      $record->project_code,
      $record->project_name,
      $record->due_date,
      $record->status,
      $record->created,
      $record->updated,
    ));
  }
  fclose($filePathSubmission);
  $fileNameDocument = $defaultPath . 'globallink_document.csv';
  $filePathDocument = fopen($fileNameDocument, 'w') or die('Cant open file!');
  fputcsv($filePathDocument, array(
    'rid',
    'submission_rid',
    'document_ticket',
    'entity_type',
    'entity_type_name',
    'object_type',
    'object_type_name',
    'object_id',
    'object_parent_id',
    'object_version_id',
    'object_title',
    'target_lang_code',
    'target_status',
    'target_ticket',
    'target_last_sent',
    'target_last_updated',
  ));
  foreach ($resultArray['resultCoreDocument'] as $record) {
    fputcsv($filePathDocument, array(
      $record->rid,
      $record->submission_rid,
      $record->document_ticket,
      $record->entity_type,
      $record->entity_type_name,
      $record->object_type,
      $record->object_type_name,
      $record->object_id,
      $record->object_parent_id,
      $record->object_version_id,
      $record->object_title,
      $record->target_lang_code,
      $record->target_status,
      $record->target_ticket,
      $record->target_last_sent,
      $record->target_last_updated,
    ));
  }
  fclose($filePathDocument);
  $fileNameFieldConfig = $defaultPath . 'globallink_field_config.csv';
  $filePathFieldConfig = fopen($fileNameFieldConfig, 'w') or die('Cant open file!');
  fputcsv($filePathFieldConfig, array(
    'fid',
    'contect type',
    'entity type',
    'node type',
    'filed name',
    'filed type',
    'filed lable',
    'filed formate',
    'translatable',
  ));
  foreach ($resultArray['resultFieldConfig'] as $record) {
    fputcsv($filePathFieldConfig, array(
      $record->fid,
      $record->content_type,
      $record->entity_type,
      $record->bundle,
      $record->field_name,
      $record->field_type,
      $record->field_label,
      $record->field_format,
      $record->translatable,
    ));
  }
  fclose($filePathFieldConfig);
  $fileNameLocale = $defaultPath . 'globallink_locale.csv';
  $filePathLocale = fopen($fileNameLocale, 'w') or die('Cant open file!');
  fputcsv($filePathLocale, array(
    'local code',
    'local description',
    'drupal local code',
    'drupal local description',
  ));
  foreach ($resultArray['resultLocale'] as $record) {
    fputcsv($filePathLocale, array(
      $record->locale_code,
      $record->locale_desc,
      $record->drupal_locale_code,
      $record->drupal_locale_desc,
    ));
  }
  fclose($filePathLocale);
  $progress = $progress + $limit;
  $context['message'] = 'Now processing ' . $progress . ' - ' . $context['results'][0] . ' Updated';
}

/**
 * Handles Export csv batch process finished.
 */
function globallink_settings_export_batch_finished($success, $results, $operations) {
  if ($success) {
    $publicPath = variable_get('file_public_path', conf_path() . '/files/');
    $rootPath = realpath($publicPath . 'export');
    $folderName = $publicPath . 'export_' . date('m-d-Y_hia') . '.zip';
    $zip = new ZipArchive();
    $zip
      ->open($folderName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY);
    foreach ($files as $name => $file) {
      if (!$file
        ->isDir()) {
        $filePath = $file
          ->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);
        $zip
          ->addFile($filePath, $relativePath);
      }
    }
    $zip
      ->close();
    $download_link = l(t('click here to download the file'), $folderName);
    $output = '<p>' . t('please !download_link.', array(
      '!download_link' => $download_link,
    )) . '</p>';
    drupal_set_message($output);
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ));
    drupal_set_message($message, 'error');
  }
}

/**
 * Nodes batch sets .
 */
function prepare_nodes_button_submit($form, &$form_state) {
  $batch = array(
    'operations' => array(),
    'finished' => 'globallink_settings_nodes_batch_finished',
    'title' => t('Updating Nodes'),
    'init_message' => t('Update Nodes is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Update Nodes has encountered an error.'),
    'file' => drupal_get_path('module', 'globallink') . '/globallink_settings.inc',
  );
  $progress = 0;
  $limit = 10;
  $result = db_query("SELECT * FROM {node} WHERE language = :language", array(
    ':language' => "und",
  ))
    ->fetchAll();
  $max = count($result);
  while ($progress <= $max) {
    $batch['operations'][] = array(
      'globallink_settings_nodes_process',
      array(
        $progress,
        $limit,
        $result,
      ),
    );
    $progress = $progress + $limit;
  }
  batch_set($batch);
}

/**
 * Nodes batch process start.
 */
function globallink_settings_nodes_process($progress, $limit, $result, &$context) {
  $source = language_default()->language;
  foreach ($result as $key => $value) {
    $update = db_query("UPDATE {node} SET language = :language WHERE nid = :nid", array(
      ':language' => $source,
      ':nid' => $value->nid,
    ));
  }
  $progress = $progress + $limit;
  $context['message'] = 'Now processing ' . $progress . ' - ' . $context['results'][0] . ' Updated';
}

/**
 * Nodes batch process finishe.
 */
function globallink_settings_nodes_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('Updated all language neutral nodes to use the site source locale successfully.');
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ));
    drupal_set_message($message, 'error');
  }
}

/**
 * Field collections batch set.
 */
function prepare_field_collections_button_submit($form, &$form_state) {
  if (module_exists('field_collection')) {
    $batch = array(
      'operations' => array(),
      'finished' => 'globallink_settings_field_collections_batch_finished',
      'title' => t('Sets all Field Collections'),
      'init_message' => t('Sets all Field Collections is starting.'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('Update Menus has encountered an error.'),
      'file' => drupal_get_path('module', 'globallink') . '/globallink_settings.inc',
    );
    $progress = 0;
    $limit = 20;
    $resultCollection = db_query("SELECT * FROM {field_config} WHERE type = :type", array(
      ':type' => "field_collection",
    ))
      ->fetchAll();
    if (!empty($resultCollection)) {
      $result = array();
      foreach ($resultCollection as $key => $value) {
        $unserialize = unserialize($value->data);
        if (isset($unserialize['storage']['details']['sql']['FIELD_LOAD_CURRENT'])) {
          $tableNameCurrent = $unserialize['storage']['details']['sql']['FIELD_LOAD_CURRENT'];
          foreach ($tableNameCurrent as $key => $value) {
            $nameCurrent = $key;
          }
          $result[]['tableName'] = $nameCurrent;
        }
        if (isset($unserialize['storage']['details']['sql']['FIELD_LOAD_REVISION'])) {
          $tableNameRevision = $unserialize['storage']['details']['sql']['FIELD_LOAD_REVISION'];
          foreach ($tableNameRevision as $key => $value) {
            $nameRevision = $key;
          }
          $result[]['tableName'] = $nameRevision;
        }
      }
      if (!empty($result)) {
        foreach ($result as $key => $value) {
          $resultAlltabledata[$value['tableName']] = db_query("SELECT * FROM {$value['tableName']} WHERE language = :language", array(
            ':language' => "und",
          ))
            ->fetchAll();
        }
        foreach ($resultAlltabledata as $key => $value) {
          $count = count($value);
        }
        $max = $count;
        while ($progress <= $max) {
          $batch['operations'][] = array(
            'globallink_settings_field_collections_process',
            array(
              $progress,
              $limit,
              $resultAlltabledata,
            ),
          );
          $progress = $progress + $limit;
        }
        batch_set($batch);
      }
      else {
        drupal_set_message('No Recoards');
      }
    }
  }
  else {
    drupal_set_message('Please install field collection module');
  }
}

/**
 * Field collections process start.
 */
function globallink_settings_field_collections_process($progress, $limit, $resultAlltabledata, &$context) {
  $source = language_default()->language;
  foreach ($resultAlltabledata as $key => $value) {
    if (strpos($key, 'field_data_') !== FALSE) {
      $table = explode('field_data_', $key);
      $table_name = $table[1];
      db_update('field_config')
        ->fields(array(
        'translatable' => '1',
      ))
        ->condition('field_name', $table_name, '=')
        ->execute();

      /*$fc_fields = db_select('globallink_field_config', 'gfc')
        ->fields('gfc', array('field_name'))
        ->condition('bundle', $table_name, '=')
        ->condition('entity_type', 'field_collection_item', '=')
        ->execute();*/
      $fc_fields = field_info_instances('field_collection_item', $table_name);
      foreach ($fc_fields as $k => $val) {
        db_update('field_config')
          ->fields(array(
          'translatable' => '1',
        ))
          ->condition('field_name', $val['field_name'], '=')
          ->execute();
        $update = db_update('field_data_' . $val['field_name'])
          ->fields(array(
          'language' => $source,
        ))
          ->condition('language', 'und', '=')
          ->condition('bundle', $table_name, '=')
          ->condition('entity_type', 'field_collection_item', '=')
          ->execute();
      }
    }
  }
  $progress = $progress + $limit;
  $context['message'] = 'Now processing ' . $progress . ' - ' . $context['results'][0] . ' Updated';
}

/**
 * Field collections process finishe.
 */
function globallink_settings_field_collections_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('All field collections have been enabled for field translation.');
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ));
    drupal_set_message($message, 'error');
  }
}

/**
 * Taxonomy create form.
 */
function globallink_translations_settings_taxonomy($form, &$form_state, $object_type, $i18n_mode = I18N_MODE_NONE, $langcode = LANGUAGE_NONE, $options = NULL) {
  $form['i18n_globallink_translations_taxonomy'] = array(
    '#type' => 'fieldset',
    '#title' => t('Multilingual options'),
    '#collapsible' => TRUE,
  );
  $form['i18n_globallink_translations_taxonomy']['i18n_mode'] = array(
    '#type' => 'radios',
    '#title' => t('Translation mode'),
    '#options' => globallink_translation_taxonomy_options($object_type, $options),
    '#default_value' => $i18n_mode,
    '#description' => t('For localizable elements, to have all items available for translation visit the <a href="@locale-refresh">translation refresh</a> page.', array(
      '@locale-refresh' => url('admin/config/regional/translate/i18n_string'),
    )),
  );
  $form['i18n_globallink_translations_taxonomy']['language'] = array(
    '#default_value' => $langcode ? $langcode : LANGUAGE_NONE,
    '#description' => t('Predefined language. If set, it will apply to all items.'),
    '#required' => TRUE,
    '#states' => array(
      'visible' => array(
        'input[name="i18n_mode"]' => array(
          'value' => (string) I18N_MODE_LANGUAGE,
        ),
      ),
    ),
  ) + i18n_element_language_select();

  // The option value 'Language neutral' makes no sense here.
  $form['i18n_globallink_translations_taxonomy']['language']['#options'][LANGUAGE_NONE] = t('- Select a language -');
  $form['i18n_globallink_translations_taxonomy']['prepare_taxonomy_button'] = array(
    '#type' => 'submit',
    '#value' => t('Run Tool'),
    '#name' => 'submit_taxonomy',
    '#submit' => array(
      'prepare_taxonomy_button_submit',
    ),
    '#attributes' => array(
      'onclick' => 'if (!confirm("RUNNING TOOL: Prepare Taxonomy. This action is irreversible. Confirm this operation.")){return false;}',
    ),
  );
  return $form;
}

/**
 * Get list of translation modes.
 *
 * @param $container_type
 *   Object type for the container
 * @param $options
 *   Options to include. If none, defaults for container type will be returned.
 */
function globallink_translation_taxonomy_options($container_type, $options = NULL) {

  // Get names and translation options for container object and items.
  $container_info = i18n_object_info($container_type, 'translation container');
  $replacements = array(
    '@container_name' => $container_info['name'],
    '@item_name_multiple' => $container_info['item name'],
    '@item_name_multiple_capitalized' => ucfirst($container_info['item name']),
  );
  $options = $options ? $options : $container_info['options'];
  return globallink_translation_taxonomy_options_list($replacements, $options);
}

/**
 * Get list of translation modes.
 */
function globallink_translation_taxonomy_options_list($replacements = array(), $options = array()) {
  $entity_version = system_get_info('module', 'entity_translation');
  $list = array(
    I18N_MODE_LOCALIZE => t('Localize. @item_name_multiple_capitalized are common for all languages, but their name and description may be localized.', $replacements),
    I18N_MODE_TRANSLATE => t('Translate. Different @item_name_multiple will be allowed for each language and they can be translated.', $replacements),
    I18N_MODE_LANGUAGE => t('Fixed Language. @item_name_multiple_capitalized will have a global language and they will only show up for pages in that language.', $replacements),
  );
  if ($entity_version['version'] !== '7.x-1.0-beta5') {
    $list[I18N_MODE_ENTITY_TRANSLATION] = t('Field translation. Term fields will be translated through the <a href="!url">Entity translation</a> module.', $replacements);
  }
  if ($options) {
    foreach (array_keys($list) as $key) {
      if (!in_array($key, $options, TRUE)) {
        unset($list[$key]);
      }
    }
  }
  return $list;
}

/**
 * Taxonomy batch set.
 */
function prepare_taxonomy_button_submit($form, &$form_state) {
  $batch = array(
    'operations' => array(),
    'finished' => 'globallink_settings_taxonomy_batch_finished',
    'title' => t('Updating Taxonomy'),
    'init_message' => t('Update Taxonomy is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Update Taxonomy has encountered an error.'),
    'file' => drupal_get_path('module', 'globallink') . '/globallink_settings.inc',
  );
  $progress = 0;
  $limit = 10;
  $values = $form_state['values'];
  $resultTaxonomyVocabulary = db_query("SELECT * FROM {taxonomy_vocabulary}")
    ->fetchAll();
  $resultTaxonomyTermdata = db_query("SELECT * FROM {taxonomy_term_data} WHERE language = :language", array(
    ':language' => "und",
  ))
    ->fetchAll();
  $max = count($resultTaxonomyVocabulary);
  while ($progress <= $max) {
    $batch['operations'][] = array(
      'globallink_settings_taxonomy_process',
      array(
        $progress,
        $limit,
        $resultTaxonomyVocabulary,
        $resultTaxonomyTermdata,
        $values,
      ),
    );
    $progress = $progress + $limit;
  }
  batch_set($batch);
}

/**
 * Taxonomy batch process start.
 */
function globallink_settings_taxonomy_process($progress, $limit, $resultTaxonomyVocabulary, $resultTaxonomyTermdata, $values, &$context) {
  $source = language_default()->language;
  foreach ($resultTaxonomyVocabulary as $key => $value) {
    $update = db_query("UPDATE {taxonomy_vocabulary} SET language = :language, i18n_mode =:i18n_mode WHERE vid = :vid", array(
      ':vid' => $value->vid,
      ':language' => $values['language'],
      ':i18n_mode' => $values['i18n_mode'],
    ));
  }
  if ($values['i18n_mode'] == '4' || $values['i18n_mode'] == '5') {
    foreach ($resultTaxonomyTermdata as $key => $value) {
      $update = db_query("UPDATE {taxonomy_term_data} SET language = :language WHERE tid = :tid", array(
        ':tid' => $value->tid,
        ':language' => $source,
      ));
    }
  }
  $progress = $progress + $limit;
  $context['message'] = 'Now processing ' . $progress . ' - ' . $context['results'][0] . ' Updated';
}

/**
 * Taxonomy batch process end.
 */
function globallink_settings_taxonomy_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('Updated all taxonomy vocabularies to use the selected multilingual mode successfully.');
    drupal_goto('admin/globallink-translations/settings');
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ));
    drupal_set_message($message, 'error');
  }
}

/**
 *
 */
function prepare_taxonomy_custom_submit_redirect(&$form, &$form_state) {
  $url = url('admin/globallink-translations/settings/taxonomy');
  header('Location: ' . $url);
  drupal_exit($url);
}

/**
 * Beans batch sets .
 */
function prepare_beans_button_submit($form, &$form_state) {
  $batch = array(
    'operations' => array(),
    'finished' => 'globallink_settings_beans_batch_finished',
    'title' => t('Updating Beans'),
    'init_message' => t('Update Beans is starting.'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Update Beans has encountered an error.'),
    'file' => drupal_get_path('module', 'globallink') . '/globallink_settings.inc',
  );
  $progress = 0;
  $limit = 10;
  $result = db_query("SELECT * FROM {bean_type}")
    ->fetchAll();
  $max = count($result);
  while ($progress <= $max) {
    $batch['operations'][] = array(
      'globallink_settings_beans_process',
      array(
        $progress,
        $limit,
        $result,
      ),
    );
    $progress = $progress + $limit;
  }
  batch_set($batch);
}

/**
 *
 */
function globallink_settings_beans_process($progress, $limit, $resultbeans, &$context) {
  $source = language_default()->language;
  foreach ($resultbeans as $key => $value) {
    $bean_fields = field_info_instances('bean', $value->name);
    foreach ($bean_fields as $bean_key => $bean_field) {
      db_update('field_config')
        ->fields(array(
        'translatable' => '1',
      ))
        ->condition('field_name', $bean_field['field_name'], '=')
        ->execute();
      $fc_fields = db_select('globallink_field_config', 'gfc')
        ->fields('gfc', array(
        'field_name',
      ))
        ->condition('bundle', 'bean:' . $value->name, '=')
        ->condition('entity_type', 'bean', '=')
        ->execute();
      foreach ($fc_fields as $k => $val) {
        db_update('field_config')
          ->fields(array(
          'translatable' => '1',
        ))
          ->condition('field_name', $val->field_name, '=')
          ->execute();
      }
      $bean_field_table = db_select('field_data_' . $bean_field['field_name'], 'gb')
        ->fields('gb', array(
        'entity_id',
      ))
        ->condition('entity_type', 'bean', '=')
        ->condition('bundle', $value->name, '=')
        ->condition('language', 'und', '=')
        ->execute();
      foreach ($bean_field_table as $bn_field => $bn_value) {
        db_update('field_data_' . $bean_field['field_name'])
          ->fields(array(
          'language' => $source,
        ))
          ->condition('entity_id', $bn_value->entity_id, '=')
          ->condition('entity_type', 'bean', '=')
          ->condition('bundle', $value->name, '=')
          ->execute();
      }
    }
  }
  $progress = $progress + $limit;
  $context['message'] = 'Now processing ' . $progress . ' - ' . $context['results'][0] . ' Updated';
}

/**
 * Beans process finishe.
 */
function globallink_settings_beans_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('All bean fields have been enabled for field translation.');
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE),
    ));
    drupal_set_message($message, 'error');
  }
}

Functions

Namesort descending Description
export_csv_button_submit Export csv batch set.
globallink_adaptor_settings Renders form for globallink_adaptor_settings.
globallink_adaptor_settings_submit Submits adaptor settings.
globallink_adaptor_settings_validate Validates adaptor settings.
globallink_get_log_data Gets log data from specific date in the form of HTML.
globallink_get_project_director_details Gets project director details.
globallink_pd_settings Renders form for globallink_pd_settings.
globallink_pd_settings_submit Handles submission of globallink_pd_settings form.
globallink_pd_settings_validate Handles validation of globallink_pd_settings form.
globallink_save_project_names Saves project names.
globallink_settings_beans_batch_finished Beans process finishe.
globallink_settings_beans_process
globallink_settings_blocks_batch_finished Blocks batch process finishe.
globallink_settings_blocks_process Block batch process start .
globallink_settings_export_batch_finished Handles Export csv batch process finished.
globallink_settings_export_process Export csv batch process start.
globallink_settings_field_collections_batch_finished Field collections process finishe.
globallink_settings_field_collections_process Field collections process start.
globallink_settings_menus_batch_finished Menu batch process finish.
globallink_settings_menus_process_batch1 Menu batch process start.
globallink_settings_nodes_batch_finished Nodes batch process finishe.
globallink_settings_nodes_process Nodes batch process start.
globallink_settings_page
globallink_settings_taxonomy_batch_finished Taxonomy batch process end.
globallink_settings_taxonomy_process Taxonomy batch process start.
globallink_translations_settings_taxonomy Taxonomy create form.
globallink_translation_taxonomy_options Get list of translation modes.
globallink_translation_taxonomy_options_list Get list of translation modes.
globallink_useful_tools Globallink Useful Tools form.
globallink_validate_project_director_details Validates project director details.
globallink_view_log Wraps globallink_convert_date_to_timestamp.
globallink_view_log_submit Exports log.
prepare_beans_button_submit Beans batch sets .
prepare_blocks_button_submit Block batch sets .
prepare_field_collections_button_submit Field collections batch set.
prepare_menus_button_submit Menu batch sets .
prepare_nodes_button_submit Nodes batch sets .
prepare_taxonomy_button_submit Taxonomy batch set.
prepare_taxonomy_custom_submit_redirect