node.admin.inc 6.08 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Content administration and module settings user interface.
6 7
 */

8
use Drupal\node\NodeInterface;
9
use Drupal\node\Entity\Node;
10

11
/**
12
 * Updates all nodes in the passed-in array with the passed-in field values.
13
 *
14 15 16
 * IMPORTANT NOTE: This function is intended to work when called from a form
 * submission handler. Calling it outside of the form submission process may not
 * work correctly.
17 18
 *
 * @param array $nodes
19
 *   Array of node nids or nodes to update.
20
 * @param array $updates
21 22
 *   Array of key/value pairs with node field names and the value to update that
 *   field to.
23 24 25
 * @param string $langcode
 *   (optional) The language updates should be applied to. If none is specified
 *   all available languages are processed.
26 27 28
 * @param bool $load
 *   (optional) TRUE if $nodes contains an array of node IDs to be loaded, FALSE
 *   if it contains fully loaded nodes. Defaults to FALSE.
29 30 31
 * @param bool $revisions
 *   (optional) TRUE if $nodes contains an array of revision IDs instead of
 *   node IDs. Defaults to FALSE; will be ignored if $load is FALSE.
32
 */
33
function node_mass_update(array $nodes, array $updates, $langcode = NULL, $load = FALSE, $revisions = FALSE) {
34 35 36 37 38
  // We use batch processing to prevent timeout when updating a large number
  // of nodes.
  if (count($nodes) > 10) {
    $batch = array(
      'operations' => array(
39
        array('_node_mass_update_batch_process', array($nodes, $updates, $langcode, $load, $revisions))
40 41 42 43 44 45 46 47 48
      ),
      'finished' => '_node_mass_update_batch_finished',
      'title' => t('Processing'),
      // We use a single multi-pass operation, so the default
      // 'Remaining x of y operations' message will be confusing here.
      'progress_message' => '',
      'error_message' => t('The update has encountered an error.'),
      // The operations do not live in the .module file, so we need to
      // tell the batch engine which file to load before calling them.
49
      'file' => drupal_get_path('module', 'node') . '/node.admin.inc',
50 51 52 53
    );
    batch_set($batch);
  }
  else {
54
    if ($load && !$revisions) {
55
      $nodes = Node::loadMultiple($nodes);
56 57
    }
    foreach ($nodes as $node) {
58 59 60
      if ($load && $revisions) {
        $node = entity_revision_load('node', $node);
      }
61
      _node_mass_update_helper($node, $updates, $langcode);
62 63 64 65 66 67
    }
    drupal_set_message(t('The update has been performed.'));
  }
}

/**
68 69
 * Updates individual nodes when fewer than 10 are queued.
 *
70 71 72
 * @param \Drupal\node\NodeInterface $node
 *   A node to update.
 * @param array $updates
73
 *   Associative array of updates.
74 75 76
 * @param string $langcode
 *   (optional) The language updates should be applied to. If none is specified
 *   all available languages are processed.
77
 *
78
 * @return \Drupal\node\NodeInterface
79 80
 *   An updated node object.
 *
81
 * @see node_mass_update()
82
 */
83
function _node_mass_update_helper(NodeInterface $node, array $updates, $langcode = NULL) {
84
  $langcodes = isset($langcode) ? array($langcode) : array_keys($node->getTranslationLanguages());
85 86
  // For efficiency manually save the original node before applying any changes.
  $node->original = clone $node;
87 88
  foreach ($langcodes as $langcode) {
    foreach ($updates as $name => $value) {
89
      $node->getTranslation($langcode)->$name = $value;
90
    }
91
  }
92
  $node->save();
93 94 95 96
  return $node;
}

/**
97 98
 * Implements callback_batch_operation().
 *
99
 * Executes a batch operation for node_mass_update().
100 101 102 103 104
 *
 * @param array $nodes
 *   An array of node IDs.
 * @param array $updates
 *   Associative array of updates.
105 106 107
 * @param bool $load
 *   TRUE if $nodes contains an array of node IDs to be loaded, FALSE if it
 *   contains fully loaded nodes.
108 109 110
 * @param bool $revisions
 *   (optional) TRUE if $nodes contains an array of revision IDs instead of
 *   node IDs. Defaults to FALSE; will be ignored if $load is FALSE.
111
 * @param array|\ArrayAccess $context.
112
 *   An array of contextual key/values.
113
 */
114
function _node_mass_update_batch_process(array $nodes, array $updates, $load, $revisions, &$context) {
115 116 117 118 119 120 121 122 123 124
  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($nodes);
    $context['sandbox']['nodes'] = $nodes;
  }

  // Process nodes by groups of 5.
  $count = min(5, count($context['sandbox']['nodes']));
  for ($i = 1; $i <= $count; $i++) {
    // For each nid, load the node, reset the values, and save it.
125 126
    $node = array_shift($context['sandbox']['nodes']);
    if ($load) {
127
      $node = $revisions ?
128
        entity_revision_load('node', $node) : Node::load($node);
129 130
    }
    $node = _node_mass_update_helper($node, $updates);
131 132

    // Store result for post-processing in the finished callback.
133
    $context['results'][] = \Drupal::l($node->label(), $node->urlInfo());
134 135 136 137 138 139 140 141 142 143 144 145 146

    // Update our progress information.
    $context['sandbox']['progress']++;
  }

  // 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'];
  }
}

/**
147 148
 * Implements callback_batch_finished().
 *
149
 * Reports the 'finished' status of batch operation for node_mass_update().
150 151 152 153
 *
 * @param bool $success
 *   A boolean indicating whether the batch mass update operation successfully
 *   concluded.
154 155
 * @param string[] $results
 *   An array of rendered links to nodes updated via the batch mode process.
156 157
 * @param array $operations
 *   An array of function calls (not used in this function).
158 159
 *
 * @see _node_mass_update_batch_process()
160 161 162 163 164 165 166
 */
function _node_mass_update_batch_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('The update has been performed.'));
  }
  else {
    drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
167
    $message = \Drupal::translation()->formatPlural(count($results), '1 item successfully processed:', '@count items successfully processed:');
168 169 170 171 172
    $item_list = array(
      '#theme' => 'item_list',
      '#items' => $results,
    );
    $message .= drupal_render($item_list);
173 174 175
    drupal_set_message($message);
  }
}