summaryrefslogtreecommitdiffstats
path: root/modules/content_migrate/includes/content_migrate.admin.inc
blob: 7c0869d407c2d30827d51701f92a000862726f72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php
// $Id$
/**
 * @file content_migrate.admin.inc
 * Code to process field data migration, moved into a separate file for efficiency.
 */

/**
 * Determine which fields can be migrated, have already been migrated, and are
 * unable to be migrated due to missing modules.
 */
function content_migrate_get_options() {
  $options = array('available' => array(), 'converted' => array(), 'missing' => array());
  
  $field_values = content_migrate_get_field_values();
  if (empty($field_values)) {
    drupal_set_message(t('There is no D6 field information in this database.'));
    return FALSE;
  }

  $type_names = node_type_get_names();
  $new_fields = array_keys(field_info_fields());
  
  // Figure out which field and widget modules are available.
  $available_modules = array_unique(array_merge(module_implements('field_info'), module_implements('field_widget_info')));
  
  foreach ($field_values as $field_name => $field_value) {
    $bundles = array();
    $missing_module = !in_array($field_value['module'], $available_modules);
    $missing_modules = $missing_module ? array($field_value['module']) : array();
    $instance_values = content_migrate_get_instance_values(NULL, $field_name);
    
    // Debug
    //dsm($field_value);
    //dsm($instance_values);
    
    foreach ($instance_values as $bundle => $instance_value) {
      $bundles[] = $type_names[$bundle];
      $label = $instance_value['label'];
      if (!in_array($instance_value['widget']['module'], $available_modules)) {
        $missing_module = TRUE;
        $missing_modules[] = $instance_value['widget']['module'];
      }
    }
    $data = array(
      0 => $field_name,
      1 => $field_value['type'],
      2 => implode(', ', $bundles),
      3 => empty($missing_modules) ? '' : t('Missing modules: @list', array('@list' => implode(', ', $missing_modules))),
    );
    if (in_array($field_name, $new_fields)) {
      $options['converted'][$field_name] = $data;
    }
    // TODO, do we need to check for more than the mere presence of a module?
    elseif ($missing_module) {
      $options['missing'][$field_name] = $data;
    }
    else {
      $options['available'][$field_name] = $data;
    }
  }
  return $options;
}

/**
 * Form generator for the migration selection form.
 * 
 * @todo Make this into a nice table where you have 
 * an option to check all available fields to migrate
 * them all at once.
 */
function content_migrate_select($form, &$form_state) {
  $form = array();
  $options = content_migrate_get_options();
  if (!$options) {
    return $form;
  }

  $header = array(t('Field'), t('Field type'), t('Content type(s)'), t('Other information'));
  $form['#tree'] = TRUE;
  $form['available'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => count($options['available']) < 1,
    '#title' => t('Available fields'),
    '#description' => t('Fields that have not yet been migrated but are available for migration.'),
  );
  $form['available']['data'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options['available'],
    '#empty' => t('No fields are available to be migrated.'),
  );  
  $form['available']['submit'] = array(
    '#type' => 'submit', 
    '#value' => t('Migrate selected fields'),
    '#submit' => array('content_migrate_select_submit'),
  );  

  $form['converted'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => count($options['converted']) < 1,
    '#title' => t('Converted fields'),
    '#description' => '<p>'. t('Fields that have already been converted. You can choose to roll them back if the conversion did not work correctly. Note that rolling fields back will completely destroy the new field tables.') . ' <span class="error"><strong>' . t('This operation cannot be undone!') . '</strong></span>',
  );    
  $form['converted']['data'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options['converted'],
    '#empty' => t('No fields are already converted.'),
  );
  $form['converted']['submit'] = array(
    '#type' => 'submit', 
    '#value' => t('Roll back selected fields'),
    '#submit' => array('content_migrate_rollback_submit'),
  );     
  
  $form['missing'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => count($options['missing']) < 1,
    '#title' => t('Unavailable fields'),
    '#description' => t('Fields that cannot be migrated because some modules are missing.'),
  );  
  $form['missing']['data'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options['missing'],
    '#empty' => t('No fields have missing modules.'),
  ); 
      
  return $form;
}

/**
 * Submit handler.
 * 
 * @TODO add a confirmation on the rollback submission.
 */
function content_migrate_rollback_submit($form, &$form_state) {
  $field_names = array_filter($form_state['values']['converted']['data']);
}

/**
 * Helper function to perform rollback.
 */
function content_migrate_rollback($field_names) {
  foreach ($field_names as $field_name) {
    $field = field_info_field($field_name);
    
    // Deleting the field only marks it for deletion.
    field_delete_field($field_name);
    
    // We are bypassing the field batch processing
    // and simply deleting all the data.
    // The assumption is that the migration was
    // unsuccessful and will be re-attempted
    // and we need to remove all traces of the 
    // new field for later migrations to work.
    $new_table = content_migrate_new_table($field);
    db_drop_table($new_table);
    
    $instances = field_read_instances(array('field_id' => $field['id']), array('include_deleted' => 1));
    foreach ($instances as $instance) {
      field_purge_instance($instance);
    }
    field_purge_field($field);
    drupal_set_message(t('Rolling back @field_name.', array('@field_name' => $field_name)));
  }
}

/**
 * Submit handler.
 */
function content_migrate_select_submit($form, &$form_state) {
  $field_names = array_filter($form_state['values']['available']['data']);
  _content_migrate_batch($field_names);
}

/**
 * Helper function to create a batch.
 */
function _content_migrate_batch($field_names) {
  $batch = array(
    'title' => t('Migrating data'),
    'file'  => drupal_get_path('module', 'content_migrate') . '/includes/content_migrate.admin.inc',
    'operations' => array(
      array('_content_migrate_batch_process_create_fields', array($field_names)),
    ),
    'finished' => "Field migration is finished",
    'init_message' => t("Fields migration is starting."),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Field migration has encountered an error.'),
  );
  // Migrate field data one field at a time.
  foreach ($field_names as $field_name) {
    $batch['operations'][] = array('_content_migrate_batch_process_migrate_data', array($field_name));
  }
  batch_set($batch);
}

/**
 * Batch operation callback to create fields.
 */
function _content_migrate_batch_process_create_fields($field_names, &$context) {
  $type_names = node_type_get_names();
  foreach ($field_names as $field_name) {
    $context['message'] = t('"Creating field: %field', array('%field' => $field_name));
    $field_value = content_migrate_get_field_values($field_name);

    // Create the field and store the new field 
    // definition in $context so we can retrieve it later. 
    try {
      // A shared field may already have been created, check first.
      $field = field_info_field('node', $field_value['field_name']);
      if (empty($field)) {
        unset($field_value['columns']);
        unset($field_value['db_storage']);   
        $field = field_create_field($field_value);
        $context['fields'][$field_name] = $field;
        drupal_set_message(t("Created field @field_name", array('@field_name' => $field_name)));
      }
 
      // Create each of the new instances and store 
      // the new instance definitions in $context.
      $instance_values = content_migrate_get_instance_values(NULL, $field_name);

      foreach ($instance_values as $bundle => $instance_value) {
        try {
          $instance = field_create_instance($instance_value); 
          $context['instances'][$field_name][$instance['bundle']] = $instance;
          drupal_set_message(t("Created instance of @field_name in bundle @bundle.", array(
            '@field_name' => $field_name, '@bundle' => $type_names[$instance['bundle']])));
          
        }
        catch (Exception $e) {
          drupal_set_message(t('Error creating instance of @field_name in bundle @bundle.', array(
            '@field_name' => $field_name, '@bundle' => $type_names[$instance_value['bundle']])), 'error');
          drupal_set_message($e, 'error');
        }
      }
    }
    catch (Exception $e) {
      drupal_set_message(t("Error creating field @field_name", array('@field_name' => $field_name)), 'error'); 
      drupal_set_message($e, 'error');
    }
    field_info_cache_clear();

  }
  $context['finished'] = TRUE;
} 

/**
 * Batch operation callback to migrate data.
 * Copy old table data to new field table.
 */
function _content_migrate_batch_process_migrate_data($field_name, &$context) {

  // The first time through, find all the nodes that have this field.
  if (!isset($context['sandbox']['progress'])) {

    $field_value = content_migrate_get_field_values($field_name);
    $instance_values = content_migrate_get_instance_values(NULL, $field_name);
    $types = array();
    foreach ($instance_values as $bundle => $instance_value) {
      $types[] = $bundle;
    }
    $field = field_info_field($field_name);  
    $old_table          = content_migrate_old_table($field_value, $instance_value);
    $old_cols           = content_migrate_old_columns($field_value, $instance_value);
    $new_table          = content_migrate_new_table($field);
    $new_revision_table = content_migrate_new_revision($field);
    $new_columns        = content_migrate_new_columns($field);
    // Shared, non-multiple fields do not have a delta but are still in per-field tables.
    $add_delta          = $field_value['cardinality'] != 1 && content_migrate_storage_type($field_value, $instance_value) == CONTENT_DB_STORAGE_PER_FIELD;

    $query = db_select($old_table, 'old_table', array('fetch' => PDO::FETCH_ASSOC));
    $node_alias = $query->join('node', 'n', 'old_table.nid=n.nid');
    $result = $query
      ->fields($node_alias, array('title', 'type', 'vid'))
      ->fields('old_table', array('nid'))
      ->orderBy('nid', 'ASC')
      ->distinct()
      ->execute();
    
    $nodes = array();
    foreach ($result as $row) {
      $nodes[] = array('nid' => $row['nid'], 'title' => $row['title'], 'type' => $row['type'], 'vid' => $row['vid']);
    }
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($nodes);
    $context['sandbox']['nodes'] = $nodes;
    $context['sandbox']['old_table'] = $old_table;
    $context['sandbox']['new_table'] = $new_table;
    $context['sandbox']['new_revision_table'] = $new_revision_table;
    $context['sandbox']['old_cols'] = $old_cols;
    $context['sandbox']['new_cols'] = $new_columns;
    $context['sandbox']['types'] = $types;
    $context['sandbox']['field'] = $field;
    $context['sandbox']['add_delta'] = $add_delta;
   
  }

  // Process one node in each batch.

  $node = array_shift($context['sandbox']['nodes']);
  if (!$node) {
    return;
  }

  // Construct an record to insert into the new field table
  // from the data in the old table.

  $query = db_select($context['sandbox']['old_table'], 'old_table', array('fetch' => PDO::FETCH_ASSOC));
    
  // We need new columns for bundle name, entity type, and language.
  $query->addExpression("'". $node['type'] ."'", 'bundle');
  $query->addExpression("'node'", 'entity_type');
  $query->addExpression("'". LANGUAGE_NONE ."'", 'language');
    
  // There are new names for what were the nid and vid columns.
  $query->addField('old_table', 'nid', 'entity_id');
  $query->addField('old_table', 'vid', 'revision_id');
    
  // Add the field columns to the select query.
  // Use the new column names as aliases in case the 
  // name changed, hopefully none did.
  foreach ($context['sandbox']['old_cols'] as $key => $col) {
    $query->addField('old_table', $col, $context['sandbox']['new_cols'][$key]);
  }
    
  // Add delta, or construct it if missing.
  if ($context['sandbox']['add_delta']) {
    $query->addField('old_table', 'delta', 'delta');
  }
  else {
    $query->addExpression(0, 'delta');
  }
  $query->condition('nid', $node['nid']);
  $result = $query->execute();

  foreach ($result as $record) {
  
    // Let modules alter this before the insert.
    drupal_alter('content_migrate_data_record', $record, $context['sandbox']['field']);

    if (!empty($record)) {
      if ($record['revision_id'] == $node['vid']) {
        drupal_write_record($context['sandbox']['new_table'], $record);
      }
      drupal_write_record($context['sandbox']['new_revision_table'], $record);
    }
  }

  // Update our progress information.
  $context['sandbox']['progress']++;
  $context['message'] = t('Processing %nid : %title', array('%title' => $node['title'], '%nid' => $node['nid']));

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }

}