You are here

function transliteration_retroactive_submit in Transliteration 7.3

Same name and namespace in other branches
  1. 6.3 transliteration.admin.inc \transliteration_retroactive_submit()

Form submit function; retroactively transliterates existing file names.

See also

transliteration_retroactive()

File

./transliteration.admin.inc, line 62
Retroactive transliteration and admin settings UI.

Code

function transliteration_retroactive_submit($form, &$form_state) {
  $count = 0;
  $errors = array();
  $result = transliteration_file_query()
    ->execute();
  while ($file = $result
    ->fetchObject()) {
    $wrapper = file_stream_wrapper_get_instance_by_uri($file->uri);
    $scheme = file_uri_scheme($file->uri);

    // Missing implementation.
    if (!$wrapper) {
      $errors[] = file_uri_target($file->uri);
      continue;
    }

    // Skip non-writable stream wrappers.
    $writeable_stream_wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE);
    if (!isset($writeable_stream_wrappers[$scheme])) {
      continue;
    }

    // Missing file.
    if (!file_exists($wrapper
      ->realpath())) {
      $errors[] = file_uri_target($file->uri);
      continue;
    }

    // Sanitize file name.
    $filename = transliteration_clean_filename(basename($file->uri));

    // Build destination URI.
    $destination = file_stream_wrapper_uri_normalize(drupal_dirname($file->uri) . '/' . $filename);
    $destination = file_destination($destination, FILE_EXISTS_RENAME);

    // Rename and update the file record accordingly.
    if ($wrapper
      ->rename($file->uri, $destination)) {

      // If possible, add a url redirect to handle old URL references.
      if (module_exists('redirect')) {
        $redirect = new stdClass();
        redirect_object_prepare($redirect, array(
          'source' => $wrapper
            ->getDirectoryPath() . '/' . file_uri_target($file->uri),
          'redirect' => $wrapper
            ->getDirectoryPath() . '/' . file_uri_target($destination),
          'status_code' => 301,
        ));
        redirect_save($redirect);
      }
      $file->uri = $destination;
      file_save($file);
      $count++;
    }
    else {
      $errors[] = file_uri_target($file->uri);
    }
  }
  if ($errors) {
    $message = t('Not all file names could be converted. The following files could not be accessed and have been ignored:');
    $message .= theme('item_list', array(
      'items' => $errors,
    ));
    drupal_set_message($message, 'error');
  }
  else {
    drupal_set_message(t('@filenames have been successfully transliterated.', array(
      '@filenames' => format_plural($count, '1 file name', '@count file names'),
    )));
  }

  // Flush page cache.
  cache_clear_all();
}