node.admin.inc 20.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
<?php
// $Id$

/**
 * @file
 * Content administration and module settings UI.
 */

/**
 * Menu callback: confirm rebuilding of permissions.
 */
function node_configure_rebuild_confirm() {
13
  return confirm_form(array(), t('Are you sure you want to rebuild the permissions on site content?'),
14
                  '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'));
15 16 17 18 19
}

/**
 * Handler for wipe confirmation
 */
20
function node_configure_rebuild_confirm_submit($form, &$form_state) {
21
  node_access_rebuild(TRUE);
22
  $form_state['redirect'] = 'admin/reports/status';
23 24 25
}

/**
26
 * Implements hook_node_operations().
27 28 29 30
 */
function node_node_operations() {
  $operations = array(
    'publish' => array(
31
      'label' => t('Publish selected content'),
32
      'callback' => 'node_mass_update',
33
      'callback arguments' => array('updates' => array('status' => NODE_PUBLISHED)),
34 35
    ),
    'unpublish' => array(
36
      'label' => t('Unpublish selected content'),
37
      'callback' => 'node_mass_update',
38
      'callback arguments' => array('updates' => array('status' => NODE_NOT_PUBLISHED)),
39 40
    ),
    'promote' => array(
41
      'label' => t('Promote selected content to front page'),
42
      'callback' => 'node_mass_update',
43
      'callback arguments' => array('updates' => array('status' => NODE_PUBLISHED, 'promote' => NODE_PROMOTED)),
44 45
    ),
    'demote' => array(
46
      'label' => t('Demote selected content from front page'),
47
      'callback' => 'node_mass_update',
48
      'callback arguments' => array('updates' => array('promote' => NODE_NOT_PROMOTED)),
49 50
    ),
    'sticky' => array(
51
      'label' => t('Make selected content sticky'),
52
      'callback' => 'node_mass_update',
53
      'callback arguments' => array('updates' => array('status' => NODE_PUBLISHED, 'sticky' => NODE_STICKY)),
54 55
    ),
    'unsticky' => array(
56
      'label' => t('Make selected content not sticky'),
57
      'callback' => 'node_mass_update',
58
      'callback arguments' => array('updates' => array('sticky' => NODE_NOT_STICKY)),
59 60
    ),
    'delete' => array(
61
      'label' => t('Delete selected content'),
62 63 64 65 66 67 68 69 70 71 72
      'callback' => NULL,
    ),
  );
  return $operations;
}

/**
 * List node administration filters that can be applied.
 */
function node_filters() {
  // Regular filters
73 74 75
  $filters['status'] = array(
    'title' => t('status'),
    'options' => array(
76
      '[any]' => t('any'),
77 78 79 80 81 82 83
      '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'),
    ),
84 85 86
  );
  // Include translation states if we have this module enabled
  if (module_exists('translation')) {
87 88 89 90
    $filters['status']['options'] += array(
      'translate-0' => t('Up to date translation'),
      'translate-1' => t('Outdated translation'),
    );
91 92
  }

93 94 95 96 97 98
  $filters['type'] = array(
    'title' => t('type'),
    'options' => array(
      '[any]' => t('any'),
    ) + node_type_get_names(),
  );
99 100 101

  // Language filter if there is a list of languages
  if ($languages = module_invoke('locale', 'language_list')) {
102
    $languages = array(LANGUAGE_NONE => t('Language neutral')) + $languages;
103 104 105 106 107 108
    $filters['language'] = array(
      'title' => t('language'),
      'options' => array(
        '[any]' => t('any'),
      ) + $languages,
    );
109 110 111 112 113
  }
  return $filters;
}

/**
114 115 116 117
 * Apply filters for node administration filters based on session.
 *
 * @param $query
 *   A SelectQuery to which the filters should be applied.
118
 */
119
function node_build_filter_query(SelectQueryInterface $query) {
120
  // Build query
121 122
  $filter_data = isset($_SESSION['node_overview_filter']) ? $_SESSION['node_overview_filter'] : array();
  foreach ($filter_data as $index => $filter) {
123 124
    list($key, $value) = $filter;
    switch ($key) {
125
      case 'term':
126 127
        $alias = $query->join('taxonomy_index', 'ti', "n.nid = %alias.nid");
        $query->condition($alias . '.tid', $value);
128
        break;
129 130 131 132 133
      case 'status':
        // Note: no exploitable hole as $key/$value have already been checked when submitted
        list($key, $value) = explode('-', $value, 2);
      case 'type':
      case 'language':
134
        $query->condition('n.' . $key, $value);
135
        break;
136 137 138 139 140 141 142 143
    }
  }
}

/**
 * Return form for node administration filters.
 */
function node_filter_form() {
144
  $session = isset($_SESSION['node_overview_filter']) ? $_SESSION['node_overview_filter'] : array();
145 146 147
  $filters = node_filters();

  $i = 0;
148 149
  $form['filters'] = array(
    '#type' => 'fieldset',
150 151 152 153 154
    '#title' => t('Show only items where'),
    '#theme' => 'node_filters',
  );
  foreach ($session as $filter) {
    list($type, $value) = $filter;
155
    if ($type == 'term') {
156
      // Load term name from DB rather than search and parse options array.
157
      $value = module_invoke('taxonomy', 'term_load', $value);
158 159
      $value = $value->name;
    }
160
    elseif ($type == 'language') {
161
      $value = $value == LANGUAGE_NONE ? t('Language neutral') : module_invoke('locale', 'language_name', $value);
162 163 164 165 166
    }
    else {
      $value = $filters[$type]['options'][$value];
    }
    if ($i++) {
167
      $form['filters']['current'][] = array('#markup' => t('<em>and</em> where <strong>%type</strong> is <strong>%value</strong>', array('%type' => $filters[$type]['title'], '%value' => $value)));
168 169
    }
    else {
170
      $form['filters']['current'][] = array('#markup' => t('<strong>%type</strong> is <strong>%value</strong>', array('%type' => $filters[$type]['title'], '%value' => $value)));
171 172 173 174 175 176 177 178 179
    }
    if (in_array($type, array('type', 'language'))) {
      // Remove the option if it is already being filtered on.
      unset($filters[$type]);
    }
  }

  foreach ($filters as $key => $filter) {
    $names[$key] = $filter['title'];
180 181 182 183 184 185
    $form['filters']['status'][$key] = array(
      '#type' => 'select',
      '#options' => $filter['options'],
      '#title' => $filter['title'],
      '#default_value' => '[any]',
    );
186 187
  }

188
  $form['filters']['actions'] = array(
189
    '#type' => 'actions',
190
    '#id' => 'node-admin-buttons',
191
    '#attributes' => array('class' => array('container-inline')),
192 193
  );
  $form['filters']['actions']['submit'] = array('#type' => 'submit', '#value' => (count($session) ? t('Refine') : t('Filter')));
194
  if (count($session)) {
195 196
    $form['filters']['actions']['undo'] = array('#type' => 'submit', '#value' => t('Undo'));
    $form['filters']['actions']['reset'] = array('#type' => 'submit', '#value' => t('Reset'));
197 198
  }

199 200
  drupal_add_js('misc/form.js');

201 202 203 204
  return $form;
}

/**
205 206 207 208 209
 * Returns HTML for a node administration filter selector.
 *
 * @param $variables
 *   An associative array containing:
 *   - form: A render element representing the form.
210 211
 *
 * @ingroup themeable
212
 */
213 214
function theme_node_filters($variables) {
  $form = $variables['form'];
215
  $output = '';
216

217
  $output .= '<ul class="clearfix">';
218 219
  if (!empty($form['current'])) {
    foreach (element_children($form['current']) as $key) {
220
      $output .= '<li>' . drupal_render($form['current'][$key]) . '</li>';
221 222
    }
  }
223
  $output .= '</ul>';
224

225 226
  $output .= '<div class="clearfix">';

227
  $output .= '<dl class="multiselect">' . (!empty($form['current']) ? '<dt><em>' . t('and') . '</em> ' . t('where') . '</dt>' : '');
228

229
  $output .= '<dd>';
230 231 232 233 234 235 236

  foreach (element_children($form['status']) as $key) {
    $output .= drupal_render($form['status'][$key]);
  }
  $output .= '</dd>';

  $output .= '</dl>';
237
  $output .= drupal_render($form['actions']);
238

239 240
  $output .= '</div>';

241 242 243 244 245 246 247 248 249 250 251
  return $output;
}

/**
 * Process result from node administration filter form.
 */
function node_filter_form_submit($form, &$form_state) {
  $filters = node_filters();
  switch ($form_state['values']['op']) {
    case t('Filter'):
    case t('Refine'):
252 253 254 255 256 257 258 259 260
      // 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]') {
          // Flatten the options array to accommodate hierarchical/nested options.
          $flat_options = form_options_flatten($filters[$filter]['options']);
          // Only accept valid selections offered on the dropdown, block bad input.
          if (isset($flat_options[$form_state['values'][$filter]])) {
            $_SESSION['node_overview_filter'][] = array($filter, $form_state['values'][$filter]);
          }
261 262 263 264 265 266 267
        }
      }
      break;
    case t('Undo'):
      array_pop($_SESSION['node_overview_filter']);
      break;
    case t('Reset'):
268
      $_SESSION['node_overview_filter'] = array();
269 270 271 272
      break;
  }
}

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
/**
 * Make mass update of nodes, changing all nodes in the $nodes array
 * to update them with the field values in $updates.
 *
 * IMPORTANT NOTE: This function is intended to work when called
 * from a form submit handler. Calling it outside of the form submission
 * process may not work correctly.
 *
 * @param array $nodes
 *   Array of node nids to update.
 * @param array $updates
 *   Array of key/value pairs with node field names and the
 *   value to update that field to.
 */
function node_mass_update($nodes, $updates) {
  // We use batch processing to prevent timeout when updating a large number
  // of nodes.
  if (count($nodes) > 10) {
    $batch = array(
      'operations' => array(
        array('_node_mass_update_batch_process', array($nodes, $updates))
      ),
      '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.
303
      'file' => drupal_get_path('module', 'node') . '/node.admin.inc',
304 305 306 307
    );
    batch_set($batch);
  }
  else {
308
    foreach ($nodes as $nid) {
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
      _node_mass_update_helper($nid, $updates);
    }
    drupal_set_message(t('The update has been performed.'));
  }
}

/**
 * Node Mass Update - helper function.
 */
function _node_mass_update_helper($nid, $updates) {
  $node = node_load($nid, NULL, TRUE);
  foreach ($updates as $name => $value) {
    $node->$name = $value;
  }
  node_save($node);
  return $node;
}

/**
 * Node Mass Update Batch operation
 */
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.
345
    $context['results'][] = l($node->title, 'node/' . $node->nid);
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367

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

/**
 * Node Mass Update Batch 'finished' callback.
 */
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:');
368
    $message .= theme('item_list', array('items' => $results));
369 370 371 372
    drupal_set_message($message);
  }
}

373 374 375
/**
 * Menu callback: content administration.
 */
376
function node_admin_content($form, $form_state) {
377
  if (isset($form_state['values']['operation']) && $form_state['values']['operation'] == 'delete') {
378
    return node_multiple_delete_confirm($form, $form_state, array_filter($form_state['values']['nodes']));
379
  }
380
  $form['filter'] = node_filter_form();
381
  $form['#submit'][] = 'node_filter_form_submit';
382
  $form['admin'] = node_admin_nodes();
383 384 385 386

  return $form;
}

387 388 389
/**
 * Form builder: Builds the node administration overview.
 */
390
function node_admin_nodes() {
391
  $admin_access = user_access('administer nodes');
392

393
  // Build the 'Update options' form.
394 395
  $form['options'] = array(
    '#type' => 'fieldset',
396
    '#title' => t('Update options'),
397
    '#attributes' => array('class' => array('container-inline')),
398
    '#access' => $admin_access,
399 400 401 402 403
  );
  $options = array();
  foreach (module_invoke_all('node_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
404 405 406 407 408
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => 'approve',
  );
409 410 411
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
412
    '#validate' => array('node_admin_nodes_validate'),
413
    '#submit' => array('node_admin_nodes_submit'),
414 415
  );

416 417
  // Enable language column if translation module is enabled
  // or if we have any node with language.
418
  $multilanguage = (module_exists('translation') || db_query("SELECT COUNT(*) FROM {node} WHERE language <> :language", array(':language' => LANGUAGE_NONE))->fetchField());
419 420 421 422 423

  // Build the sortable table header.
  $header = array(
    'title' => array('data' => t('Title'), 'field' => 'n.title'),
    'type' => array('data' => t('Type'), 'field' => 'n.type'),
424
    'author' => t('Author'),
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
    'status' => array('data' => t('Status'), 'field' => 'n.status'),
    'changed' => array('data' => t('Updated'), 'field' => 'n.changed', 'sort' => 'desc')
  );
  if ($multilanguage) {
    $header['language'] = array('data' => t('Language'), 'field' => 'n.language');
  }
  $header['operations'] = array('data' => t('Operations'));

  $query = db_select('node', 'n')->extend('PagerDefault')->extend('TableSort');
  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.
    if (user_access('view own unpublished content') && $own_unpublished = db_query('SELECT nid FROM {node} WHERE uid = :uid AND status = :status', array(':uid' => $GLOBALS['user']->uid, ':status' => 0))->fetchCol()) {
      $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
    ->fields('n',array('nid'))
    ->limit(50)
    ->orderByHeader($header)
    ->execute()
    ->fetchCol();
  $nodes = node_load_multiple($nids);

  // Prepare the list of nodes.
460
  $languages = language_list();
461
  $destination = drupal_get_destination();
462 463
  $options = array();
  foreach ($nodes as $node) {
464
    $l_options = $node->language != LANGUAGE_NONE ? array('language' => $languages[$node->language]) : array();
465
    $options[$node->nid] = array(
466 467 468
      'title' => array(
        'data' => array(
          '#type' => 'link',
469
          '#title' => $node->title,
470 471 472 473 474
          '#href' => 'node/' . $node->nid,
          '#options' => $l_options,
          '#suffix' => ' ' . theme('mark', array('type' => node_mark($node->nid, $node->changed))),
        ),
      ),
475
      'type' => check_plain(node_type_get_name($node)),
476
      'author' => theme('username', array('account' => $node)),
477
      'status' => $node->status ? t('published') : t('not published'),
478 479
      'changed' => format_date($node->changed, 'short'),
    );
480
    if ($multilanguage) {
481
      $options[$node->nid]['language'] = $node->language == LANGUAGE_NONE ? t('Language neutral') : t($languages[$node->language]->name);
482
    }
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    // Build a list of all the accessible operations for the current node.
    $operations = array();
    if (node_access('update', $node)) {
      $operations['edit'] = array(
        'title' => t('edit'),
        'href' => 'node/' . $node->nid . '/edit',
        'query' => $destination,
      );
    }
    if (node_access('delete', $node)) {
      $operations['delete'] = array(
        'title' => t('delete'),
        'href' => 'node/' . $node->nid . '/delete',
        'query' => $destination,
      );
    }
    $options[$node->nid]['operations'] = array();
    if (count($operations) > 1) {
      // Render an unordered list of operations links.
      $options[$node->nid]['operations'] = array(
        'data' => array(
504
          '#theme' => 'links__node_operations',
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
          '#links' => $operations,
          '#attributes' => array('class' => array('links', 'inline')),
        ),
      );
    }
    elseif (!empty($operations)) {
      // Render the first and only operation as a link.
      $link = reset($operations);
      $options[$node->nid]['operations'] = array(
        'data' => array(
          '#type' => 'link',
          '#title' => $link['title'],
          '#href' => $link['href'],
          '#options' => array('query' => $link['query']),
        ),
      );
    }
  }

  // Only use a tableselect when the current user is able to perform any
  // operations.
  if ($admin_access) {
    $form['nodes'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
      '#empty' => t('No content available.'),
532
    );
533
  }
534 535 536 537 538 539
  // Otherwise, use a simple table.
  else {
    $form['nodes'] = array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $options,
540
      '#empty' => t('No content available.'),
541 542 543
    );
  }

544
  $form['pager'] = array('#markup' => theme('pager', array('tags' => NULL)));
545 546 547
  return $form;
}

548 549
/**
 * Validate node_admin_nodes form submissions.
550
 *
551 552 553 554
 * Check if any nodes have been selected to perform the chosen
 * 'Update option' on.
 */
function node_admin_nodes_validate($form, &$form_state) {
555 556
  // Error if there are no items to select.
  if (!is_array($form_state['values']['nodes']) || !count(array_filter($form_state['values']['nodes']))) {
557 558 559 560 561 562
    form_set_error('', t('No items selected.'));
  }
}

/**
 * Process node_admin_nodes form submissions.
563
 *
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
 * Execute the chosen 'Update option' on the selected nodes.
 */
function node_admin_nodes_submit($form, &$form_state) {
  $operations = module_invoke_all('node_operations');
  $operation = $operations[$form_state['values']['operation']];
  // Filter out unchecked nodes
  $nodes = array_filter($form_state['values']['nodes']);
  if ($function = $operation['callback']) {
    // Add in callback arguments if present.
    if (isset($operation['callback arguments'])) {
      $args = array_merge(array($nodes), $operation['callback arguments']);
    }
    else {
      $args = array($nodes);
    }
    call_user_func_array($function, $args);

    cache_clear_all();
  }
  else {
584
    // We need to rebuild the form to go to a second step. For example, to
585 586 587 588 589
    // show the confirmation form for the deletion of nodes.
    $form_state['rebuild'] = TRUE;
  }
}

590
function node_multiple_delete_confirm($form, &$form_state, $nodes) {
591 592 593
  $form['nodes'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  // array_filter returns only elements with TRUE values
  foreach ($nodes as $nid => $value) {
594
    $title = db_query('SELECT title FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
595 596 597 598
    $form['nodes'][$nid] = array(
      '#type' => 'hidden',
      '#value' => $nid,
      '#prefix' => '<li>',
599
      '#suffix' => check_plain($title) . "</li>\n",
600
    );
601 602 603
  }
  $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
  $form['#submit'][] = 'node_multiple_delete_confirm_submit';
604 605
  $confirm_question = format_plural(count($nodes),
                                  'Are you sure you want to delete this item?',
606
                                  'Are you sure you want to delete these items?');
607
  return confirm_form($form,
608
                    $confirm_question,
609
                    'admin/content', t('This action cannot be undone.'),
610
                    t('Delete'), t('Cancel'));
611 612 613 614
}

function node_multiple_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
615 616 617 618
    node_delete_multiple(array_keys($form_state['values']['nodes']));
    $count = count($form_state['values']['nodes']);
    watchdog('content', 'Deleted @count posts.', array('@count' => $count));
    drupal_set_message(t('Deleted @count posts.', array('@count' => $count)));
619
  }
620
  $form_state['redirect'] = 'admin/content';
621
}