You are here

function uc_catalog_update_7001 in Ubercart 7.3

Migrates uploaded catalog images to the new {file} table.

File

uc_catalog/uc_catalog.install, line 113
Install, update and uninstall functions for the uc_catalog module.

Code

function uc_catalog_update_7001(&$sandbox) {
  if (!db_table_exists('uc_catalog_images')) {
    return;
  }
  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['current_fid'] = 0;
    $sandbox['max'] = db_query("SELECT COUNT(*) FROM {files} f INNER JOIN {uc_catalog_images} u ON u.fid = f.fid")
      ->fetchField();
  }
  $limit = 500;

  // The old {files} tables still exists.  We migrate core data from upload
  // module, but any contrib module using it will need to do its own update.
  $result = db_query_range('SELECT tid, f.fid, uid, u.filename, u.filepath AS uri, u.filemime, u.filesize, status, timestamp FROM {files} f INNER JOIN {uc_catalog_images} u ON u.fid = f.fid WHERE f.fid > :current ORDER BY f.fid', 0, $limit, array(
    ':current' => $sandbox['current_fid'],
  ), array(
    'fetch' => PDO::FETCH_ASSOC,
  ));

  // We will convert filepaths to uri using the default schmeme
  // and stripping off the existing file directory path.
  $basename = variable_get('file_directory_path', conf_path() . '/files');
  $scheme = variable_get('file_default_scheme', 'public') . '://';
  $fids = array();
  foreach ($result as $file) {

    // Get term id for the image.
    $tid = $file['tid'];

    // Don't break the insert query with extra data.
    unset($file['tid']);
    $file['uri'] = $scheme . str_replace($basename, '', $file['uri']);
    $file['uri'] = file_stream_wrapper_uri_normalize($file['uri']);
    db_merge('file_managed')
      ->key(array(
      'fid' => $file['fid'],
    ))
      ->fields(array(
      'uid' => $file['uid'],
      'filename' => $file['filename'],
      'uri' => $file['uri'],
      'filemime' => $file['filemime'],
      'filesize' => $file['filesize'],
      'status' => $file['status'],
      'timestamp' => $file['timestamp'],
    ))
      ->execute();
    $fids[] = $file['fid'];

    // Add the usage entry for the file.
    file_usage_add((object) $file, 'file', 'taxonomy_term', $tid);
    $term = (object) array(
      'tid' => $tid,
      'uc_catalog_image' => array(
        LANGUAGE_NONE => array(
          0 => array(
            'fid' => $file['fid'],
          ),
        ),
      ),
    );
    _update_7000_field_sql_storage_write('taxonomy_term', 'catalog', $term->tid, NULL, 'uc_catalog_image', $term->uc_catalog_image);
    $sandbox['progress']++;
    $sandbox['current_fid'] = $file['fid'];
    $sandbox['message'] = check_plain($file['filename']);
  }

  // TODO: delete the found fids from {files}?
  if ($sandbox['progress'] < $sandbox['max']) {
    $sandbox['#finished'] = min(0.99, $sandbox['progress'] / $sandbox['max']);
  }
  else {
    $sandbox['#finished'] = 1;
  }
}