forum.module 43 KB
Newer Older
Dries's avatar
Dries committed
1 2 3
<?php
// $Id$

4 5
/**
 * @file
6
 * Provides discussion forums.
7 8
 */

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

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

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

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

  // Add action link to 'node/add/forum' on 'forum' page.
  if ($root_path == 'forum') {
    $tid = (isset($router_item['page_arguments'][0]) ? $router_item['page_arguments'][0] : 0);
173 174
    $forum_term = forum_forum_load($tid);
    if ($forum_term) {
175 176 177 178 179 180 181 182 183 184 185 186
      $vid = variable_get('forum_nav_vocabulary', 0);
      $vocabulary = taxonomy_vocabulary_load($vid);

      $links = array();
      // Loop through all bundles for forum taxonomy vocabulary field.
      $field = field_info_field('taxonomy_' . $vocabulary->machine_name);
      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))),
187
              'href' => 'node/add/' . str_replace('_', '-', $type) . '/' . $forum_term->tid,
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
            ),
          );
        }
      }
      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(
207
              'title' => t('<a href="@login">Log in</a> to post new content in the forum.', array(
208 209 210 211 212 213 214 215 216 217 218
                '@login' => url('user/login', array('query' => drupal_get_destination())),
              )),
              'localized_options' => array('html' => TRUE),
            ),
          );
        }
      }
      $data['actions']['output'] = array_merge($data['actions']['output'], $links);
    }
  }
}
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 244 245 246 247 248 249
/**
 * 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,
  );
}

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

263
  return is_array($field);
264
}
265

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

285 286 287
    }
  }
}
288

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

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

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

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

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

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

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

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

474
/**
475
 * Implements hook_taxonomy_term_delete().
476
 */
477 478 479 480 481 482 483 484 485
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);
}
486

487
/**
488
 * Implements hook_comment_publish().
489 490 491 492 493 494 495 496 497
 *
 * 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);
}

/**
498
 * Implements hook_comment_update().
499 500 501 502 503 504 505 506 507 508 509 510 511
 *
 * 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);
  }
}

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

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

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

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

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

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

621
/**
622
 * Implements hook_block_info().
623
 */
624
function forum_block_info() {
625 626 627 628 629 630 631 632
  $blocks['active'] = array(
    'info' => t('Active forum topics'),
    'cache' => DRUPAL_CACHE_CUSTOM,
  );
  $blocks['new'] = array(
    'info' => t('New forum topics'),
    'cache' => DRUPAL_CACHE_CUSTOM,
  );
633 634 635 636
  return $blocks;
}

/**
637
 * Implements hook_block_configure().
638 639 640 641 642 643 644
 */
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;
}

/**
645
 * Implements hook_block_save().
646 647 648 649 650 651
 */
function forum_block_save($delta = '', $edit = array()) {
  variable_set('forum_block_num_' . $delta, $edit['forum_block_num_' . $delta]);
}

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

    case 'new':
      $title = t('New forum topics');
      $query
672
        ->orderBy('f.created', 'DESC')
673 674 675
        ->range(0, variable_get('forum_block_num_new', '5'));
      break;
  }
676

677
  $block['subject'] = $title;
678 679 680
  // 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');
681
  return $block;
682
}
683

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

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

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

721
  return $form;
Dries's avatar
Dries committed
722 723
}

724
/**
725
 * Returns a tree of all forums for a given taxonomy term ID.
726 727
 *
 * @param $tid
728
 *    (optional) Taxonomy ID of the forum, if not givin all forums will be returned.
729
 * @return
730 731 732 733 734
 *   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
735
 */
736
function forum_forum_load($tid = NULL) {
737 738
  $cache = &drupal_static(__FUNCTION__, array());

739 740 741 742
  // Return a cached forum tree if available.
  if (!isset($tid)) {
    $tid = 0;
  }
743 744 745
  if (isset($cache[$tid])) {
    return $cache[$tid];
  }
746

747
  $vid = variable_get('forum_nav_vocabulary', 0);
748 749 750 751 752 753 754 755 756

  // 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.
757
  elseif ($tid === 0) {
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    $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();
773
  $_forums = taxonomy_get_tree($vid, $tid);
774

775
  if (count($_forums)) {
776 777
    $query = db_select('node', 'n');
    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
778
    $query->join('forum', 'f', 'n.vid = f.vid');
779 780 781
    $query->addExpression('COUNT(n.nid)', 'topic_count');
    $query->addExpression('SUM(ncs.comment_count)', 'comment_count');
    $counts = $query
782
      ->fields('f', array('tid'))
783 784 785 786 787
      ->condition('status', 1)
      ->groupBy('tid')
      ->addTag('node_access')
      ->execute()
      ->fetchAllAssoc('tid');
788
  }
789

790
  foreach ($_forums as $forum) {
791
    // Determine if the child term is a container.
792 793 794
    if (in_array($forum->tid, variable_get('forum_containers', array()))) {
      $forum->container = 1;
    }
795

796
    // Merge in the topic and post counters.
797
    if (!empty($counts[$forum->tid])) {
798 799 800 801 802 803 804 805
      $forum->num_topics = $counts[$forum->tid]->topic_count;
      $forum->num_posts = $counts[$forum->tid]->topic_count + $counts[$forum->tid]->comment_count;
    }
    else {
      $forum->num_topics = 0;
      $forum->num_posts = 0;
    }

806
    // Query "Last Post" information for this forum.
807 808
    $query = db_select('node', 'n');
    $query->join('users', 'u1', 'n.uid = u1.uid');
809
    $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $forum->tid));
810 811
    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
    $query->join('users', 'u2', 'ncs.last_comment_uid = u2.uid');
812
    $query->addExpression('CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u2.name END', 'last_comment_name');
813

814 815 816 817 818 819 820 821
    $topic = $query
      ->fields('ncs', array('last_comment_timestamp', 'last_comment_uid'))
      ->condition('n.status', 1)
      ->orderBy('last_comment_timestamp', 'DESC')
      ->range(0, 1)
      ->addTag('node_access')
      ->execute()
      ->fetchObject();
822

823
    // Merge in the "Last Post" information.
824
    $last_post = new stdClass();
825
    if (!empty($topic->last_comment_timestamp)) {
826
      $last_post->created = $topic->last_comment_timestamp;
827 828 829
      $last_post->name = $topic->last_comment_name;
      $last_post->uid = $topic->last_comment_uid;
    }
830
    $forum->last_post = $last_post;
831

832 833 834
    $forums[$forum->tid] = $forum;
  }

835 836 837 838
  // Cache the result, and return the tree.
  $forum_term->forums = $forums;
  $cache[$tid] = $forum_term;
  return $forum_term;
839 840
}

841 842 843 844 845
/**
 * Calculate the number of nodes the user has not yet read and are newer
 * than NODE_NEW_LIMIT.
 */
function _forum_topics_unread($term, $uid) {
846
  $query = db_select('node', 'n');
847
  $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $term));
848
  $query->leftJoin('history', 'h', 'n.nid = h.nid AND h.uid = :uid', array(':uid' => $uid));
849 850 851 852 853 854 855 856
  $query->addExpression('COUNT(n.nid)', 'count');
  return $query
    ->condition('status', 1)
    ->condition('n.created', NODE_NEW_LIMIT, '>')
    ->isNull('h.nid')
    ->addTag('node_access')
    ->execute()
    ->fetchField();
857 858
}

Dries's avatar
Dries committed
859
function forum_get_topics($tid, $sortby, $forum_per_page) {
860
  global $user, $forum_topic_list_header;
861

862
  $forum_topic_list_header = array(
863
    NULL,
864 865 866
    array('data' => t('Topic'), 'field' => 'f.title'),
    array('data' => t('Replies'), 'field' => 'f.comment_count'),
    array('data' => t('Last reply'), 'field' => 'f.last_comment_timestamp'),
867
  );
868

Dries's avatar
Dries committed
869
  $order = _forum_get_topic_order($sortby);
870
  for ($i = 0; $i < count($forum_topic_list_header); $i++) {
Dries's avatar
Dries committed
871 872
    if ($forum_topic_list_header[$i]['field'] == $order['field']) {
      $forum_topic_list_header[$i]['sort'] = $order['sort'];
873 874 875
    }
  }

876 877
  $query = db_select('forum_index', 'f')->extend('PagerDefault')->extend('TableSort');
  $query->fields('f');
878
  $query
879
    ->condition('f.tid', $tid)
880
    ->addTag('node_access')
881
    ->orderBy('f.sticky', 'DESC')
882
    ->orderByHeader($forum_topic_list_header)
883
    ->orderBy('f.last_comment_timestamp', 'DESC')
884
    ->limit($forum_per_page);
885

886 887
  $count_query = db_select('forum_index', 'f');
  $count_query->condition('f.tid', $tid);
888
  $count_query->addExpression('COUNT(*)');
889
  $count_query->addTag('node_access');
890

891 892
  $query->setCountQuery($count_query);
  $result = $query->execute();
893 894 895 896 897
  $nids = array();
  foreach ($result as $record) {
    $nids[] = $record->nid;
  }
  if ($nids) {
898
    $result = db_query("SELECT n.title, n.nid, n.type, n.sticky, n.created, n.uid, n.comment AS comment_mode, ncs.*, f.tid AS forum_tid, u.name, CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u2.name END AS last_comment_name FROM {node} n INNER JOIN {node_comment_statistics} ncs ON n.nid = ncs.nid INNER JOIN {forum} f ON n.vid = f.vid INNER JOIN {users} u ON n.uid = u.uid INNER JOIN {users} u2 ON ncs.last_comment_uid = u2.uid WHERE n.nid IN (:nids)", array(':nids' => $nids));
899 900 901 902 903
  }
  else {
    $result = array();
  }

904
  $topics = array();
905
  foreach ($result as $topic) {
Dries's avatar
Dries committed
906 907
    if ($user->uid) {
      // folder is new if topic is new or there are new comments since last visit