forum.module 48.7 KB
Newer Older
Dries's avatar
 
Dries committed
1 2
<?php

Dries's avatar
 
Dries committed
3 4
/**
 * @file
5
 * Provides discussion forums.
Dries's avatar
 
Dries committed
6 7
 */

8
use Drupal\node\Node;
9
use Drupal\taxonomy\Term;
10

11
/**
12
 * Implements hook_help().
13
 */
14 15
function forum_help($path, $arg) {
  switch ($path) {
16
    case 'admin/help#forum':
17 18 19 20 21 22 23 24 25 26 27 28
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Forum module lets you create threaded discussion forums with functionality similar to other message board systems. Forums are useful because they allow community members to discuss topics with one another while ensuring those conversations are archived for later reference. In a forum, users post topics and threads in nested hierarchies, allowing discussions to be categorized and grouped. The forum hierarchy consists of:') . '</p>';
      $output .= '<ul>';
      $output .= '<li>' . t('Optional containers (for example, <em>Support</em>), which can hold:') . '</li>';
      $output .= '<ul><li>' . t('Forums (for example, <em>Installing Drupal</em>), which can hold:') . '</li>';
      $output .= '<ul><li>' . t('Forum topics submitted by users (for example, <em>How to start a Drupal 6 Multisite</em>), which start discussions and are starting points for:') . '</li>';
      $output .= '<ul><li>' . t('Threaded comments submitted by users (for example, <em>You have these options...</em>).') . '</li>';
      $output .= '</ul>';
      $output .= '</ul>';
      $output .= '</ul>';
      $output .= '</ul>';
29
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@forum">Forum module</a>.', array('@forum' => 'http://drupal.org/documentation/modules/forum')) . '</p>';
30 31
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
32 33 34 35
      $output .= '<dt>' . t('Setting up forum structure') . '</dt>';
      $output .= '<dd>' . t('Visit the <a href="@forums">Forums page</a> to set up containers and forums to hold your discussion topics.', array('@forums' => url('admin/structure/forum'))) . '</dd>';
      $output .= '<dt>' . t('Starting a discussion') . '</dt>';
      $output .= '<dd>' . t('The <a href="@create-topic">Forum topic</a> link on the <a href="@content-add">Add new content</a> page creates the first post of a new threaded discussion, or thread.', array('@create-topic' => url('node/add/forum'), '@content-add' => url('node/add'))) . '</dd>';
36
      $output .= '<dt>' . t('Navigation') . '</dt>';
37
      $output .= '<dd>' . t('Enabling the Forum module provides a default <em>Forums</em> menu item in the navigation menu that links to the <a href="@forums">Forums page</a>.', array('@forums' => url('forum'))) . '</dd>';
38 39 40
      $output .= '<dt>' . t('Moving forum topics') . '</dt>';
      $output .= '<dd>' . t('A forum topic (and all of its comments) may be moved between forums by selecting a different forum while editing a forum topic. When moving a forum topic between forums, the <em>Leave shadow copy</em> option creates a link in the original forum pointing to the new location.') . '</dd>';
      $output .= '<dt>' . t('Locking and disabling comments') . '</dt>';
41
      $output .= '<dd>' . t('Selecting <em>Closed</em> under <em>Comment settings</em> while editing a forum topic will lock (prevent new comments on) the thread. Selecting <em>Hidden</em> under <em>Comment settings</em> while editing a forum topic will hide all existing comments on the thread, and prevent new ones.') . '</dd>';
42
      $output .= '</dl>';
43
      return $output;
44
    case 'admin/structure/forum':
45
      $output = '<p>' . t('Forums contain forum topics. Use containers to group related forums.') . '</p>';
46
      $output .= theme('more_help_link', array('url' => 'admin/help/forum'));
47
      return $output;
48
    case 'admin/structure/forum/add/container':
49
      return '<p>' . t('Use containers to group related forums.') . '</p>';
50
    case 'admin/structure/forum/add/forum':
51
      return '<p>' . t('A forum holds related forum topics.') . '</p>';
52
    case 'admin/structure/forum/settings':
53
      return '<p>' . t('Adjust the display of your forum topics. Organize the forums on the <a href="@forum-structure">forum structure page</a>.', array('@forum-structure' => url('admin/structure/forum'))) . '</p>';
Dries's avatar
 
Dries committed
54 55 56
  }
}

57
/**
58
 * Implements hook_theme().
59 60 61
 */
function forum_theme() {
  return array(
62
    'forums' => array(
63
      'template' => 'forums',
64
      'variables' => array('forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
65 66
    ),
    'forum_list' => array(
67
      'template' => 'forum-list',
68
      'variables' => array('forums' => NULL, 'parents' => NULL, 'tid' => NULL),
69 70
    ),
    'forum_topic_list' => array(
71
      'template' => 'forum-topic-list',
72
      'variables' => array('tid' => NULL, 'topics' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
73 74
    ),
    'forum_icon' => array(
75
      'template' => 'forum-icon',
76
      'variables' => array('new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0, 'first_new' => FALSE),
77
    ),
78
    'forum_submitted' => array(
79
      'template' => 'forum-submitted',
80
      'variables' => array('topic' => NULL),
81
    ),
82
    'forum_form' => array(
83
      'render element' => 'form',
84 85
      'file' => 'forum.admin.inc',
    ),
86 87 88
  );
}

89
/**
90
 * Implements hook_menu().
91
 */
92 93
function forum_menu() {
  $items['forum'] = array(
94
    'title' => 'Forums',
95 96
    'page callback' => 'forum_page',
    'access arguments' => array('access content'),
97
    'file' => 'forum.pages.inc',
98
  );
99 100 101 102 103 104 105
  $items['forum/%forum_forum'] = array(
    'title' => 'Forums',
    'page callback' => 'forum_page',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'file' => 'forum.pages.inc',
  );
106
  $items['admin/structure/forum'] = array(
107
    'title' => 'Forums',
108
    'description' => 'Control forum hierarchy settings.',
109 110
    'page callback' => 'drupal_get_form',
    'page arguments' => array('forum_overview'),
111
    'access arguments' => array('administer forums'),
112
    'file' => 'forum.admin.inc',
113
  );
114
  $items['admin/structure/forum/list'] = array(
115
    'title' => 'List',
116 117 118
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
119
  $items['admin/structure/forum/add/container'] = array(
120
    'title' => 'Add container',
121 122
    'page callback' => 'forum_form_main',
    'page arguments' => array('container'),
123
    'access arguments' => array('administer forums'),
124
    'type' => MENU_LOCAL_ACTION,
125
    'parent' => 'admin/structure/forum',
126
    'file' => 'forum.admin.inc',
127
  );
128
  $items['admin/structure/forum/add/forum'] = array(
129
    'title' => 'Add forum',
130 131
    'page callback' => 'forum_form_main',
    'page arguments' => array('forum'),
132
    'access arguments' => array('administer forums'),
133
    'type' => MENU_LOCAL_ACTION,
134
    'parent' => 'admin/structure/forum',
135
    'file' => 'forum.admin.inc',
136
  );
137
  $items['admin/structure/forum/settings'] = array(
138
    'title' => 'Settings',
139 140
    'page callback' => 'drupal_get_form',
    'page arguments' => array('forum_admin_settings'),
141
    'access arguments' => array('administer forums'),
142 143
    'weight' => 5,
    'type' => MENU_LOCAL_TASK,
144
    'parent' => 'admin/structure/forum',
145
    'file' => 'forum.admin.inc',
146
  );
147
  $items['admin/structure/forum/edit/container/%taxonomy_term'] = array(
148
    'title' => 'Edit container',
149
    'page callback' => 'forum_form_main',
150
    'page arguments' => array('container', 5),
151
    'access arguments' => array('administer forums'),
152
    'file' => 'forum.admin.inc',
153
  );
154
  $items['admin/structure/forum/edit/forum/%taxonomy_term'] = array(
155
    'title' => 'Edit forum',
156 157
    'page callback' => 'forum_form_main',
    'page arguments' => array('forum', 5),
158
    'access arguments' => array('administer forums'),
159
    'file' => 'forum.admin.inc',
160 161 162
  );
  return $items;
}
163

164 165 166 167 168 169
/**
 * Implements hook_menu_local_tasks_alter().
 */
function forum_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  global $user;

170 171 172
  // Add action link to 'node/add/forum' on 'forum' sub-pages.
  if ($root_path == 'forum' || $root_path == 'forum/%') {
    $tid = (isset($router_item['page_arguments'][0]) ? $router_item['page_arguments'][0]->tid : 0);
173 174
    $forum_term = forum_forum_load($tid);
    if ($forum_term) {
175 176
      $links = array();
      // Loop through all bundles for forum taxonomy vocabulary field.
177
      $field = field_info_field('taxonomy_forums');
178 179 180 181 182 183
      foreach ($field['bundles']['node'] as $type) {
        if (node_access('create', $type)) {
          $links[$type] = array(
            '#theme' => 'menu_local_action',
            '#link' => array(
              'title' => t('Add new @node_type', array('@node_type' => node_type_get_name($type))),
184
              'href' => 'node/add/' . $type . '/' . $forum_term->tid,
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
            ),
          );
        }
      }
      if (empty($links)) {
        // Authenticated user does not have access to create new topics.
        if ($user->uid) {
          $links['disallowed'] = array(
            '#theme' => 'menu_local_action',
            '#link' => array(
              'title' => t('You are not allowed to post new content in the forum.'),
            ),
          );
        }
        // Anonymous user does not have access to create new topics.
        else {
          $links['login'] = array(
            '#theme' => 'menu_local_action',
            '#link' => array(
204
              'title' => t('<a href="@login">Log in</a> to post new content in the forum.', array(
205 206 207 208 209 210 211 212 213 214 215
                '@login' => url('user/login', array('query' => drupal_get_destination())),
              )),
              'localized_options' => array('html' => TRUE),
            ),
          );
        }
      }
      $data['actions']['output'] = array_merge($data['actions']['output'], $links);
    }
  }
}
216

217 218 219 220
/**
 * Implements hook_entity_info_alter().
 */
function forum_entity_info_alter(&$info) {
221
  // Take over URI construction for taxonomy terms that are forums.
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
  if ($vid = variable_get('forum_nav_vocabulary', 0)) {
    // Within hook_entity_info(), we can't invoke entity_load() as that would
    // cause infinite recursion, so we call taxonomy_vocabulary_get_names()
    // instead of taxonomy_vocabulary_load(). All we need is the machine name
    // of $vid, so retrieving and iterating all the vocabulary names is somewhat
    // inefficient, but entity info is cached across page requests, and an
    // iteration of all vocabularies once per cache clearing isn't a big deal,
    // and is done as part of taxonomy_entity_info() anyway.
    foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
      if ($vid == $vocabulary->vid) {
        $info['taxonomy_term']['bundles'][$machine_name]['uri callback'] = 'forum_uri';
      }
    }
  }
}

/**
239
 * Entity URI callback used in forum_entity_info_alter().
240 241 242 243 244 245 246
 */
function forum_uri($forum) {
  return array(
    'path' => 'forum/' . $forum->tid,
  );
}

247
/**
248
 * Checks whether a node can be used in a forum, based on its content type.
249
 *
250 251
 * @param Drupal\node\Node $node
 *   A node entity.
252
 *
253 254
 * @return
 *   Boolean indicating if the node can be assigned to a forum.
255
 */
256
function _forum_node_check_node_type(Node $node) {
257
  // Fetch information about the forum field.
258
  $field = field_info_instance('node', 'taxonomy_forums', $node->type);
259

260
  return is_array($field);
261
}
262

263
/**
264
 * Implements hook_node_view().
265
 */
266
function forum_node_view(Node $node, $view_mode) {
267
  $vid = variable_get('forum_nav_vocabulary', 0);
268
  $vocabulary = taxonomy_vocabulary_load($vid);
269
  if (_forum_node_check_node_type($node)) {
270
    if ($view_mode == 'full' && node_is_page($node)) {
271 272 273
      // Breadcrumb navigation
      $breadcrumb[] = l(t('Home'), NULL);
      $breadcrumb[] = l($vocabulary->name, 'forum');
274
      if ($parents = taxonomy_term_load_parents_all($node->forum_tid)) {
275
        $parents = array_reverse($parents);
276 277
        foreach ($parents as $parent) {
          $breadcrumb[] = l($parent->name, 'forum/' . $parent->tid);
278 279 280
        }
      }
      drupal_set_breadcrumb($breadcrumb);
281

282 283 284
    }
  }
}
285

286
/**
287
 * Implements hook_node_validate().
288
 *
289 290
 * Checks in particular that the node is assigned only a "leaf" term in the
 * forum taxonomy.
291
 */
292
function forum_node_validate(Node $node, $form) {
293 294
  if (_forum_node_check_node_type($node)) {
    $langcode = $form['taxonomy_forums']['#language'];
295
    // vocabulary is selected, not a "container" term.
296
    if (!empty($node->taxonomy_forums[$langcode])) {
297 298
      // Extract the node's proper topic ID.
      $containers = variable_get('forum_containers', array());
299 300 301 302 303 304 305
      foreach ($node->taxonomy_forums[$langcode] as $delta => $item) {
        // If no term was selected (e.g. when no terms exist yet), remove the
        // item.
        if (empty($item['tid'])) {
          unset($node->taxonomy_forums[$langcode][$delta]);
          continue;
        }
306
        $term = taxonomy_term_load($item['tid']);
307 308 309 310
        if (!$term) {
          form_set_error('taxonomy_forums', t('Select a forum.'));
          continue;
        }
311 312 313
        $used = db_query_range('SELECT 1 FROM {taxonomy_term_data} WHERE tid = :tid AND vid = :vid',0 , 1, array(
          ':tid' => $term->tid,
          ':vid' => $term->vid,
314
        ))->fetchField();
315
        if ($used && in_array($term->tid, $containers)) {
316
          form_set_error('taxonomy_forums', t('The item %forum is a forum container, not a forum. Select one of the forums below instead.', array('%forum' => $term->name)));
317 318
        }
      }
319 320 321
    }
  }
}
322

323
/**
324
 * Implements hook_node_presave().
325
 *
326
 * Assigns the forum taxonomy when adding a topic from within a forum.
327
 */
328
function forum_node_presave(Node $node) {
329
  if (_forum_node_check_node_type($node)) {
330 331
    // Make sure all fields are set properly:
    $node->icon = !empty($node->icon) ? $node->icon : '';
332 333
    reset($node->taxonomy_forums);
    $langcode = key($node->taxonomy_forums);
334
    if (!empty($node->taxonomy_forums[$langcode])) {
335
      $node->forum_tid = $node->taxonomy_forums[$langcode][0]['tid'];
336
      $old_tid = db_query_range("SELECT f.tid FROM {forum} f INNER JOIN {node} n ON f.vid = n.vid WHERE n.nid = :nid ORDER BY f.vid DESC", 0, 1, array(':nid' => $node->nid))->fetchField();
337
      if ($old_tid && isset($node->forum_tid) && ($node->forum_tid != $old_tid) && !empty($node->shadow)) {
338
        // A shadow copy needs to be created. Retain new term and add old term.
339
        $node->taxonomy_forums[$langcode][] = array('tid' => $old_tid);
340 341 342 343
      }
    }
  }
}
344

345
/**
346
 * Implements hook_node_update().
347
 */
348
function forum_node_update(Node $node) {
349
  if (_forum_node_check_node_type($node)) {
350
    if (empty($node->revision) && db_query('SELECT tid FROM {forum} WHERE nid=:nid', array(':nid' => $node->nid))->fetchField()) {
351
      if (!empty($node->forum_tid)) {
352
        db_update('forum')
353
          ->fields(array('tid' => $node->forum_tid))
354 355
          ->condition('vid', $node->vid)
          ->execute();
356 357 358
      }
      // The node is removed from the forum.
      else {
359 360 361
        db_delete('forum')
          ->condition('nid', $node->nid)
          ->execute();
362 363 364
      }
    }
    else {
365
      if (!empty($node->forum_tid)) {
366 367
        db_insert('forum')
          ->fields(array(
368
            'tid' => $node->forum_tid,
369 370 371 372
            'vid' => $node->vid,
            'nid' => $node->nid,
          ))
          ->execute();
373
      }
374
    }
375 376
    // If the node has a shadow forum topic, update the record for this
    // revision.
377
    if (!empty($node->shadow)) {
378 379 380 381 382 383 384 385 386 387 388 389
      db_delete('forum')
        ->condition('nid', $node->nid)
        ->condition('vid', $node->vid)
        ->execute();
      db_insert('forum')
        ->fields(array(
          'nid' => $node->nid,
          'vid' => $node->vid,
          'tid' => $node->forum_tid,
        ))
        ->execute();
     }
390 391
  }
}
392

393
/**
394
 * Implements hook_node_insert().
395
 */
396
function forum_node_insert(Node $node) {
397 398
  if (_forum_node_check_node_type($node)) {
    if (!empty($node->forum_tid)) {
399 400
      $nid = db_insert('forum')
        ->fields(array(
401
          'tid' => $node->forum_tid,
402 403 404 405
          'vid' => $node->vid,
          'nid' => $node->nid,
        ))
        ->execute();
406 407 408
    }
  }
}
409

410
/**
411
 * Implements hook_node_predelete().
412
 */
413
function forum_node_predelete(Node $node) {
414
  if (_forum_node_check_node_type($node)) {
415 416 417
    db_delete('forum')
      ->condition('nid', $node->nid)
      ->execute();
418 419 420
    db_delete('forum_index')
      ->condition('nid', $node->nid)
      ->execute();
421
  }
422
}
423

424
/**
425
 * Implements hook_node_load().
426
 */
427
function forum_node_load($nodes) {
428 429
  $node_vids = array();
  foreach ($nodes as $node) {
430
    if (_forum_node_check_node_type($node)) {
431 432 433 434
      $node_vids[] = $node->vid;
    }
  }
  if (!empty($node_vids)) {
435 436 437 438 439
    $query = db_select('forum', 'f');
    $query
      ->fields('f', array('nid', 'tid'))
      ->condition('f.vid', $node_vids);
    $result = $query->execute();
440 441 442
    foreach ($result as $record) {
      $nodes[$record->nid]->forum_tid = $record->tid;
    }
443
  }
444 445
}

446
/**
447
 * Implements hook_node_info().
448
 */
449
function forum_node_info() {
450 451
  return array(
    'forum' => array(
452
      'name' => t('Forum topic'),
453
      'base' => 'forum',
454
      'description' => t('A <em>forum topic</em> starts a new discussion thread within a forum.'),
455 456 457
      'title_label' => t('Subject'),
    )
  );
Dries's avatar
 
Dries committed
458 459
}

460
/**
461
 * Implements hook_permission().
462
 */
463
function forum_permission() {
464
  $perms = array(
465 466 467
    'administer forums' => array(
      'title' => t('Administer forums'),
    ),
468 469
  );
  return $perms;
Dries's avatar
 
Dries committed
470
}
Dries's avatar
 
Dries committed
471

472
/**
473
 * Implements hook_taxonomy_term_delete().
474
 */
475
function forum_taxonomy_term_delete(Term $term) {
476 477
  // For containers, remove the tid from the forum_containers variable.
  $containers = variable_get('forum_containers', array());
478
  $key = array_search($term->tid, $containers);
479 480 481 482 483
  if ($key !== FALSE) {
    unset($containers[$key]);
  }
  variable_set('forum_containers', $containers);
}
484

485
/**
486
 * Implements hook_comment_publish().
487
 *
488
 * This actually handles the insertion and update of published nodes since
489 490 491 492 493 494 495
 * comment_save() calls hook_comment_publish() for all published comments.
 */
function forum_comment_publish($comment) {
  _forum_update_forum_index($comment->nid);
}

/**
496
 * Implements hook_comment_update().
497
 *
498 499
 * The Comment module doesn't call hook_comment_unpublish() when saving
 * individual comments, so we need to check for those here.
500 501
 */
function forum_comment_update($comment) {
502 503
  // comment_save() calls hook_comment_publish() for all published comments,
  // so we need to handle all other values here.
504 505 506 507 508 509
  if (!$comment->status) {
    _forum_update_forum_index($comment->nid);
  }
}

/**
510
 * Implements hook_comment_unpublish().
511 512 513 514 515 516
 */
function forum_comment_unpublish($comment) {
  _forum_update_forum_index($comment->nid);
}

/**
517
 * Implements hook_comment_delete().
518 519 520 521 522 523
 */
function forum_comment_delete($comment) {
  _forum_update_forum_index($comment->nid);
}

/**
524
 * Implements hook_field_storage_pre_insert().
525
 */
526 527
function forum_field_storage_pre_insert($entity_type, $entity, &$skip_fields) {
  if ($entity_type == 'node' && $entity->status && _forum_node_check_node_type($entity)) {
528
    $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
529
    foreach ($entity->taxonomy_forums as $language) {
530
      foreach ($language as $item) {
531
        $query->values(array(
532 533
          'nid' => $entity->nid,
          'title' => $entity->title,
534
          'tid' => $item['tid'],
535 536
          'sticky' => $entity->sticky,
          'created' => $entity->created,
537
          'comment_count' => 0,
538
          'last_comment_timestamp' => $entity->created,
539 540 541 542 543 544 545 546
        ));
      }
    }
    $query->execute();
  }
}

/**
547
 * Implements hook_field_storage_pre_update().
548
 */
549
function forum_field_storage_pre_update($entity_type, $entity, &$skip_fields) {
550 551
  $first_call = &drupal_static(__FUNCTION__, array());

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
  if ($entity_type == 'node' && _forum_node_check_node_type($entity)) {

    // If the node is published, update the forum index.
    if ($entity->status) {

      // We don't maintain data for old revisions, so clear all previous values
      // from the table. Since this hook runs once per field, per object, make
      // sure we only wipe values once.
      if (!isset($first_call[$entity->nid])) {
        $first_call[$entity->nid] = FALSE;
        db_delete('forum_index')->condition('nid', $entity->nid)->execute();
      }
      $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
      foreach ($entity->taxonomy_forums as $language) {
        foreach ($language as $item) {
          $query->values(array(
            'nid' => $entity->nid,
            'title' => $entity->title,
            'tid' => $item['tid'],
            'sticky' => $entity->sticky,
            'created' => $entity->created,
            'comment_count' => 0,
            'last_comment_timestamp' => $entity->created,
          ));
        }
577
      }
578 579 580 581
      $query->execute();
      // The logic for determining last_comment_count is fairly complex, so
      // call _forum_update_forum_index() too.
      _forum_update_forum_index($entity->nid);
Dries's avatar
 
Dries committed
582
    }
583 584 585 586 587 588

    // When a forum node is unpublished, remove it from the forum_index table.
    else {
      db_delete('forum_index')->condition('nid', $entity->nid)->execute();
    }

589 590
  }
}
Dries's avatar
 
Dries committed
591

592
/**
593
 * Implements hook_form_FORM_ID_alter() for taxonomy_form_vocabulary().
594
 */
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
function forum_form_taxonomy_form_vocabulary_alter(&$form, &$form_state, $form_id) {
  $vid = variable_get('forum_nav_vocabulary', 0);
  if (isset($form['vid']['#value']) && $form['vid']['#value'] == $vid) {
    $form['help_forum_vocab'] = array(
      '#markup' => t('This is the designated forum vocabulary. Some of the normal vocabulary options have been removed.'),
      '#weight' => -1,
    );
    // Forum's vocabulary always has single hierarchy. Forums and containers
    // have only one parent or no parent for root items. By default this value
    // is 0.
    $form['hierarchy']['#value'] = TAXONOMY_HIERARCHY_SINGLE;
    // Do not allow to delete forum's vocabulary.
    $form['actions']['delete']['#access'] = FALSE;
  }
}

/**
 * Implements hook_form_FORM_ID_alter() for taxonomy_form_term().
 */
function forum_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
615
  $vid = variable_get('forum_nav_vocabulary', 0);
616
  if (isset($form['vid']['#value']) && $form['vid']['#value'] == $vid) {
617
    // Hide multiple parents select from forum terms.
618
    $form['relations']['parent']['#access'] = FALSE;
619
  }
620 621 622
}

/**
623
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
624 625 626
 */
function forum_form_node_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['taxonomy_forums'])) {
627
    $langcode = $form['taxonomy_forums']['#language'];
628
    // Make the vocabulary required for 'real' forum-nodes.
629 630
    $form['taxonomy_forums'][$langcode]['#required'] = TRUE;
    $form['taxonomy_forums'][$langcode]['#multiple'] = FALSE;
631 632
    if (empty($form['taxonomy_forums'][$langcode]['#default_value'])) {
      // If there is no default forum already selected, try to get the forum
633 634
      // ID from the URL (e.g., if we are on a page like node/add/forum/2, we
      // expect "2" to be the ID of the forum that was requested).
635
      $requested_forum_id = arg(3);
636
      $form['taxonomy_forums'][$langcode]['#default_value'] = is_numeric($requested_forum_id) ? $requested_forum_id : '';
637
    }
638
  }
639 640
}

641
/**
642
 * Implements hook_block_info().
643
 */
644
function forum_block_info() {
645 646 647
  $blocks['active'] = array(
    'info' => t('Active forum topics'),
    'cache' => DRUPAL_CACHE_CUSTOM,
648
    'properties' => array('administrative' => TRUE),
649 650 651 652
  );
  $blocks['new'] = array(
    'info' => t('New forum topics'),
    'cache' => DRUPAL_CACHE_CUSTOM,
653
    'properties' => array('administrative' => TRUE),
654
  );
655 656 657 658
  return $blocks;
}

/**
659
 * Implements hook_block_configure().
660 661 662 663 664 665 666
 */
function forum_block_configure($delta = '') {
  $form['forum_block_num_' . $delta] = array('#type' => 'select', '#title' => t('Number of topics'), '#default_value' => variable_get('forum_block_num_' . $delta, '5'), '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)));
  return $form;
}

/**
667
 * Implements hook_block_save().
668 669 670 671 672 673
 */
function forum_block_save($delta = '', $edit = array()) {
  variable_set('forum_block_num_' . $delta, $edit['forum_block_num_' . $delta]);
}

/**
674
 * Implements hook_block_view().
675
 *
676 677
 * Generates a block containing the currently active forum topics and the most
 * recently added forum topics.
678
 */
679
function forum_block_view($delta = '') {
680 681
  $query = db_select('forum_index', 'f')
    ->fields('f')
682 683
    ->addTag('node_access')
    ->addMetaData('base_table', 'forum_index');
684 685 686 687
  switch ($delta) {
    case 'active':
      $title = t('Active forum topics');
      $query
688
        ->orderBy('f.last_comment_timestamp', 'DESC')
689 690 691 692 693 694
        ->range(0, variable_get('forum_block_num_active', '5'));
      break;

    case 'new':
      $title = t('New forum topics');
      $query
695
        ->orderBy('f.created', 'DESC')
696 697 698
        ->range(0, variable_get('forum_block_num_new', '5'));
      break;
  }
Dries's avatar
 
Dries committed
699

700
  $block['subject'] = $title;
701 702 703
  // Cache based on the altered query. Enables us to cache with node access enabled.
  $block['content'] = drupal_render_cache_by_query($query, 'forum_block_view');
  $block['content']['#access'] = user_access('access content');
704
  return $block;
705
}
706

707
/**
708 709 710 711 712 713
 * Render API callback: Lists nodes based on the element's #query property.
 *
 * This function can be used as a #pre_render callback.
 *
 * @see forum_block_view()
 */
714 715 716
function forum_block_view_pre_render($elements) {
  $result = $elements['#query']->execute();
  if ($node_title_list = node_title_list($result)) {
717
    $elements['forum_list'] = $node_title_list;
718
    $elements['forum_more'] = array('#theme' => 'more_link', '#url' => 'forum', '#title' => t('Read the latest forum topics.'));
719
  }
720
  return $elements;
Dries's avatar
 
Dries committed
721 722
}

723
/**
724
 * Implements hook_form().
725
 */
726 727
function forum_form(Node $node, &$form_state) {
  $type = node_type_load($node->type);
728 729 730 731 732 733
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE, '#weight' => -5
  );
734

735
  if (!empty($node->nid)) {
736
    $forum_terms = $node->taxonomy_forums;
737
    // If editing, give option to leave shadows.
738
    $shadow = (count($forum_terms) > 1);
739
    $form['shadow'] = array('#type' => 'checkbox', '#title' => t('Leave shadow copy'), '#default_value' => $shadow, '#description' => t('If you move this topic, you can leave a link in the old forum to the new forum.'));
740
    $form['forum_tid'] = array('#type' => 'value', '#value' => $node->forum_tid);
Dries's avatar
Dries committed
741
  }
Dries's avatar
 
Dries committed
742

743
  return $form;
Dries's avatar
 
Dries committed
744 745
}

Dries's avatar
 
Dries committed
746
/**
747
 * Returns a tree of all forums for a given taxonomy term ID.
Dries's avatar
 
Dries committed
748 749
 *
 * @param $tid
750 751 752
 *   (optional) Taxonomy term ID of the forum. If not given all forums will be
 *   returned.
 *
Dries's avatar
 
Dries committed
753
 * @return
754
 *   A tree of taxonomy objects, with the following additional properties:
755 756 757 758
 *   - num_topics: Number of topics in the forum.
 *   - num_posts: Total number of posts in all topics.
 *   - last_post: Most recent post for the forum.
 *   - forums: An array of child forums.
Dries's avatar
 
Dries committed
759
 */
760
function forum_forum_load($tid = NULL) {
761 762
  $cache = &drupal_static(__FUNCTION__, array());