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

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

8
use Drupal\Core\Database\Query\SelectInterface;
9
use Drupal\Core\Language\Language;
10

11
/**
12 13
 * Page callback: Form constructor for the permission rebuild confirmation form.
 *
14 15 16
 * @return array
 *   An array as expected by drupal_render().
 *
17
 * @see node_configure_rebuild_confirm_submit()
18
 * @see node_menu()
19
 * @ingroup forms
20 21
 */
function node_configure_rebuild_confirm() {
22
  return confirm_form(array(), t('Are you sure you want to rebuild the permissions on site content?'),
23
                  'admin/reports/status', t('This action rebuilds all permissions on site content, and may be a lengthy process. This action cannot be undone.'), t('Rebuild permissions'), t('Cancel'));
24 25 26
}

/**
27
 * Form submission handler for node_configure_rebuild_confirm().
28
 */
29
function node_configure_rebuild_confirm_submit($form, &$form_state) {
30
  node_access_rebuild(TRUE);
31
  $form_state['redirect'] = 'admin/reports/status';
32 33 34
}

/**
35 36 37
 * Lists node administration filters that can be applied.
 *
 * @return
38
 *   An associative array of filters.
39 40 41
 */
function node_filters() {
  // Regular filters
42 43 44
  $filters['status'] = array(
    'title' => t('status'),
    'options' => array(
45
      '[any]' => t('any'),
46 47 48 49 50 51 52
      'status-1' => t('published'),
      'status-0' => t('not published'),
      'promote-1' => t('promoted'),
      'promote-0' => t('not promoted'),
      'sticky-1' => t('sticky'),
      'sticky-0' => t('not sticky'),
    ),
53 54 55
  );
  // Include translation states if we have this module enabled
  if (module_exists('translation')) {
56 57 58 59
    $filters['status']['options'] += array(
      'translate-0' => t('Up to date translation'),
      'translate-1' => t('Outdated translation'),
    );
60 61
  }

62 63 64 65 66 67
  $filters['type'] = array(
    'title' => t('type'),
    'options' => array(
      '[any]' => t('any'),
    ) + node_type_get_names(),
  );
68

69
  // Language filter if language support is present.
70
  if (language_multilingual()) {
71
    $languages = language_list(Language::STATE_ALL);
72
    foreach ($languages as $langcode => $language) {
73 74
      // Make locked languages appear special in the list.
      $language_options[$langcode] = $language->locked ? t('- @name -', array('@name' => $language->name)) : $language->name;
75
    }
76
    $filters['langcode'] = array(
77 78
      'title' => t('language'),
      'options' => array(
79
        '[any]' => t('- Any -'),
80
      ) + $language_options,
81
    );
82 83 84 85 86
  }
  return $filters;
}

/**
87
 * Applies filters for the node administration overview based on session.
88
 *
89
 * @param Drupal\Core\Database\Query\SelectInterface $query
90
 *   A SelectQuery to which the filters should be applied.
91
 */
92
function node_build_filter_query(SelectInterface $query) {
93
  // Build query
94 95
  $filter_data = isset($_SESSION['node_overview_filter']) ? $_SESSION['node_overview_filter'] : array();
  foreach ($filter_data as $index => $filter) {
96 97 98 99 100 101
    list($key, $value) = $filter;
    switch ($key) {
      case 'status':
        // Note: no exploitable hole as $key/$value have already been checked when submitted
        list($key, $value) = explode('-', $value, 2);
      case 'type':
102
      case 'langcode':
103
        $query->condition('n.' . $key, $value);
104
        break;
105 106 107 108 109
    }
  }
}

/**
110
 * Returns the node administration filters form array to node_admin_content().
111 112 113 114 115
 *
 * @see node_admin_nodes()
 * @see node_admin_nodes_submit()
 * @see node_admin_nodes_validate()
 * @see node_filter_form_submit()
116 117 118
 * @see node_multiple_delete_confirm()
 * @see node_multiple_delete_confirm_submit()
 *
119
 * @ingroup forms
120 121
 */
function node_filter_form() {
122
  $session = isset($_SESSION['node_overview_filter']) ? $_SESSION['node_overview_filter'] : array();
123 124 125
  $filters = node_filters();

  $i = 0;
126
  $form['filters'] = array(
127
    '#type' => 'details',
128
    '#title' => t('Show only items where'),
129
    '#theme' => 'exposed_filters__node',
130 131 132
  );
  foreach ($session as $filter) {
    list($type, $value) = $filter;
133
    if ($type == 'term') {
134
      // Load term name from DB rather than search and parse options array.
135
      $value = module_invoke('taxonomy', 'term_load', $value);
136 137
      $value = $value->name;
    }
138
    elseif ($type == 'langcode') {
139
      $value = language_name($value);
140 141 142 143
    }
    else {
      $value = $filters[$type]['options'][$value];
    }
144
    $t_args = array('%property' => $filters[$type]['title'], '%value' => $value);
145
    if ($i++) {
146
      $form['filters']['current'][] = array('#markup' => t('and where %property is %value', $t_args));
147 148
    }
    else {
149
      $form['filters']['current'][] = array('#markup' => t('where %property is %value', $t_args));
150
    }
151
    if (in_array($type, array('type', 'langcode'))) {
152 153 154 155 156
      // Remove the option if it is already being filtered on.
      unset($filters[$type]);
    }
  }

157 158 159 160 161 162 163 164 165
  $form['filters']['status'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('clearfix')),
    '#prefix' => ($i ? '<div class="additional-filters">' . t('and where') . '</div>' : ''),
  );
  $form['filters']['status']['filters'] = array(
    '#type' => 'container',
    '#attributes' => array('class' => array('filters')),
  );
166
  foreach ($filters as $key => $filter) {
167
    $form['filters']['status']['filters'][$key] = array(
168 169 170 171 172
      '#type' => 'select',
      '#options' => $filter['options'],
      '#title' => $filter['title'],
      '#default_value' => '[any]',
    );
173 174
  }

175
  $form['filters']['status']['actions'] = array(
176 177
    '#type' => 'actions',
    '#attributes' => array('class' => array('container-inline')),
178
  );
179 180 181 182
  $form['filters']['status']['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => count($session) ? t('Refine') : t('Filter'),
  );
183
  if (count($session)) {
184 185
    $form['filters']['status']['actions']['undo'] = array('#type' => 'submit', '#value' => t('Undo'));
    $form['filters']['status']['actions']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
186 187
  }

188
  $form['#attached']['library'][] = array('system', 'drupal.form');
189

190 191 192 193
  return $form;
}

/**
194 195 196 197 198 199 200
 * Form submission handler for node_filter_form().
 *
 * @see node_admin_content()
 * @see node_admin_nodes()
 * @see node_admin_nodes_submit()
 * @see node_admin_nodes_validate()
 * @see node_filter_form()
201 202
 * @see node_multiple_delete_confirm()
 * @see node_multiple_delete_confirm_submit()
203 204 205 206 207 208
 */
function node_filter_form_submit($form, &$form_state) {
  $filters = node_filters();
  switch ($form_state['values']['op']) {
    case t('Filter'):
    case t('Refine'):
209 210 211
      // Apply every filter that has a choice selected other than 'any'.
      foreach ($filters as $filter => $options) {
        if (isset($form_state['values'][$filter]) && $form_state['values'][$filter] != '[any]') {
212
          $_SESSION['node_overview_filter'][] = array($filter, $form_state['values'][$filter]);
213 214 215 216 217 218 219
        }
      }
      break;
    case t('Undo'):
      array_pop($_SESSION['node_overview_filter']);
      break;
    case t('Reset'):
220
      $_SESSION['node_overview_filter'] = array();
221 222 223 224
      break;
  }
}

225
/**
226
 * Updates all nodes in the passed-in array with the passed-in field values.
227
 *
228 229 230
 * 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.
231 232 233 234
 *
 * @param array $nodes
 *   Array of node nids to update.
 * @param array $updates
235 236
 *   Array of key/value pairs with node field names and the value to update that
 *   field to.
237 238 239
 * @param string $langcode
 *   (optional) The language updates should be applied to. If none is specified
 *   all available languages are processed.
240
 */
241
function node_mass_update($nodes, $updates, $langcode = NULL) {
242 243 244 245 246
  // We use batch processing to prevent timeout when updating a large number
  // of nodes.
  if (count($nodes) > 10) {
    $batch = array(
      'operations' => array(
247
        array('_node_mass_update_batch_process', array($nodes, $updates, $langcode))
248 249 250 251 252 253 254 255 256
      ),
      '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.
257
      'file' => drupal_get_path('module', 'node') . '/node.admin.inc',
258 259 260 261
    );
    batch_set($batch);
  }
  else {
262
    foreach ($nodes as $nid) {
263
      _node_mass_update_helper($nid, $updates, $langcode);
264 265 266 267 268 269
    }
    drupal_set_message(t('The update has been performed.'));
  }
}

/**
270 271 272 273 274 275
 * Updates individual nodes when fewer than 10 are queued.
 *
 * @param $nid
 *   ID of node to update.
 * @param $updates
 *   Associative array of updates.
276 277 278
 * @param string $langcode
 *   (optional) The language updates should be applied to. If none is specified
 *   all available languages are processed.
279
 *
280 281 282
 * @return object
 *   An updated node object.
 *
283
 * @see node_mass_update()
284
 */
285
function _node_mass_update_helper($nid, $updates, $langcode = NULL) {
286
  $node = node_load($nid, TRUE);
287
  $langcodes = isset($langcode) ? array($langcode) : array_keys($node->getTranslationLanguages());
288 289
  // For efficiency manually save the original node before applying any changes.
  $node->original = clone $node;
290 291 292 293
  foreach ($langcodes as $langcode) {
    foreach ($updates as $name => $value) {
      $node->getTranslation($langcode, FALSE)->$name = $value;
    }
294
  }
295
  $node->save();
296 297 298 299
  return $node;
}

/**
300
 * Executes a batch operation for node_mass_update().
301 302 303 304 305 306 307
 *
 * @param array $nodes
 *   An array of node IDs.
 * @param array $updates
 *   Associative array of updates.
 * @param array $context
 *   An array of contextual key/values.
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
 */
function _node_mass_update_batch_process($nodes, $updates, &$context) {
  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.
    $nid = array_shift($context['sandbox']['nodes']);
    $node = _node_mass_update_helper($nid, $updates);

    // Store result for post-processing in the finished callback.
324
    $context['results'][] = l($node->label(), 'node/' . $node->nid);
325 326 327 328 329 330 331 332 333 334 335 336 337

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

/**
338
 * Reports the 'finished' status of batch operation for node_mass_update().
339 340 341 342 343 344 345 346
 *
 * @param bool $success
 *   A boolean indicating whether the batch mass update operation successfully
 *   concluded.
 * @param int $results
 *   The number of nodes updated via the batch mode process.
 * @param array $operations
 *   An array of function calls (not used in this function).
347 348 349 350 351 352 353 354
 */
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');
    $message = format_plural(count($results), '1 item successfully processed:', '@count items successfully processed:');
355 356 357 358 359
    $item_list = array(
      '#theme' => 'item_list',
      '#items' => $results,
    );
    $message .= drupal_render($item_list);
360 361 362 363
    drupal_set_message($message);
  }
}

364
/**
365 366 367 368 369 370 371 372
 * Page callback: Form constructor for the content administration form.
 *
 * @see node_admin_nodes()
 * @see node_admin_nodes_submit()
 * @see node_admin_nodes_validate()
 * @see node_filter_form()
 * @see node_filter_form_submit()
 * @see node_menu()
373 374
 * @see node_multiple_delete_confirm()
 * @see node_multiple_delete_confirm_submit()
375
 * @ingroup forms
376
 */
377
function node_admin_content($form, $form_state) {
378
  if (isset($form_state['values']['operation']) && $form_state['values']['operation'] == 'delete') {
379
    return node_multiple_delete_confirm($form, $form_state, array_filter($form_state['values']['nodes']));
380
  }
381
  $form['filter'] = node_filter_form();
382
  $form['#submit'][] = 'node_filter_form_submit';
383
  $form['admin'] = node_admin_nodes();
384 385 386 387

  return $form;
}

388
/**
389 390 391 392 393
 * Returns the admin form object to node_admin_content().
 *
 * @see node_admin_nodes_submit()
 * @see node_filter_form()
 * @see node_filter_form_submit()
394 395 396
 * @see node_multiple_delete_confirm()
 * @see node_multiple_delete_confirm_submit()
 *
397
 * @ingroup forms
398
 */
399
function node_admin_nodes() {
400
  $admin_access = user_access('administer nodes');
401

402
  // Build the 'Update options' form.
403
  $form['options'] = array(
404
    '#type' => 'details',
405
    '#title' => t('Update options'),
406
    '#attributes' => array('class' => array('container-inline')),
407
    '#access' => $admin_access,
408 409
  );
  $options = array();
410 411 412
  $actions = entity_load_multiple_by_properties('action', array('type' => 'node'));
  foreach ($actions as $id => $action) {
    $options[$id] = $action->label();
413
  }
414 415
  $form['options']['operation'] = array(
    '#type' => 'select',
416
    '#title' => t('Action'),
417
    '#title_display' => 'invisible',
418 419 420
    '#options' => $options,
    '#default_value' => 'approve',
  );
421 422 423
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
424
    '#tableselect' => TRUE,
425
    '#submit' => array('node_admin_nodes_submit'),
426 427
  );

428 429
  // Enable language column and filter if multiple languages are enabled.
  $multilingual = language_multilingual();
430 431 432

  // Build the sortable table header.
  $header = array(
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    'title' => array(
      'data' => t('Title'),
      'field' => 'n.title',
    ),
    'type' => array(
      'data' => t('Content type'),
      'field' => 'n.type',
      'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
    ),
    'author' => array(
      'data' => t('Author'),
      'class' => array(RESPONSIVE_PRIORITY_LOW),
    ),
    'status' => array(
      'data' => t('Status'),
      'field' => 'n.status',
    ),
    'changed' => array(
      'data' => t('Updated'),
      'field' => 'n.changed',
      'sort' => 'desc',
      'class' => array(RESPONSIVE_PRIORITY_LOW)
    ,)
456
  );
457
  if ($multilingual) {
458
    $header['language_name'] = array('data' => t('Language'), 'field' => 'n.langcode', 'class' => array(RESPONSIVE_PRIORITY_LOW));
459 460 461
  }
  $header['operations'] = array('data' => t('Operations'));

462
  $query = db_select('node_field_data', 'n')
463
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
464
    ->extend('Drupal\Core\Database\Query\TableSortExtender');
465 466 467 468 469 470
  node_build_filter_query($query);

  if (!user_access('bypass node access')) {
    // If the user is able to view their own unpublished nodes, allow them
    // to see these in addition to published nodes. Check that they actually
    // have some unpublished nodes to view before adding the condition.
471
    if (user_access('view own unpublished content') && $own_unpublished = db_query('SELECT DISTINCT nid FROM {node_field_data} WHERE uid = :uid AND status = :status', array(':uid' => $GLOBALS['user']->uid, ':status' => 0))->fetchCol()) {
472 473 474 475 476 477 478 479 480 481 482
      $query->condition(db_or()
        ->condition('n.status', 1)
        ->condition('n.nid', $own_unpublished, 'IN')
      );
    }
    else {
      // If not, restrict the query to published nodes.
      $query->condition('n.status', 1);
    }
  }
  $nids = $query
483 484
    ->distinct()
    ->fields('n', array('nid'))
485 486
    ->limit(50)
    ->orderByHeader($header)
487
    ->addTag('node_access')
488 489 490 491 492
    ->execute()
    ->fetchCol();
  $nodes = node_load_multiple($nids);

  // Prepare the list of nodes.
493
  $languages = language_list(Language::STATE_ALL);
494
  $destination = drupal_get_destination();
495 496 497 498 499
  $form['nodes'] = array(
    '#type' => 'table',
    '#header' => $header,
    '#empty' => t('No content available.'),
  );
500
  foreach ($nodes as $node) {
501
    $l_options = $node->langcode != Language::LANGCODE_NOT_SPECIFIED && isset($languages[$node->langcode]) ? array('language' => $languages[$node->langcode]) : array();
502 503 504 505
    $mark = array(
      '#theme' => 'mark',
      '#type' => node_mark($node->nid, $node->changed),
    );
506 507 508 509 510
    $form['nodes'][$node->nid]['title'] = array(
      '#type' => 'link',
      '#title' => $node->label(),
      '#href' => 'node/' . $node->nid,
      '#options' => $l_options,
511
      '#suffix' => ' ' . drupal_render($mark),
512 513 514 515 516 517 518 519 520 521 522 523 524
    );
    $form['nodes'][$node->nid]['type'] = array(
      '#markup' => check_plain(node_get_type_label($node)),
    );
    $form['nodes'][$node->nid]['author'] = array(
      '#theme' => 'username',
      '#account' => $node,
    );
    $form['nodes'][$node->nid]['status'] = array(
      '#markup' => $node->status ? t('published') : t('not published'),
    );
    $form['nodes'][$node->nid]['changed'] = array(
      '#markup' => format_date($node->changed, 'short'),
525
    );
526
    if ($multilingual) {
527 528 529
      $form['nodes'][$node->nid]['language_name'] = array(
        '#markup' => language_name($node->langcode),
      );
530
    }
531

532 533 534 535
    // Build a list of all the accessible operations for the current node.
    $operations = array();
    if (node_access('update', $node)) {
      $operations['edit'] = array(
536
        'title' => t('Edit'),
537 538 539 540 541 542
        'href' => 'node/' . $node->nid . '/edit',
        'query' => $destination,
      );
    }
    if (node_access('delete', $node)) {
      $operations['delete'] = array(
543
        'title' => t('Delete'),
544 545 546 547
        'href' => 'node/' . $node->nid . '/delete',
        'query' => $destination,
      );
    }
548
    if ($node->isTranslatable()) {
549
      $operations['translate'] = array(
550
        'title' => t('Translate'),
551 552 553 554
        'href' => 'node/' . $node->nid . '/translations',
        'query' => $destination,
      );
    }
555
    $form['nodes'][$node->nid]['operations'] = array();
556 557
    if (count($operations) > 1) {
      // Render an unordered list of operations links.
558 559 560 561
      $form['nodes'][$node->nid]['operations'] = array(
        '#type' => 'operations',
        '#subtype' => 'node',
        '#links' => $operations,
562 563 564 565 566
      );
    }
    elseif (!empty($operations)) {
      // Render the first and only operation as a link.
      $link = reset($operations);
567 568 569 570 571
      $form['nodes'][$node->nid]['operations'] = array(
        '#type' => 'link',
        '#title' => $link['title'],
        '#href' => $link['href'],
        '#options' => array('query' => $link['query']),
572 573 574 575 576 577 578
      );
    }
  }

  // Only use a tableselect when the current user is able to perform any
  // operations.
  if ($admin_access) {
579
    $form['nodes']['#tableselect'] = TRUE;
580 581
  }

582
  $form['pager'] = array('#theme' => 'pager');
583 584 585
  return $form;
}

586
/**
587 588 589
 * Form submission handler for node_admin_nodes().
 *
 * Executes the chosen 'Update option' on the selected nodes.
590
 *
591 592 593 594
 * @see node_admin_nodes()
 * @see node_admin_nodes_validate()
 * @see node_filter_form()
 * @see node_filter_form_submit()
595 596
 * @see node_multiple_delete_confirm()
 * @see node_multiple_delete_confirm_submit()
597 598
 */
function node_admin_nodes_submit($form, &$form_state) {
599 600 601 602 603 604
  if ($action = entity_load('action', $form_state['values']['operation'])) {
    $nodes = entity_load_multiple('node', array_filter($form_state['values']['nodes']));
    $action->execute($nodes);
    $operation_definition = $action->getPluginDefinition();
    if (!empty($operation_definition['confirm_form_path'])) {
      $form_state['redirect'] = $operation_definition['confirm_form_path'];
605
    }
606
    cache_invalidate_tags(array('content' => TRUE));
607 608
  }
  else {
609
    // We need to rebuild the form to go to a second step. For example, to
610 611 612 613 614
    // show the confirmation form for the deletion of nodes.
    $form_state['rebuild'] = TRUE;
  }
}

615 616 617 618 619 620 621 622
/**
 * Multiple node deletion confirmation form for node_admin_content().
 *
 * @see node_admin_nodes()
 * @see node_admin_nodes_submit()
 * @see node_admin_nodes_validate()
 * @see node_filter_form()
 * @see node_filter_form_submit()
623
 * @see node_multiple_delete_confirm_submit()
624
 * @ingroup forms
625
 */
626
function node_multiple_delete_confirm($form, &$form_state, $nodes) {
627
  $form['nodes'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
628
  $node_entities = node_load_multiple(array_keys($nodes));
629 630
  // array_filter returns only elements with TRUE values
  foreach ($nodes as $nid => $value) {
631 632 633 634
    $form['nodes'][$nid] = array(
      '#type' => 'hidden',
      '#value' => $nid,
      '#prefix' => '<li>',
635
      '#suffix' => check_plain($node_entities[$nid]->label()) . "</li>\n",
636
    );
637 638 639
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  $form['#submit'][] = 'node_multiple_delete_confirm_submit';
640 641
  $confirm_question = format_plural(count($nodes),
                                  'Are you sure you want to delete this item?',
642
                                  'Are you sure you want to delete these items?');
643
  return confirm_form($form,
644
                    $confirm_question,
645
                    'admin/content', t('This action cannot be undone.'),
646
                    t('Delete'), t('Cancel'));
647 648
}

649 650 651 652 653 654 655 656
/**
 * Form submission handler for node_multiple_delete_confirm().
 *
 * @see node_admin_nodes()
 * @see node_admin_nodes_submit()
 * @see node_admin_nodes_validate()
 * @see node_filter_form()
 * @see node_filter_form_submit()
657
 * @see node_multiple_delete_confirm()
658
 */
659 660
function node_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
661
    entity_delete_multiple('node', array_keys($form_state['values']['nodes']));
662 663
    $count = count($form_state['values']['nodes']);
    watchdog('content', 'Deleted @count posts.', array('@count' => $count));
664
    drupal_set_message(format_plural($count, 'Deleted 1 post.', 'Deleted @count posts.'));
665
  }
666
  $form_state['redirect'] = 'admin/content';
667
}