forum.module 43.9 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
/**
9
 * Implements hook_help().
10
 */
11 12
function forum_help($path, $arg) {
  switch ($path) {
13
    case 'admin/help#forum':
14 15 16 17 18 19 20 21 22 23 24 25 26
      $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>';
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@forum">Forum module</a>.', array('@forum' => 'http://drupal.org/handbook/modules/forum')) . '</p>';
27 28
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
29 30 31 32
      $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>';
33
      $output .= '<dt>' . t('Navigation') . '</dt>';
34
      $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>';
35 36 37
      $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>';
38
      $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>';
39
      $output .= '</dl>';
40
      return $output;
41
    case 'admin/structure/forum':
42
      $output = '<p>' . t('Forums contain forum topics. Use containers to group related forums.') . '</p>';
43
      $output .= theme('more_help_link', array('url' => 'admin/help/forum'));
44
      return $output;
45
    case 'admin/structure/forum/add/container':
46
      return '<p>' . t('Use containers to group related forums.') . '</p>';
47
    case 'admin/structure/forum/add/forum':
48
      return '<p>' . t('A forum holds related forum topics.') . '</p>';
49
    case 'admin/structure/forum/settings':
50
      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
51 52 53
  }
}

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

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

161 162 163 164 165 166
/**
 * Implements hook_menu_local_tasks_alter().
 */
function forum_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  global $user;

167 168 169
  // 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);
170 171
    $forum_term = forum_forum_load($tid);
    if ($forum_term) {
172 173
      $links = array();
      // Loop through all bundles for forum taxonomy vocabulary field.
174
      $field = field_info_field('taxonomy_forums');
175 176 177 178 179 180
      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))),
181
              'href' => 'node/add/' . str_replace('_', '-', $type) . '/' . $forum_term->tid,
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            ),
          );
        }
      }
      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(
201
              'title' => t('<a href="@login">Log in</a> to post new content in the forum.', array(
202 203 204 205 206 207 208 209 210 211 212
                '@login' => url('user/login', array('query' => drupal_get_destination())),
              )),
              'localized_options' => array('html' => TRUE),
            ),
          );
        }
      }
      $data['actions']['output'] = array_merge($data['actions']['output'], $links);
    }
  }
}
213

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
/**
 * Implements hook_entity_info_alter().
 */
function forum_entity_info_alter(&$info) {
  // Take over URI constuction for taxonomy terms that are forums.
  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';
      }
    }
  }
}

/**
 * Entity URI callback.
 */
function forum_uri($forum) {
  return array(
    'path' => 'forum/' . $forum->tid,
  );
}

244
/**
245 246 247 248
 * Check whether a content type can be used in a forum.
 *
 * @param $node
 *   A node object.
249
 *
250 251
 * @return
 *   Boolean indicating if the node can be assigned to a forum.
252
 */
253
function _forum_node_check_node_type($node) {
254
  // Fetch information about the forum field.
255
  $field = field_info_instance('node', 'taxonomy_forums', $node->type);
256

257
  return is_array($field);
258
}
259

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

279 280 281
    }
  }
}
282

283
/**
284
 * Implements hook_node_validate().
285
 *
286 287
 * Check in particular that only a "leaf" term in the associated taxonomy.
 */
288
function forum_node_validate($node, $form) {
289 290
  if (_forum_node_check_node_type($node)) {
    $langcode = $form['taxonomy_forums']['#language'];
291
    // vocabulary is selected, not a "container" term.
292
    if (!empty($node->taxonomy_forums[$langcode])) {
293 294
      // Extract the node's proper topic ID.
      $containers = variable_get('forum_containers', array());
295 296 297 298 299 300 301
      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;
        }
302
        $term = taxonomy_term_load($item['tid']);
303 304 305 306
        if (!$term) {
          form_set_error('taxonomy_forums', t('Select a forum.'));
          continue;
        }
307 308 309
        $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,
310
        ))->fetchField();
311
        if ($used && in_array($term->tid, $containers)) {
312
          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)));
313 314
        }
      }
315 316 317
    }
  }
}
318

319
/**
320
 * Implements hook_node_presave().
321 322 323
 *
 * Assign forum taxonomy when adding a topic from within a forum.
 */
324
function forum_node_presave($node) {
325
  if (_forum_node_check_node_type($node)) {
326 327
    // Make sure all fields are set properly:
    $node->icon = !empty($node->icon) ? $node->icon : '';
328 329
    reset($node->taxonomy_forums);
    $langcode = key($node->taxonomy_forums);
330
    if (!empty($node->taxonomy_forums[$langcode])) {
331
      $node->forum_tid = $node->taxonomy_forums[$langcode][0]['tid'];
332
      $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();
333
      if ($old_tid && isset($node->forum_tid) && ($node->forum_tid != $old_tid) && !empty($node->shadow)) {
334
        // A shadow copy needs to be created. Retain new term and add old term.
335
        $node->taxonomy_forums[$langcode][] = array('tid' => $old_tid);
336 337 338 339
      }
    }
  }
}
340

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

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

406
/**
407
 * Implements hook_node_delete().
408
 */
409
function forum_node_delete($node) {
410
  if (_forum_node_check_node_type($node)) {
411 412 413
    db_delete('forum')
      ->condition('nid', $node->nid)
      ->execute();
414 415 416
    db_delete('forum_index')
      ->condition('nid', $node->nid)
      ->execute();
417
  }
418
}
419

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

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

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

468
/**
469
 * Implements hook_taxonomy_term_delete().
470
 */
471 472 473 474 475 476 477 478 479
function forum_taxonomy_term_delete($tid) {
  // For containers, remove the tid from the forum_containers variable.
  $containers = variable_get('forum_containers', array());
  $key = array_search($tid, $containers);
  if ($key !== FALSE) {
    unset($containers[$key]);
  }
  variable_set('forum_containers', $containers);
}
480

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

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

/**
506
 * Implements hook_comment_unpublish().
507 508 509 510 511 512
 */
function forum_comment_unpublish($comment) {
  _forum_update_forum_index($comment->nid);
}

/**
513
 * Implements hook_comment_delete().
514 515 516 517 518 519
 */
function forum_comment_delete($comment) {
  _forum_update_forum_index($comment->nid);
}

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

/**
543
 * Implements hook_field_storage_pre_update().
544
 */
545
function forum_field_storage_pre_update($entity_type, $entity, &$skip_fields) {
546 547
  $first_call = &drupal_static(__FUNCTION__, array());

548
  if ($entity_type == 'node' && $entity->status && _forum_node_check_node_type($entity)) {
549 550 551
    // 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.
552 553 554
    if (!isset($first_call[$entity->nid])) {
      $first_call[$entity->nid] = FALSE;
      db_delete('forum_index')->condition('nid', $entity->nid)->execute();
555 556
    }
    // Only save data to the table if the node is published.
557
    if ($entity->status) {
558
      $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
559
      foreach ($entity->taxonomy_forums as $language) {
560
        foreach ($language as $item) {
561
          $query->values(array(
562 563
            'nid' => $entity->nid,
            'title' => $entity->title,
564
            'tid' => $item['tid'],
565 566
            'sticky' => $entity->sticky,
            'created' => $entity->created,
567
            'comment_count' => 0,
568
            'last_comment_timestamp' => $entity->created,
569
          ));
570
        }
571 572 573 574
      }
      $query->execute();
      // The logic for determining last_comment_count is fairly complex, so
      // call _forum_update_forum_index() too.
575
      _forum_update_forum_index($entity->nid);
Dries's avatar
 
Dries committed
576
    }
577 578
  }
}
Dries's avatar
 
Dries committed
579

580
/**
581
 * Implements hook_form_alter().
582
 */
583
function forum_form_alter(&$form, $form_state, $form_id) {
584
  $vid = variable_get('forum_nav_vocabulary', 0);
585 586 587
  if (isset($form['vid']) && $form['vid']['#value'] == $vid) {
    // Hide critical options from forum vocabulary.
    if ($form_id == 'taxonomy_form_vocabulary') {
588
      $form['help_forum_vocab'] = array(
589
        '#markup' => t('This is the designated forum vocabulary. Some of the normal vocabulary options have been removed.'),
590 591 592
        '#weight' => -1,
      );
      $form['hierarchy'] = array('#type' => 'value', '#value' => 1);
593
      $form['delete']['#access'] = FALSE;
594
    }
595 596 597
    // Hide multiple parents select from forum terms.
    elseif ($form_id == 'taxonomy_form_term') {
      $form['advanced']['parent']['#access'] = FALSE;
598
    }
599
  }
600
  if (!empty($form['#node_edit_form']) && isset($form['taxonomy_forums'])) {
601
    $langcode = $form['taxonomy_forums']['#language'];
602
    // Make the vocabulary required for 'real' forum-nodes.
603 604
    $form['taxonomy_forums'][$langcode]['#required'] = TRUE;
    $form['taxonomy_forums'][$langcode]['#multiple'] = FALSE;
605 606
    if (empty($form['taxonomy_forums'][$langcode]['#default_value'])) {
      // If there is no default forum already selected, try to get the forum
607 608
      // 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).
609
      $requested_forum_id = arg(3);
610
      $form['taxonomy_forums'][$langcode]['#default_value'] = is_numeric($requested_forum_id) ? $requested_forum_id : '';
611
    }
612
  }
613 614
}

615
/**
616
 * Implements hook_block_info().
617
 */
618
function forum_block_info() {
619 620 621
  $blocks['active'] = array(
    'info' => t('Active forum topics'),
    'cache' => DRUPAL_CACHE_CUSTOM,
622
    'properties' => array('administrative' => TRUE),
623 624 625 626
  );
  $blocks['new'] = array(
    'info' => t('New forum topics'),
    'cache' => DRUPAL_CACHE_CUSTOM,
627
    'properties' => array('administrative' => TRUE),
628
  );
629 630 631 632
  return $blocks;
}

/**
633
 * Implements hook_block_configure().
634 635 636 637 638 639 640
 */
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;
}

/**
641
 * Implements hook_block_save().
642 643 644 645 646 647
 */
function forum_block_save($delta = '', $edit = array()) {
  variable_set('forum_block_num_' . $delta, $edit['forum_block_num_' . $delta]);
}

/**
648
 * Implements hook_block_view().
649 650 651 652
 *
 * Generates a block containing the currently active forum topics and the
 * most recently added forum topics.
 */
653
function forum_block_view($delta = '') {
654 655
  $query = db_select('forum_index', 'f')
    ->fields('f')
656 657 658 659 660
    ->addTag('node_access');
  switch ($delta) {
    case 'active':
      $title = t('Active forum topics');
      $query
661
        ->orderBy('f.last_comment_timestamp', 'DESC')
662 663 664 665 666 667
        ->range(0, variable_get('forum_block_num_active', '5'));
      break;

    case 'new':
      $title = t('New forum topics');
      $query
668
        ->orderBy('f.created', 'DESC')
669 670 671
        ->range(0, variable_get('forum_block_num_new', '5'));
      break;
  }
Dries's avatar
 
Dries committed
672

673
  $block['subject'] = $title;
674 675 676
  // 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');
677
  return $block;
678
}
679

680 681 682
/**
* A #pre_render callback. Lists nodes based on the element's #query property.
*
683
* @see forum_block_view()
684 685 686 687 688 689 690
*
* @return
*   A renderable array.
*/
function forum_block_view_pre_render($elements) {
  $result = $elements['#query']->execute();
  if ($node_title_list = node_title_list($result)) {
691
    $elements['forum_list'] = $node_title_list;
692
    $elements['forum_more'] = array('#theme' => 'more_link', '#url' => 'forum', '#title' => t('Read the latest forum topics.'));
693
  }
694
  return $elements;
Dries's avatar
 
Dries committed
695 696
}

697
/**
698
 * Implements hook_form().
699
 */
700
function forum_form($node, $form_state) {
701
  $type = node_type_get_type($node);
702 703 704 705 706 707
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE, '#weight' => -5
  );
708

709
  if (!empty($node->nid)) {
710 711
    $forum_terms = $node->taxonomy_forums;
    // If editing, give option to leave shadows
712
    $shadow = (count($forum_terms) > 1);
713
    $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.'));
714
    $form['forum_tid'] = array('#type' => 'value', '#value' => $node->forum_tid);
Dries's avatar
Dries committed
715
  }
Dries's avatar
 
Dries committed
716

717
  return $form;
Dries's avatar
 
Dries committed
718 719
}

Dries's avatar
 
Dries committed
720
/**
721
 * Returns a tree of all forums for a given taxonomy term ID.
Dries's avatar
 
Dries committed
722 723
 *
 * @param $tid
724
 *    (optional) Taxonomy ID of the forum, if not givin all forums will be returned.
Dries's avatar
 
Dries committed
725
 * @return
726 727 728 729 730
 *   A tree of taxonomy objects, with the following additional properties:
 *    - '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
731
 */
732
function forum_forum_load($tid = NULL) {
733 734
  $cache = &drupal_static(__FUNCTION__, array());

735 736 737 738
  // Return a cached forum tree if available.
  if (!isset($tid)) {
    $tid = 0;
  }
739 740 741
  if (isset($cache[$tid])) {
    return $cache[$tid];
  }
742

743
  $vid = variable_get('forum_nav_vocabulary', 0);
744 745 746 747 748 749 750 751 752

  // Load and validate the parent term.
  if ($tid) {
    $forum_term = taxonomy_term_load($tid);
    if (!$forum_term || ($forum_term->vid != $vid)) {
      return $cache[$tid] = FALSE;
    }
  }
  // If $tid is 0, create an empty object to hold the child terms.
753
  elseif ($tid === 0) {
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    $forum_term = (object) array(
      'tid' => 0,
    );
  }

  // Determine if the requested term is a container.
  if (!$forum_term->tid || in_array($forum_term->tid, variable_get('forum_containers', array()))) {
    $forum_term->container = 1;
  }

  // Load parent terms.
  $forum_term->parents = taxonomy_get_parents_all($forum_term->tid);

  // Load the tree below.
  $forums = array();
769
  $_forums = taxonomy_get_tree($vid, $tid);
Dries's avatar
 
Dries committed
770

Dries's avatar
 
Dries committed
771
  if (count($_forums