Projet

Général

Profil

Paste
Télécharger (40 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / node_export / node_export.module @ 87dbc3bf

1
<?php
2

    
3
/**
4
 * @file
5
 * The Node export module.
6
 *
7
 * Allows users to export nodes and then import them into another Drupal installation.
8
 */
9

    
10
/**
11
 * Implements hook_permission().
12
 */
13
function node_export_permission() {
14
  return array(
15
    'export nodes' => array(
16
      'title' => t('Export nodes'),
17
    ),
18
    'export own nodes' => array(
19
      'title' => t('Export own nodes'),
20
    ),
21
    'use PHP to import nodes' => array(
22
      'title' => t('Use PHP to import nodes'),
23
      'description' => t('Required for importing, but can allow execution of PHP.'),
24
      'restrict access' => TRUE,
25
    ),
26
  );
27
}
28

    
29
/**
30
 * Implements hook_menu().
31
 */
32
function node_export_menu() {
33
  $items['admin/config/content/node_export'] = array(
34
    'access arguments' => array('administer site configuration'),
35
    'page callback' => 'drupal_get_form',
36
    'page arguments' => array('node_export_settings'),
37
    'title' => 'Node export',
38
    'description' => 'Configure the settings for Node export.',
39
    'file' => 'node_export.pages.inc',
40
  );
41
  $selected_formats = variable_get('node_export_format', array('drupal'));
42
  if (count(array_filter($selected_formats)) > 1) {
43
    $format_handlers = node_export_format_handlers();
44
    foreach ($format_handlers as $format_handler => $format) {
45
      if (!empty($selected_formats[$format_handler])) {
46
        $items['node/%node/node_export/' . $format_handler] = array(
47
          'access callback' => 'node_export_access_export',
48
          'access arguments' => array(1),
49
          'page callback' => 'node_export_gui',
50
          'page arguments' => array(1, $format_handler),
51
          'title' => 'Node export (' . $format['#title'] . ')',
52
          'weight' => 5,
53
          'type' => MENU_LOCAL_TASK,
54
          'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
55
          'file' => 'node_export.pages.inc',
56
        );
57
      }
58
    }
59
  }
60
  else {
61
    $items['node/%node/node_export'] = array(
62
      'access callback' => 'node_export_access_export',
63
      'access arguments' => array(1),
64
      'page callback' => 'node_export_gui',
65
      'page arguments' => array(1),
66
      'title' => 'Node export',
67
      'weight' => 5,
68
      'type' => MENU_LOCAL_TASK,
69
      'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
70
      'file' => 'node_export.pages.inc',
71
    );
72
  }
73
  $items['admin/content/node_export'] = array(
74
    'access arguments' => array('export nodes'),
75
    'page callback' => 'node_export_gui',
76
    'page arguments' => array(NULL, NULL),
77
    'title' => 'Node export',
78
    'type' => MENU_CALLBACK,
79
    'file' => 'node_export.pages.inc',
80
  );
81
  $items['node/add/node_export'] = array(
82
    'title' => 'Node export: import',
83
    'page callback' => 'drupal_get_form',
84
    'page arguments' => array('node_export_import_form'),
85
    'access callback' => 'node_export_access_import',
86
    'description' => 'Import content using <em>Node export</em>.',
87
    'file' => 'node_export.pages.inc',
88
  );
89

    
90
  return $items;
91
}
92

    
93
/**
94
 * Check access to export a node.
95
 */
96
function node_export_access_export($node) {
97
  global $user;
98
  if (is_int($node)) {
99
    $node = node_load($node);
100
  }
101

    
102
  if (function_exists('drush_main')) {
103
    // Always allow drush to export nodes.
104
    $access = TRUE;
105
  }
106
  else {
107
    // Check basic role permissions first.
108
    $access = (user_access('export nodes') || ($user->uid && ($node->uid == $user->uid) && user_access('export own nodes')));
109
    // Make sure the user can view the original node content.
110
    $access = $access && node_access('view', $node);
111
  }
112

    
113
  // Let other modules alter this - for example to only allow some users
114
  // to export specific nodes or types.
115
  drupal_alter("node_export_access_export", $access, $node);
116
  return $access;
117
}
118

    
119
/**
120
 * Check access to import a node.
121
 */
122
function node_export_access_import($node = NULL) {
123
  global $user;
124

    
125
  if (function_exists('drush_main')) {
126
    // Always allow drush to import nodes.
127
    $access = TRUE;
128
  }
129
  elseif (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install') {
130
    // During the install phase $user is the Anonymous user; however, in
131
    // practice $user is performing tasks only granted to the admin user
132
    // (eg: installing modules, changing site settings).  For this reason
133
    // it seems sensible to allow this "Anonymous admin" user to import
134
    // any nodes they wish.
135
    $access = TRUE;
136
  }
137
  else {
138
    // Check basic role permissions first.
139
    $access = user_access('use PHP to import nodes');
140

    
141
    if (!is_null($node) && $access) {
142
      // Check node conditions.
143
      $access = node_access('create', $node->type);
144
    }
145
  }
146

    
147
  // Let other modules alter this - for example to only allow some users
148
  // to import specific nodes or types.
149
  drupal_alter("node_export_access_import", $access, $node);
150
  return $access;
151
}
152

    
153
/**
154
 * Check access to export an array of nodes.
155
 */
156
function node_export_access_export_nodes($nodes) {
157
  // Convert to array if it isn't already.
158
  if (is_object($nodes)) {
159
    $nodes = array($nodes);
160
  }
161
  foreach ($nodes as &$node) {
162
    if (!node_export_access_export($node)) {
163
      return FALSE;
164
    }
165
  }
166
  return TRUE;
167
}
168

    
169
/**
170
 * Check access to import an array of nodes.
171
 */
172
function node_export_access_import_nodes($nodes) {
173
  // Convert to array if it isn't already.
174
  if (is_object($nodes)) {
175
    $nodes = array($nodes);
176
  }
177
  foreach ($nodes as &$node) {
178
    if (!node_export_access_import($node)) {
179
      return FALSE;
180
    }
181
  }
182
  return TRUE;
183
}
184

    
185
/**
186
 * Implements hook_node_type_update().
187
 */
188
function node_export_node_type_update($info) {
189
  if (!empty($info->old_type) && $info->old_type != $info->type) {
190
    if (variable_get('node_export_reset_' . $info->old_type, FALSE)) {
191
      variable_del('node_export_reset_' . $info->old_type);
192
      variable_set('node_export_reset_' . $info->type, TRUE);
193
    }
194
  }
195
}
196

    
197
/**
198
 * Implements hook_node_type_delete().
199
 */
200
function node_export_node_type_delete($info) {
201
  variable_del('node_export_reset_' . $info->type);
202
}
203

    
204
/**
205
 * Implements hook_views_api().
206
 */
207
function node_export_views_api() {
208
  return array(
209
    'api' => 3,
210
    'path' => drupal_get_path('module', 'node_export') . '/views',
211
  );
212
}
213

    
214
/**
215
 * Implements hook_node_operations().
216
 */
217
function node_export_node_operations() {
218
  $operations = array();
219
  if (user_access('export nodes')) {
220

    
221
    $selected_formats = variable_get('node_export_format', array('drupal'));
222
    if (count(array_filter($selected_formats)) > 1) {
223
      $format_handlers = node_export_format_handlers();
224
      foreach ($format_handlers as $format_handler => $format) {
225
        if ($selected_formats[$format_handler]) {
226
          $operations['node_export_' . $format_handler] = array(
227
            'label' => t('Node export') . " (" . $format['#title'] . ")",
228
            'callback' => 'node_export_bulk_operation',
229
            'callback arguments' => array('format' => $format_handler),
230
          );
231
        }
232
      }
233
    }
234
    else {
235
      $operations = array(
236
        'node_export' => array(
237
          'label' => t('Node export'),
238
          'callback' => 'node_export_bulk_operation',
239
        ),
240
      );
241
    }
242

    
243
  }
244
  return $operations;
245
}
246

    
247
/**
248
 * Callback for use with hook_node_operations().
249
 */
250
function node_export_bulk_operation($nodes = NULL, $format = NULL, $delivery = NULL) {
251
  module_load_include('inc', 'node_export', 'node_export.pages');
252
  return node_export_gui($nodes, $format, $delivery);
253
}
254

    
255
/**
256
 * Implements hook_action_info()
257
 */
258
function node_export_action_info() {
259
  $actions = array();
260
  if (user_access('export nodes')) {
261
    $selected_formats = variable_get('node_export_format', array('drupal'));
262
    $format_handlers = node_export_format_handlers();
263
    foreach ($format_handlers as $format_handler => $format) {
264
      if (!empty($selected_formats[$format_handler])) {
265
         // @todo: should formats be able to define their own actions?
266
         if (!empty($format['#file']) && is_file($format['#file'])) {
267
           require_once $format['#file'];
268
         }
269
         $format_action = 'node_export_' . $format_handler . '_action';
270
         if (function_exists($format_action . '_form')) {
271
           $actions[$format_action] = array(
272
             'type' => 'node',
273
             'label' => t('Node export') . " (" . $format['#title'] . ")",
274
             'behavior' => array('changes_property'),
275
             // This action only works when invoked through VBO. That's why it's
276
             // declared as non-configurable to prevent it from being shown in the
277
             // "Create an advanced action" dropdown on admin/config/system/actions.
278
             'configurable' => FALSE,
279
             'vbo_configurable' => TRUE,
280
           );
281
        }
282
      }
283
    }
284
  }
285
  return $actions;
286

    
287
}
288

    
289
/**
290
 * Export Nodes Action "Configuration" Form
291
 *
292
 * Technically for a normal action this is where you would provide config
293
 * for the actual execution of the action. However, we're hijacking it to
294
 * present the completed node_export_gui page.
295
 */
296
function node_export_action_form($context, &$form_state, $format = NULL) {
297
  // Get the name of the vbo views field
298
  $vbo = _views_bulk_operations_get_field($form_state['build_info']['args'][0]);
299
  // Adjust the selection in case the user chose 'select all'
300
  _views_bulk_operations_adjust_selection($form_state['selection'], $form_state['select_all_pages'], $vbo);
301
  $nodes = array_combine($form_state['selection'], $form_state['selection']);
302
  return node_export_bulk_operation($nodes);
303
}
304

    
305
/**
306
 * Export nodes.
307
 *
308
 * @param $nids
309
 *   A node ID or array of node IDs to export.
310
 * @param $format
311
 *   The format to use for export.
312
 * @param $msg_t
313
 *   Function used to translate.
314
 * @return
315
 *   An array with keys 'success' which is a boolean value representing whether
316
 *   the export was successful and 'output' which contains the code string or an
317
 *   array of translated error messages to be shown to the user.
318
 */
319
function node_export($nids, $format = NULL, $msg_t = 't') {
320
  global $user;
321

    
322
  // Make $nids an array if it isn't.
323
  if (is_int($nids)) {
324
    $nids = array($nids);
325
  }
326
  elseif (is_object($nids)) {
327
    $nids = array($nids->nid);
328
  }
329

    
330
  $nodes = array();
331
  foreach ($nids as $nid) {
332
    $original_node = node_load($nid);
333

    
334
    if (!node_export_access_export($original_node)) {
335
      // Halt exporting.
336
      $error = $msg_t("You do not have permission to perform a Node export on one or more of these nodes.  No nodes exported.");
337
      return array(
338
        'success' => FALSE,
339
        'output' => array($error),
340
      );
341
    }
342

    
343
    $node = node_export_prepare_node($original_node);
344

    
345
    $nodes[] = $node;
346
  }
347

    
348
  // Get the node code from the format handler
349
  $format_handlers = node_export_format_handlers();
350
  $node_export_format = variable_get('node_export_format', array('drupal'));
351
  $format_handler = $format ? $format : reset($node_export_format);
352
  if (!isset($format_handlers[$format_handler])) {
353
    $format_handler = 'drupal';
354
  }
355

    
356
  // Let other modules do special fixing up.
357
  drupal_alter('node_export', $nodes, $format_handler);
358

    
359
  // If any nodes are set to FALSE, then an error was triggered in another module.
360
  // Currently modules doing this should also leave a watchdog warning.
361
  if (in_array(FALSE, $nodes)) {
362
    // Halt exporting.
363
    $error = $msg_t('An error occurred when processing nodes, please check your logs.  No nodes exported.');
364
    return array(
365
      'success' => FALSE,
366
      'output' => array($error),
367
    );
368
  }
369

    
370
  if (!empty($format_handlers[$format_handler]['#file']) && is_file($format_handlers[$format_handler]['#file'])) {
371
    require_once $format_handlers[$format_handler]['#file'];
372
  }
373

    
374
  $code_string = call_user_func(
375
    $format_handlers[$format_handler]['#export_callback'],
376
    $nodes,
377
    $format_handler
378
  );
379

    
380
  // Let modules modify the node code.
381
  drupal_alter('node_export_encode', $code_string, $nodes, $format_handler);
382

    
383
  return array(
384
    'success' => TRUE,
385
    'output' => $code_string,
386
    'format' => $format_handler,
387
  );
388

    
389
}
390

    
391
/**
392
 * Prepare a single node during export.
393
 */
394
function node_export_prepare_node(&$original_node) {
395
  // Create UUID if it's not there.
396
  if (!uuid_get_uuid('node', 'nid', $original_node->nid)) {
397
    $original_node->uuid = uuid_set_uuid('node', 'nid', $original_node->nid);
398
    // Save it so future node exports are consistent.
399
    node_save($original_node);
400
  }
401

    
402
  $node = clone($original_node);
403

    
404
  // Fix taxonomy array
405
  if (isset($node->taxonomy) && count($node->taxonomy)) {
406
    $vocabularies = taxonomy_get_vocabularies();
407
    $new_taxonomy = array();
408
    foreach ($node->taxonomy as $term) {
409
      // Free-tagging vocabularies need a different format
410
      if ($vocabularies[$term->vid]->tags) {
411
        $new_taxonomy['tags'][$term->vid][] = $term->name;
412
      }
413
      else {
414
        $new_taxonomy[$term->vid][$term->tid] = $term->tid;
415
      }
416
    }
417
    if (isset($new_taxonomy['tags']) && count($new_taxonomy['tags'])) {
418
      // Comma seperate the tags
419
      foreach ($new_taxonomy['tags'] as $vid => $tags) {
420
        $new_taxonomy['tags'][$vid] = implode(', ', $tags);
421
      }
422
    }
423
    $node->taxonomy = $new_taxonomy;
424
  }
425

    
426
  // Attach path to the node.  Drupal doesn't attach this anymore for
427
  // performance reasons http://drupal.org/node/332333#comment-2163634.
428
  $node->path = path_load(array('source' => 'node/' . $node->nid));
429

    
430
  // Fix menu array
431
  $node->menu = node_export_get_menu($original_node);
432

    
433
  // Remove recursion from the object.
434
  $node = node_export_remove_recursion($node);
435

    
436
  // Add a parameter to identify this node as coming from D7, might be useful some day.
437
  $node->node_export_drupal_version = '7';
438

    
439
  // Export file fields.
440
  node_export_file_field_export($node, $original_node);
441

    
442
  // Let other modules do special fixing up.
443
  drupal_alter('node_export_node', $node, $original_node);
444

    
445
  return $node;
446
}
447

    
448
/**
449
 *  Check if all types in the import exist.
450
 *
451
 *  @return
452
 *    TRUE if all types exist, otherwise an array of missing type names.
453
 */
454
function node_export_import_types_check($nodes) {
455
  $missing_types = array();
456
  foreach ($nodes as $node) {
457
    if (node_type_get_name($node) == FALSE) {
458
      $missing_types[$node->type] = $node->type;
459
    }
460
  }
461
  return (!empty($missing_types) ? $missing_types : TRUE);
462
}
463

    
464
/**
465
 * Import Function
466
 *
467
 * @param $code_string
468
 *   The string of export code.
469
 * @param $msg_t
470
 *   Function used to translate.
471
 * @param $save
472
 *   When TRUE will save the nodes that are imported.
473
 * @return
474
 *   An array with keys 'success' which is a boolean value representing whether
475
 *   the import was successful and 'output' which contains an array of
476
 *   translated strings to be shown to the user as messages.
477
 */
478
function node_export_import($code_string, $msg_t = 't', $save = TRUE) {
479
  // Early check to avoid letting hooligans and the elderly pass data to the
480
  // eval() function call.
481
  if (!node_export_access_import()) {
482
    $error = $msg_t(
483
      'You do not have permission to import any nodes.'
484
    );
485
    return array(
486
      'success' => FALSE,
487
      'output' => array($error),
488
    );
489
  }
490

    
491
  // Allow modules to manipulate the $code_string.
492
  drupal_alter('node_export_decode', $code_string);
493

    
494
  // Pass the string to each format handler until one returns something useful.
495
  $format_handlers = node_export_format_handlers();
496
  $nodes = array();
497
  $used_format = "";
498
  foreach ($format_handlers as $format_handler => $format) {
499

    
500
    if (!empty($format['#file']) && is_file($format['#file'])) {
501
      require_once $format['#file'];
502
    }
503

    
504
    $nodes = call_user_func(
505
      $format['#import_callback'],
506
      $code_string
507
    );
508

    
509
    if (!empty($nodes)) {
510
      $used_format = $format_handler;
511
      break;
512
    }
513
  }
514

    
515
  if (isset($nodes['success']) && !$nodes['success']) {
516
    // Instead of returning nodes, the format handler returned an error array.
517
    // Translate the errors and return them.
518
    foreach ($nodes['output'] as $key => $output) {
519
      $nodes['output'][$key] = $msg_t($output);
520
    }
521
    return array(
522
      'success' => FALSE,
523
      'output' => $nodes['output'],
524
    );
525
  }
526

    
527
  if ($used_format == "") {
528
    $error = $msg_t(
529
      'Node export was unable to recognize the format of the supplied code.  No nodes imported.'
530
    );
531
    return array(
532
      'success' => FALSE,
533
      'output' => array($error),
534
    );
535
  }
536

    
537
  $nodes = node_export_restore_recursion($nodes);
538

    
539
  $types_exist = node_export_import_types_check($nodes);
540
  if ($types_exist !== TRUE) {
541
    // There was a problem with the content types check.
542
    $error = $msg_t(
543
      'Error encountered during import.  Node types unknown on this site: %t.  No nodes imported.',
544
      array('%t' => implode(", ", $types_exist))
545
    );
546
    return array(
547
      'success' => FALSE,
548
      'output' => array($error),
549
    );
550
  }
551

    
552
  if (!node_export_access_import_nodes($nodes)) {
553
    // There was a problem with permissions.
554
    $error = $msg_t(
555
      'You do not have permission to perform a Node export: import on one or more of these nodes.  No nodes imported.'
556
    );
557
    return array(
558
      'success' => FALSE,
559
      'output' => array($error),
560
    );
561
  }
562

    
563
  $count = 0;
564
  $total = count($nodes);
565
  // Let other modules do special fixing up.
566
  drupal_alter('node_export_import', $nodes, $used_format, $save);
567
  $new_nodes = array();
568
  $messages = array();
569
  foreach ($nodes as $original_node) {
570
    $node = node_export_node_clone($original_node);
571

    
572
    // Import file fields.
573
    node_export_file_field_import($node, $original_node);
574

    
575
    // Handle existing nodes.
576
    $nids = entity_get_id_by_uuid('node', array($node->uuid));
577
    if (!empty($nids[$node->uuid])) {
578
      $existing = variable_get('node_export_existing', 'new');
579
      switch ($existing) {
580
        case 'new':
581
          $node->is_new = TRUE;
582
          unset($node->uuid);
583
          break;
584
        case 'revision':
585
          $node->nid = $nids[$node->uuid];
586
          $node->is_new = FALSE;
587
          $node->revision = 1;
588
          break;
589
        case 'skip':
590
          $save = FALSE;
591
          break;
592
      }
593
    }
594

    
595
    // Let other modules do special fixing up.
596
    drupal_alter('node_export_node_import', $node, $original_node, $save);
597

    
598
    if ($save) {
599
      node_export_save($node);
600
      $new_nodes[$node->nid] = $node;
601
      $messages[] = $msg_t("Imported node !nid: !node", array('!nid' => $node->nid, '!node' => l($node->title, 'node/' . $node->nid)));
602
      $count++;
603
    }
604
    else {
605
      $new_nodes[] = $node;
606
    }
607
  }
608

    
609
  if ($save) {
610
    drupal_alter('node_export_after_import', $new_nodes, $used_format, $save);
611
    $messages[] = $msg_t("!count of !total nodes were imported.  Some values may have been reset depending on Node export's configuration.", array('!total' => $total, '!count' => $count));
612

    
613
    // Clear the page and block caches.
614
    cache_clear_all();
615

    
616
    // Nodes were saved, so return the nids.
617
    return array(
618
      'success' => TRUE,
619
      'output' => $messages,
620
      'nids' => array_keys($new_nodes),
621
      'format' => $used_format,
622
    );
623
  }
624
  else {
625
    // We didn't save, so return full nodes.
626
    return array(
627
      'success' => TRUE,
628
      'output' => $messages,
629
      'nodes' => $new_nodes,
630
      'format' => $used_format,
631
    );
632
  }
633

    
634
}
635

    
636

    
637
/**
638
 * Save a node object into the database.
639
 *
640
 * $node->changed is not forced like in node_save().
641
 *
642
 * A modified version of node_save().
643
 */
644
function node_export_save(&$node) {
645
  $transaction = db_transaction();
646

    
647
  try {
648
    // Load the stored entity, if any.
649
    if (!empty($node->nid) && !isset($node->original)) {
650
      $node->original = entity_load_unchanged('node', $node->nid);
651
    }
652

    
653
    field_attach_presave('node', $node);
654
    global $user;
655

    
656
    // Determine if we will be inserting a new node.
657
    if (!isset($node->is_new)) {
658
      $node->is_new = empty($node->nid);
659
    }
660

    
661
    // Set the timestamp fields.
662
    if (empty($node->created)) {
663
      $node->created = REQUEST_TIME;
664
    }
665

    
666
    // The update of the changed value is forced in the original node_save().
667
    if (empty($node->changed)) {
668
      $node->changed = REQUEST_TIME;
669
    }
670

    
671
    $node->timestamp = REQUEST_TIME;
672
    $update_node = TRUE;
673

    
674
    // Let modules modify the node before it is saved to the database.
675
    module_invoke_all('node_presave', $node);
676

    
677
    if ($node->is_new || !empty($node->revision)) {
678
      // When inserting either a new node or a new node revision, $node->log
679
      // must be set because {node_revision}.log is a text column and therefore
680
      // cannot have a default value. However, it might not be set at this
681
      // point (for example, if the user submitting a node form does not have
682
      // permission to create revisions), so we ensure that it is at least an
683
      // empty string in that case.
684
      // @todo: Make the {node_revision}.log column nullable so that we can
685
      // remove this check.
686
      if (!isset($node->log)) {
687
        $node->log = '';
688
      }
689
    }
690
    elseif (empty($node->log)) {
691
      // If we are updating an existing node without adding a new revision, we
692
      // need to make sure $node->log is unset whenever it is empty. As long as
693
      // $node->log is unset, drupal_write_record() will not attempt to update
694
      // the existing database column when re-saving the revision; therefore,
695
      // this code allows us to avoid clobbering an existing log entry with an
696
      // empty one.
697
      unset($node->log);
698
    }
699

    
700
    // When saving a new node revision, unset any existing $node->vid so as to
701
    // ensure that a new revision will actually be created, then store the old
702
    // revision ID in a separate property for use by node hook implementations.
703
    if (!$node->is_new && !empty($node->revision) && $node->vid) {
704
      $node->old_vid = $node->vid;
705
      unset($node->vid);
706
    }
707

    
708
    // Save the node and node revision.
709
    if ($node->is_new) {
710
      // For new nodes, save new records for both the node itself and the node
711
      // revision.
712
      drupal_write_record('node', $node);
713
      _node_save_revision($node, $user->uid);
714
      $op = 'insert';
715
    }
716
    else {
717
      // For existing nodes, update the node record which matches the value of
718
      // $node->nid.
719
      drupal_write_record('node', $node, 'nid');
720
      // Then, if a new node revision was requested, save a new record for
721
      // that; otherwise, update the node revision record which matches the
722
      // value of $node->vid.
723
      if (!empty($node->revision)) {
724
        _node_save_revision($node, $user->uid);
725
      }
726
      else {
727
        _node_save_revision($node, $user->uid, 'vid');
728
        $update_node = FALSE;
729
      }
730
      $op = 'update';
731
    }
732
    if ($update_node) {
733
      db_update('node')
734
        ->fields(array('vid' => $node->vid))
735
        ->condition('nid', $node->nid)
736
        ->execute();
737
    }
738

    
739
    // Call the node specific callback (if any). This can be
740
    // node_invoke($node, 'insert') or
741
    // node_invoke($node, 'update').
742
    node_invoke($node, $op);
743

    
744
    // Save fields.
745
    $function = "field_attach_$op";
746
    $function('node', $node);
747

    
748
    module_invoke_all('node_' . $op, $node);
749
    module_invoke_all('entity_' . $op, $node, 'node');
750

    
751
    // Update the node access table for this node. There's no need to delete
752
    // existing records if the node is new.
753
    $delete = $op == 'update';
754
    node_access_acquire_grants($node, $delete);
755

    
756
    // Clear internal properties.
757
    unset($node->is_new);
758
    unset($node->original);
759
    // Clear the static loading cache.
760
    entity_get_controller('node')->resetCache(array($node->nid));
761

    
762
    // Ignore slave server temporarily to give time for the
763
    // saved node to be propagated to the slave.
764
    db_ignore_slave();
765
  }
766
  catch (Exception $e) {
767
    $transaction->rollback();
768
    watchdog_exception('node', $e);
769
    throw $e;
770
  }
771
}
772

    
773
/**
774
 * Prepare a clone of the node during import.
775
 */
776
function node_export_node_clone($original_node) {
777
  global $user;
778

    
779
  $node = clone($original_node);
780

    
781
  $node->nid = NULL;
782
  $node->vid = NULL;
783

    
784
  if (variable_get('node_export_reset_author_' . $node->type, TRUE)) {
785
    $node->name = !empty($user->name) ? $user->name : (!empty($user->uid) ? NULL : variable_get('anonymous', t('Anonymous')));
786
    $node->uid = $user->uid;
787
  }
788

    
789
  if (variable_get('node_export_reset_created_' . $node->type, TRUE)) {
790
    $node->created = NULL;
791
  }
792

    
793
  if (variable_get('node_export_reset_changed_' . $node->type, TRUE)) {
794
    $node->changed = NULL;
795
  }
796

    
797
  if (variable_get('node_export_reset_revision_timestamp_'. $node->type, TRUE)) {
798
    $node->revision_timestamp = NULL;
799
  }
800

    
801
  if (variable_get('node_export_reset_last_comment_timestamp_'. $node->type, TRUE)) {
802
    $node->last_comment_timestamp = NULL;
803
  }
804

    
805
  if (variable_get('node_export_reset_menu_' . $node->type, TRUE)) {
806
    $node->menu = NULL;
807
  }
808

    
809
  if (variable_get('node_export_reset_path_' . $node->type, TRUE)) {
810
    $node->path = NULL;
811
  }
812
  else {
813
    if (is_array($node->path) && isset($node->path['pid'])) {
814
      unset($node->path['pid']);
815
    }
816
    if (module_exists('pathauto')) {
817
      // Prevent pathauto from creating a new path alias.
818
      $node->path['pathauto'] = FALSE;
819
    }
820
  }
821

    
822
  if (variable_get('node_export_reset_book_mlid_' . $node->type, TRUE) && isset($node->book['mlid'])) {
823
    $node->book['mlid'] = NULL;
824
  }
825

    
826
  // @todo - is this still needed?
827
  $node->files = array();
828

    
829
  if (variable_get('node_export_reset_status_' . $node->type, FALSE)) {
830
    $node->status = FALSE;
831
  }
832

    
833
  if (variable_get('node_export_reset_promote_' . $node->type, FALSE)) {
834
    $node->promote = FALSE;
835
  }
836

    
837
  if (variable_get('node_export_reset_sticky_' . $node->type, FALSE)) {
838
    $node->sticky = FALSE;
839
  }
840

    
841
  return $node;
842

    
843
}
844

    
845
/**
846
 * Create a new menu entry with title, parent and weight exported from
847
 * another nodes menu. Returns NULL if the node has no menu title.
848
 */
849
function node_export_get_menu($node) {
850

    
851
  // This will fetch the existing menu item if the node had one.
852
  module_invoke_all('node_prepare', $node);
853

    
854
  $type = $node->type;
855

    
856
  // Only keep the values we care about.
857
  if (!empty($node->menu['mlid'])) {
858

    
859
    // Store a copy of the old menu
860
    $old_menu = $node->menu;
861

    
862
    // Now fetch the defaults for a new menu entry.
863
    $node = new stdClass;
864
    $node->type = $type;
865
    //module_invoke_all('node_prepare', $node);
866

    
867
    node_object_prepare($node);
868

    
869
    // Make a list of values to attempt to copy.
870
    $menu_fields = array(
871
      'link_title',
872
      'plid',
873
      'menu_name',
874
      'weight',
875
      'hidden',
876
      'expanded',
877
      'has_children',
878
    );
879

    
880
    // Copy those fields from the old menu over the new menu defaults.
881
    foreach ($menu_fields as $menu_field) {
882
      $node->menu[$menu_field] = $old_menu[$menu_field];
883
    }
884

    
885
    // Copy the menu description from the old menu.
886
    // Issue #1287300.
887
    if (isset($old_menu['options']['attributes']['title'])) {
888
      $node->menu['description'] = $old_menu['options']['attributes']['title'];
889
    }
890
    else {
891
      $node->menu['description'] = '';
892
    }
893

    
894
    // Ensure menu will be created during node import.
895
    // Issue #1139120.
896
    $node->menu['enabled'] = 1;
897

    
898
    // Return the menu.
899
    return $node->menu;
900
  }
901

    
902
}
903

    
904
/**
905
 * Remove recursion problem from an object or array.
906
 */
907
function node_export_remove_recursion($o) {
908
  static $replace;
909
  if (!isset($replace)) {
910
    $replace = create_function(
911
      '$m',
912
      '$r="\x00{$m[1]}ecursion_export_node_";return \'s:\'.strlen($r.$m[2]).\':"\'.$r.$m[2].\'";\';'
913
    );
914
  }
915
  if (is_array($o) || is_object($o)) {
916
    $re = '#(r|R):([0-9]+);#';
917
    $serialize = serialize($o);
918
    if (preg_match($re, $serialize)) {
919
      $last = $pos = 0;
920
      while (false !== ($pos = strpos($serialize, 's:', $pos))) {
921
        $chunk = substr($serialize, $last, $pos - $last);
922
        if (preg_match($re, $chunk)) {
923
          $length = strlen($chunk);
924
          $chunk = preg_replace_callback($re, $replace, $chunk);
925
          $serialize = substr($serialize, 0, $last) . $chunk . substr($serialize, $last + ($pos - $last));
926
          $pos += strlen($chunk) - $length;
927
        }
928
        $pos += 2;
929
        $last = strpos($serialize, ':', $pos);
930
        $length = substr($serialize, $pos, $last - $pos);
931
        $last += 4 + $length;
932
        $pos = $last;
933
      }
934
      $serialize = substr($serialize, 0, $last) . preg_replace_callback($re, $replace, substr($serialize, $last));
935
      $o = unserialize($serialize);
936
    }
937
  }
938
  return $o;
939
}
940

    
941
/**
942
 * Restore recursion to an object or array.
943
 */
944
function node_export_restore_recursion($o) {
945
  return unserialize(
946
    preg_replace(
947
      '#s:[0-9]+:"\x00(r|R)ecursion_export_node_([0-9]+)";#',
948
      '\1:\2;',
949
      serialize($o)
950
    )
951
  );
952
}
953

    
954
/**
955
 * Get a list of possible format handlers (other than the default).
956
 *
957
 * @return
958
 *   An array of format handlers from hook implementations.
959
 * @see hook_node_export_format_handlers()
960
 */
961
function node_export_format_handlers() {
962
  module_load_include('inc', 'node_export', 'node_export.formats');
963
  $format_handlers = &drupal_static(__FUNCTION__);
964
  if (empty($format_handlers)) {
965
    $format_handlers = module_invoke_all('node_export_format_handlers');
966
  }
967
  return $format_handlers;
968
}
969

    
970

    
971
/**
972
 * Handle exporting file fields.
973
 */
974
function node_export_file_field_export(&$node, $original_node) {
975
  $types = array_filter(variable_get('node_export_file_types', array()));
976
  if (in_array($node->type, $types)) {
977
    $assets_path = variable_get('node_export_file_assets_path', '');
978
    $export_mode = variable_get('node_export_file_mode', 'inline');
979

    
980
    switch ($export_mode) {
981
      case 'local':
982
        $export_var = 'node_export_file_path';
983
        break;
984
      case 'remote':
985
        $export_var = 'node_export_file_url';
986
        break;
987
      default:
988
      case 'inline':
989
        $export_var = 'node_export_file_data';
990
        break;
991
    }
992

    
993
    // If files are supposed to be copied to the assets path.
994
    if ($export_mode == 'local' && $assets_path) {
995
      // Ensure the assets path is created
996
      if (!is_dir($assets_path) && mkdir($assets_path, 0777, TRUE) == FALSE) {
997
        drupal_set_message(t("Could not create assets path! '!path'", array('!path' => $assets_path)), 'error');
998
        // Don't continue if the assets path is not ready
999
        return;
1000
      }
1001

    
1002
      // Ensure it is writable
1003
      if (!is_writable($assets_path)) {
1004
        drupal_set_message(t("Assets path is not writable! '!path'", array('!path' => $assets_path)), 'error');
1005
        // Don't continue if the assets path is not ready
1006
        return;
1007
      }
1008
    }
1009

    
1010
    // get all fields from this node type
1011
    $fields = field_info_instances('node', $node->type);
1012
    foreach($fields as $field_instance) {
1013

    
1014
      // load field infos to check the type
1015
      $field = &$node->{$field_instance['field_name']};
1016
      $info = field_info_field($field_instance['field_name']);
1017

    
1018
      $supported_fields = array_map('trim', explode(',', variable_get('node_export_file_supported_fields', 'file, image')));
1019

    
1020
      // check if this field should implement file import/export system
1021
      if (in_array($info['type'], $supported_fields)) {
1022

    
1023
        // we need to loop into each language because i18n translation can build
1024
        // fields with different language than the node one.
1025
        foreach($field as $language => $files) {
1026
          if (is_array($files)) {
1027
            foreach($files as $i => $file) {
1028

    
1029
              // convert file to array to stay into the default node_export_file format
1030
              $file = (object) $file;
1031

    
1032
              // Check the file
1033
              if (!isset($file->uri) || !is_file($file->uri)) {
1034
                drupal_set_message(t("File field found on node, but file doesn't exist on disk? '!path'", array('!path' => $file->uri)), 'error');
1035
                continue;
1036
              }
1037

    
1038
              if ($export_mode == 'local') {
1039
                if ($assets_path) {
1040
                  $export_data = $assets_path . '/' . basename($file->uri);
1041
                  if (!copy($file->uri, $export_data)) {
1042
                    drupal_set_message(t("Export file error, could not copy '%filepath' to '%exportpath'.", array('%filepath' => $file->uri, '%exportpath' => $export_data)), 'error');
1043
                    return FALSE;
1044
                  }
1045
                }
1046
                else {
1047
                  $export_data = $file->uri;
1048
                }
1049
              }
1050
              // Remote export mode
1051
              elseif ($export_mode == 'remote') {
1052
                $export_data = url($file->uri, array('absolute' => TRUE));
1053
              }
1054
              // Default is 'inline' export mode
1055
              else {
1056
                $export_data = base64_encode(file_get_contents($file->uri));
1057
              }
1058

    
1059
              // build the field again, and remove fid to be sure that imported node
1060
              // will rebuild the file again, or keep an existing one with a different fid
1061
              $field[$language][$i]['fid'] = NULL;
1062
              $field[$language][$i][$export_var] = $export_data;
1063

    
1064
            }
1065
          }
1066
        }
1067
      }
1068
    }
1069
  }
1070
}
1071

    
1072
/**
1073
 * Handle importing file fields.
1074
 */
1075
function node_export_file_field_import(&$node, $original_node) {
1076
  // Get all fields from this node type.
1077
  $fields = field_info_instances('node', $node->type);
1078
  foreach($fields as $field_instance) {
1079

    
1080
    // Load field info to check the type.
1081
    $field = &$node->{$field_instance['field_name']};
1082
    $info = field_info_field($field_instance['field_name']);
1083

    
1084
    $supported_fields = array_map('trim', explode(',', variable_get('node_export_file_supported_fields', 'file, image')));
1085

    
1086
    // Check if this field should implement file import/export system.
1087
    if (in_array($info['type'], $supported_fields)) {
1088

    
1089
      // We need to loop into each language because i18n translation can build
1090
      // fields with different language than the node one.
1091
      foreach($field as $language => $files) {
1092
        if (is_array($files)) {
1093
          foreach($files as $i => $file) {
1094

    
1095
            // Convert file to array to stay into the default node_export_file format.
1096
            $file = (object)$file;
1097

    
1098
            $result = _node_export_file_field_import_file($file);
1099
            // The file was saved successfully, update the file field (by reference).
1100
            if ($result == TRUE && isset($file->fid)) {
1101
              $field[$language][$i] = (array)$file;
1102
            }
1103

    
1104
          }
1105
        }
1106
      }
1107
    }
1108
  }
1109
}
1110

    
1111
/**
1112
 * Detects remote and local file exports and imports accordingly.
1113
 *
1114
 * @param &$file
1115
 *   The file, passed by reference.
1116
 * @return TRUE or FALSE
1117
 *   Depending on success or failure.  On success the $file object will
1118
 *   have a valid $file->fid attribute.
1119
 */
1120
function _node_export_file_field_import_file(&$file) {
1121
  // This is here for historical reasons to support older exports.  It can be
1122
  // removed in the next major version.
1123
  $file->uri = strtr($file->uri, array('#FILES_DIRECTORY_PATH#' => 'public:/'));
1124

    
1125
  // The file is already in the right location AND either the
1126
  // node_export_file_path is not set or the node_export_file_path and filepath
1127
  // contain the same file
1128
  if (is_file($file->uri) &&
1129
    (
1130
      (!isset($file->node_export_file_path) || !is_file($file->node_export_file_path)) ||
1131
      (
1132
        is_file($file->node_export_file_path) &&
1133
        filesize($file->uri) == filesize($file->node_export_file_path) &&
1134
        strtoupper(dechex(crc32(file_get_contents($file->uri)))) ==
1135
          strtoupper(dechex(crc32(file_get_contents($file->node_export_file_path))))
1136
      )
1137
    )
1138
  ) {
1139
    // Keep existing file if it exists already at this uri (see also #1023254)
1140
    // Issue #1058750.
1141
    $query = db_select('file_managed', 'f')
1142
        ->fields('f', array('fid'))
1143
        ->condition('uri', $file->uri)
1144
        ->execute()
1145
        ->fetchCol();
1146

    
1147
    if (!empty($query)) {
1148
      watchdog('node_export', 'kept existing managed file at uri "%uri"', array('%uri' => $file->uri), WATCHDOG_NOTICE);
1149
      $file = file_load(array_shift($query));
1150
    }
1151

    
1152
    $file = file_save($file);
1153
  }
1154
  elseif (isset($file->node_export_file_data)) {
1155
    $directory = drupal_dirname($file->uri);
1156
    if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
1157
      if (file_put_contents($file->uri, base64_decode($file->node_export_file_data))) {
1158
        $file = file_save($file);
1159
      }
1160
    }
1161
  }
1162
  // The file is in a local location, move it to the
1163
  // destination then finish the save
1164
  elseif (isset($file->node_export_file_path) && is_file($file->node_export_file_path)) {
1165
    $directory = drupal_dirname($file->uri);
1166
    if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
1167
      // The $file->node_export_file_path is passed to reference, and modified
1168
      // by file_unmanaged_copy().  Making a copy to avoid tainting the original.
1169
      $node_export_file_path = $file->node_export_file_path;
1170
      file_unmanaged_copy($node_export_file_path, $directory, FILE_EXISTS_REPLACE);
1171

    
1172
      // At this point the $file->node_export_file_path will contain the
1173
      // destination of the copied file
1174
      //$file->uri = $node_export_file_path;
1175
      $file = file_save($file);
1176
    }
1177
  }
1178
  // The file is in a remote location, attempt to download it
1179
  elseif (isset($file->node_export_file_url)) {
1180
    // Need time to do the download
1181
    ini_set('max_execution_time', 900);
1182

    
1183
    $temp_path = file_directory_temp() . '/' . md5(mt_rand()) . '.txt';
1184
    if (($source = fopen($file->node_export_file_url, 'r')) == FALSE) {
1185
      drupal_set_message(t("Could not open '@file' for reading.", array('@file' => $file->node_export_file_url)));
1186
      return FALSE;
1187
    }
1188
    elseif (($dest = fopen($temp_path, 'w')) == FALSE) {
1189
      drupal_set_message(t("Could not open '@file' for writing.", array('@file' => $file->uri)));
1190
      return FALSE;
1191
    }
1192
    else {
1193
      // PHP5 specific, downloads the file and does buffering
1194
      // automatically.
1195
      $bytes_read = @stream_copy_to_stream($source, $dest);
1196

    
1197
      // Flush all buffers and wipe the file statistics cache
1198
      @fflush($source);
1199
      @fflush($dest);
1200
      clearstatcache();
1201

    
1202
      if ($bytes_read != filesize($temp_path)) {
1203
        drupal_set_message(t("Remote export '!url' could not be fully downloaded, '@file' to temporary location '!temp'.", array('!url' => $file->node_export_file_url, '@file' => $file->uri, '!temp' => $temp_path)));
1204
        return FALSE;
1205
      }
1206
      // File was downloaded successfully!
1207
      else {
1208
        if (!@copy($temp_path, $file->uri)) {
1209
          unlink($temp_path);
1210
          drupal_set_message(t("Could not move temporary file '@temp' to '@file'.", array('@temp' => $temp_path, '@file' => $file->uri)));
1211
          return FALSE;
1212
        }
1213

    
1214
        unlink($temp_path);
1215
        $file->filesize = filesize($file->uri);
1216
        $file->filemime = file_get_mimetype($file->uri);
1217
      }
1218
    }
1219

    
1220
    fclose($source);
1221
    fclose($dest);
1222

    
1223
    $file = file_save($file);
1224
  }
1225
  // Unknown error
1226
  else {
1227
    drupal_set_message(t("Unknown error occurred attempting to import file: @filepath", array('@filepath' => $file->uri)), 'error');
1228
    return FALSE;
1229
  }
1230

    
1231
  return TRUE;
1232
}
1233

    
1234
// Remove once http://drupal.org/node/858274 is resolved.
1235
if (!function_exists('uuid_set_uuid')) {
1236
  /**
1237
   * API function to set the UUID of an object based on its serial ID.
1238
   *
1239
   * @param $table
1240
   *   Base table of the object. Currently, one of node, revision_revisions,
1241
   *   users, vocabulary or term_data.
1242
   * @param $key
1243
   *   The name of the serial ID column.
1244
   * @param $serial_id
1245
   *   The serial ID of the object.
1246
   * @param $uuid
1247
   *   Optional UUID.  If omitted, a UUID will be generated.
1248
   * @return
1249
   *   The UUID on success, FALSE if the uuid provided is not valid.
1250
   */
1251
  function uuid_set_uuid($table, $key, $serial_id, $uuid = FALSE) {
1252
    if (empty($uuid)) {
1253
      $uuid = uuid_generate();
1254
    }
1255

    
1256
    if (!uuid_is_valid($uuid)) {
1257
      return FALSE;
1258
    }
1259

    
1260
    $query = db_query("UPDATE {" . $table . "} SET uuid = :uuid WHERE " . $key . " = :id", array(':uuid' => $uuid, ':id' => $serial_id));
1261
    /*
1262
    if (!$query->rowCount()) {
1263
      @db_query("INSERT INTO {" . $table . "} (" . $key . ", uuid) VALUES (:id, :uuid)", array(':uuid' => $uuid, ':id' => $serial_id));
1264
    }
1265
    */
1266

    
1267
    return $uuid;
1268
  }
1269
}
1270

    
1271
// Remove once http://drupal.org/node/858274 is resolved.
1272
if (!function_exists('uuid_get_uuid')) {
1273
  /**
1274
   * API function to get the UUID of an object based on its serial ID.
1275
   *
1276
   * @param $entity_type
1277
   *   The entity type.
1278
   * @param $key
1279
   *   The name of the serial ID column.
1280
   * @param $id
1281
   *   The serial ID of the object.
1282
   * @return
1283
   *   The UUID of the object, or FALSE if not found.
1284
   */
1285
  function uuid_get_uuid($entity_type, $key, $id) {
1286
    $supported = uuid_get_core_entity_info();
1287
    if (!isset($supported[$entity_type])) {
1288
      return FALSE;
1289
    }
1290
    $entity_info = entity_get_info($entity_type);
1291
    $table = $entity_info['base table'];
1292
    return db_query("SELECT uuid FROM {" . $table . "} WHERE " . $key . " = :id", array(':id' => $id))->fetchField();
1293
  }
1294
}