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

Dries's avatar
 
Dries committed
4 5
/**
 * @file
6
 * Provides discussion forums.
Dries's avatar
 
Dries committed
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
      return '<p>' . t('Forums contain forum topics. Use containers to group related forums.') . '</p>';
44
    case 'admin/structure/forum/add/container':
45
      return '<p>' . t('Use containers to group related forums.') . '</p>';
46
    case 'admin/structure/forum/add/forum':
47
      return '<p>' . t('A forum holds related forum topics.') . '</p>';
48
    case 'admin/structure/forum/settings':
49
      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
50 51 52
  }
}

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

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

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
/**
 * 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);
    $forums = forum_get_forums($tid);
    $parents = taxonomy_get_parents_all($tid);
    if ($forums || $parents) {
      $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))),
              'href' => 'node/add/' . str_replace('_', '-', $type) . '/' . $tid,
            ),
          );
        }
      }
      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(
              'title' => t('<a href="@login">Login</a> to post new content in the forum.', array(
                '@login' => url('user/login', array('query' => drupal_get_destination())),
              )),
              'localized_options' => array('html' => TRUE),
            ),
          );
        }
      }
      $data['actions']['output'] = array_merge($data['actions']['output'], $links);
    }
  }
}
211 212

/**
213
 * Implements hook_init().
214
 */
215
function forum_init() {
216
  drupal_add_css(drupal_get_path('module', 'forum') . '/forum.css');
217
}
218

219
/**
220 221 222 223
 * Check whether a content type can be used in a forum.
 *
 * @param $node
 *   A node object.
224
 *
225 226
 * @return
 *   Boolean indicating if the node can be assigned to a forum.
227
 */
228
function _forum_node_check_node_type($node) {
229
  // Fetch information about the forum field.
230
  $field = field_info_instance('node', 'taxonomy_forums', $node->type);
231

232
  return is_array($field);
233
}
234

235
/**
236
 * Implements hook_node_view().
237
 */
238
function forum_node_view($node, $view_mode) {
239
  $vid = variable_get('forum_nav_vocabulary', 0);
240
  $vocabulary = taxonomy_vocabulary_load($vid);
241
  if (_forum_node_check_node_type($node)) {
242
    if (node_is_page($node)) {
243 244 245
      // Breadcrumb navigation
      $breadcrumb[] = l(t('Home'), NULL);
      $breadcrumb[] = l($vocabulary->name, 'forum');
246
      if ($parents = taxonomy_get_parents_all($node->forum_tid)) {
247
        $parents = array_reverse($parents);
248 249
        foreach ($parents as $parent) {
          $breadcrumb[] = l($parent->name, 'forum/' . $parent->tid);
250 251 252
        }
      }
      drupal_set_breadcrumb($breadcrumb);
253

254 255 256
    }
  }
}
257

258
/**
259
 * Implements hook_node_prepare().
260
 */
261
function forum_node_prepare($node) {
262
  if (_forum_node_check_node_type($node)) {
263 264
    if (empty($node->nid)) {
      // New topic
265
      $node->taxonomy_forums[0]['tid'] =  arg(3);
266 267 268 269 270
    }
  }
}

/**
271
 * Implements hook_node_validate().
272
 *
273 274
 * Check in particular that only a "leaf" term in the associated taxonomy.
 */
275
function forum_node_validate($node, $form) {
276 277
  if (_forum_node_check_node_type($node)) {
    $langcode = $form['taxonomy_forums']['#language'];
278
    // vocabulary is selected, not a "container" term.
279
    if (!empty($node->taxonomy_forums[$langcode])) {
280 281
      // Extract the node's proper topic ID.
      $containers = variable_get('forum_containers', array());
282 283
      foreach ($node->taxonomy_forums[$langcode] as $item) {
        $term = taxonomy_term_load($item['tid']);
284 285 286
        $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,
287
        ))->fetchField();
288
        if ($used && in_array($term->tid, $containers)) {
289
          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)));
290 291
        }
      }
292 293 294
    }
  }
}
295

296
/**
297
 * Implements hook_node_presave().
298 299 300
 *
 * Assign forum taxonomy when adding a topic from within a forum.
 */
301
function forum_node_presave($node) {
302
  if (_forum_node_check_node_type($node)) {
303 304
    // Make sure all fields are set properly:
    $node->icon = !empty($node->icon) ? $node->icon : '';
305 306
    $langcode = array_shift(array_keys($node->taxonomy_forums));
    if (!empty($node->taxonomy_forums[$langcode])) {
307
      $node->forum_tid = $node->taxonomy_forums[$langcode][0]['tid'];
308
      $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();
309
      if ($old_tid && isset($node->forum_tid) && ($node->forum_tid != $old_tid) && !empty($node->shadow)) {
310
        // A shadow copy needs to be created. Retain new term and add old term.
311
        $node->taxonomy_forums[$langcode][] = array('tid' => $old_tid);
312 313 314 315
      }
    }
  }
}
316

317
/**
318
 * Implements hook_node_update().
319
 */
320
function forum_node_update($node) {
321
  if (_forum_node_check_node_type($node)) {
322
    if (empty($node->revision) && db_query('SELECT tid FROM {forum} WHERE nid=:nid', array(':nid' => $node->nid))->fetchField()) {
323
      if (!empty($node->forum_tid)) {
324
        db_update('forum')
325
          ->fields(array('tid' => $node->forum_tid))
326 327
          ->condition('vid', $node->vid)
          ->execute();
328 329 330
      }
      // The node is removed from the forum.
      else {
331 332 333
        db_delete('forum')
          ->condition('nid', $node->nid)
          ->execute();
334 335 336
      }
    }
    else {
337
      if (!empty($node->forum_tid)) {
338 339
        db_insert('forum')
          ->fields(array(
340
            'tid' => $node->forum_tid,
341 342 343 344
            'vid' => $node->vid,
            'nid' => $node->nid,
          ))
          ->execute();
345
      }
346
    }
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    // 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();
     }
362 363
  }
}
364

365
/**
366
 * Implements hook_node_insert().
367
 */
368
function forum_node_insert($node) {
369 370
  if (_forum_node_check_node_type($node)) {
    if (!empty($node->forum_tid)) {
371 372
      $nid = db_insert('forum')
        ->fields(array(
373
          'tid' => $node->forum_tid,
374 375 376 377
          'vid' => $node->vid,
          'nid' => $node->nid,
        ))
        ->execute();
378 379 380
    }
  }
}
381

382
/**
383
 * Implements hook_node_delete().
384
 */
385
function forum_node_delete($node) {
386
  if (_forum_node_check_node_type($node)) {
387 388 389
    db_delete('forum')
      ->condition('nid', $node->nid)
      ->execute();
390 391 392
    db_delete('forum_index')
      ->condition('nid', $node->nid)
      ->execute();
393
  }
394
}
395

396
/**
397
 * Implements hook_node_load().
398
 */
399
function forum_node_load($nodes) {
400 401
  $node_vids = array();
  foreach ($nodes as $node) {
402
    if (_forum_node_check_node_type($node)) {
403 404 405 406
      $node_vids[] = $node->vid;
    }
  }
  if (!empty($node_vids)) {
407 408 409 410 411
    $query = db_select('forum', 'f');
    $query
      ->fields('f', array('nid', 'tid'))
      ->condition('f.vid', $node_vids);
    $result = $query->execute();
412 413 414
    foreach ($result as $record) {
      $nodes[$record->nid]->forum_tid = $record->tid;
    }
415
  }
416 417
}

418
/**
419
 * Implements hook_node_info().
420
 */
421
function forum_node_info() {
422 423
  return array(
    'forum' => array(
424
      'name' => t('Forum topic'),
425
      'base' => 'forum',
426
      'description' => t('A <em>forum topic</em> starts a new discussion thread within a forum.'),
427 428 429
      'title_label' => t('Subject'),
    )
  );
Dries's avatar
 
Dries committed
430 431
}

432
/**
433
 * Implements hook_permission().
434
 */
435
function forum_permission() {
436
  $perms = array(
437 438 439
    'administer forums' => array(
      'title' => t('Administer forums'),
    ),
440 441
  );
  return $perms;
Dries's avatar
 
Dries committed
442
}
Dries's avatar
 
Dries committed
443

444
/**
445
 * Implements hook_taxonomy_term_delete().
446
 */
447 448 449 450 451 452 453 454 455
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);
}
456

457
/**
458
 * Implements hook_comment_publish().
459 460 461 462 463 464 465 466 467
 *
 * 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);
}

/**
468
 * Implements hook_comment_update().
469 470 471 472 473 474 475 476 477 478 479 480 481
 *
 * 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);
  }
}

/**
482
 * Implements hook_comment_unpublish().
483 484 485 486 487 488
 */
function forum_comment_unpublish($comment) {
  _forum_update_forum_index($comment->nid);
}

/**
489
 * Implements hook_comment_delete().
490 491 492 493 494 495
 */
function forum_comment_delete($comment) {
  _forum_update_forum_index($comment->nid);
}

/**
496
 * Implements hook_field_storage_pre_insert().
497
 */
498
function forum_field_storage_pre_insert($obj_type, $object, &$skip_fields) {
499 500 501
  if ($obj_type == 'node' && $object->status && _forum_node_check_node_type($object)) {
    $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
    foreach ($object->taxonomy_forums as $language) {
502
      foreach ($language as $item) {
503 504
        $query->values(array(
          'nid' => $object->nid,
505
          'title' => $object->title,
506
          'tid' => $item['tid'],
507 508 509 510 511 512 513 514 515 516 517 518
          'sticky' => $object->sticky,
          'created' => $object->created,
          'comment_count' => 0,
          'last_comment_timestamp' => $object->created,
        ));
      }
    }
    $query->execute();
  }
}

/**
519
 * Implements hook_field_storage_pre_update().
520
 */
521
function forum_field_storage_pre_update($obj_type, $object, &$skip_fields) {
522 523 524 525 526 527 528 529 530 531 532 533 534 535
  $first_call = &drupal_static(__FUNCTION__, array());

  if ($obj_type == 'node' && $object->status && _forum_node_check_node_type($object)) {
    // 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[$object->nid])) {
      $first_call[$object->nid] = FALSE;
      db_delete('forum_index')->condition('nid', $object->nid)->execute();
    }
    // Only save data to the table if the node is published.
    if ($object->status) {
      $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
      foreach ($object->taxonomy_forums as $language) {
536
        foreach ($language as $item) {
537 538
          $query->values(array(
            'nid' => $object->nid,
539
            'title' => $object->title,
540
            'tid' => $item['tid'],
541 542 543 544 545
            'sticky' => $object->sticky,
            'created' => $object->created,
            'comment_count' => 0,
            'last_comment_timestamp' => $object->created,
          ));
546
        }
547 548 549 550 551
      }
      $query->execute();
      // The logic for determining last_comment_count is fairly complex, so
      // call _forum_update_forum_index() too.
      _forum_update_forum_index($object->nid);
Dries's avatar
 
Dries committed
552
    }
553 554
  }
}
Dries's avatar
 
Dries committed
555

556
/**
557
 * Implements hook_form_alter().
558
 */
559
function forum_form_alter(&$form, $form_state, $form_id) {
560
  $vid = variable_get('forum_nav_vocabulary', 0);
561 562 563
  if (isset($form['vid']) && $form['vid']['#value'] == $vid) {
    // Hide critical options from forum vocabulary.
    if ($form_id == 'taxonomy_form_vocabulary') {
564
      $form['help_forum_vocab'] = array(
565
        '#markup' => t('This is the designated forum vocabulary. Some of the normal vocabulary options have been removed.'),
566 567 568
        '#weight' => -1,
      );
      $form['hierarchy'] = array('#type' => 'value', '#value' => 1);
569
      $form['delete']['#access'] = FALSE;
570
    }
571 572 573
    // Hide multiple parents select from forum terms.
    elseif ($form_id == 'taxonomy_form_term') {
      $form['advanced']['parent']['#access'] = FALSE;
574
    }
575
  }
576
  if ($form_id == 'forum_node_form') {
577
    $langcode = $form['taxonomy_forums']['#language'];
578
    // Make the vocabulary required for 'real' forum-nodes.
579 580
    $form['taxonomy_forums'][$langcode]['#required'] = TRUE;
    $form['taxonomy_forums'][$langcode]['#multiple'] = FALSE;
581
  }
582 583
}

584
/**
585
 * Implements hook_block_info().
586
 */
587
function forum_block_info() {
588 589 590 591 592 593 594 595
  $blocks['active'] = array(
    'info' => t('Active forum topics'),
    'cache' => DRUPAL_CACHE_CUSTOM,
  );
  $blocks['new'] = array(
    'info' => t('New forum topics'),
    'cache' => DRUPAL_CACHE_CUSTOM,
  );
596 597 598 599
  return $blocks;
}

/**
600
 * Implements hook_block_configure().
601 602 603 604 605 606 607
 */
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;
}

/**
608
 * Implements hook_block_save().
609 610 611 612 613 614
 */
function forum_block_save($delta = '', $edit = array()) {
  variable_set('forum_block_num_' . $delta, $edit['forum_block_num_' . $delta]);
}

/**
615
 * Implements hook_block_view().
616 617 618 619
 *
 * Generates a block containing the currently active forum topics and the
 * most recently added forum topics.
 */
620
function forum_block_view($delta = '') {
621 622
  $query = db_select('forum_index', 'f')
    ->fields('f')
623 624 625 626 627
    ->addTag('node_access');
  switch ($delta) {
    case 'active':
      $title = t('Active forum topics');
      $query
628
        ->orderBy('f.last_comment_timestamp', 'DESC')
629 630 631 632 633 634
        ->range(0, variable_get('forum_block_num_active', '5'));
      break;

    case 'new':
      $title = t('New forum topics');
      $query
635
        ->orderBy('f.created', 'DESC')
636 637 638
        ->range(0, variable_get('forum_block_num_new', '5'));
      break;
  }
Dries's avatar
 
Dries committed
639

640 641 642 643 644 645 646
  $cache_keys = array_merge(array('forum', $delta), drupal_render_cid_parts());
  // Cache based on the altered query. Enables us to cache with node access enabled.
  $query->preExecute();
  $cache_keys[] = md5(serialize(array((string) $query, $query->getArguments())));

  $block['subject'] = $title;
  $block['content'] = array(
647 648 649 650 651 652 653
     '#access' => user_access('access content'),
     '#pre_render' => array('forum_block_view_pre_render'),
     '#cache' => array(
        'keys' => $cache_keys,
        'expire' => CACHE_TEMPORARY,
     ),
     '#query' => $query,
654 655
  );
  return $block;
656
}
657

658 659 660 661 662 663 664 665 666 667 668 669
/**
* A #pre_render callback. Lists nodes based on the element's #query property.
*
* @see forum_block_view().
*
* @return
*   A renderable array.
*/
function forum_block_view_pre_render($elements) {
  $result = $elements['#query']->execute();
  if ($node_title_list = node_title_list($result)) {
    $elements['forum_list'] = array('#markup' => $node_title_list);
670
    $elements['forum_more'] = array('#markup' => theme('more_link', array('url' => url('forum'), 'title' => t('Read the latest forum topics.'))));
671
  }
672
  return $elements;
Dries's avatar
 
Dries committed
673 674
}

675
/**
676
 * Implements hook_form().
677
 */
678
function forum_form($node, $form_state) {
679
  $type = node_type_get_type($node);
680 681 682 683 684 685
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE, '#weight' => -5
  );
686

687
  if (!empty($node->nid)) {
688 689
    $forum_terms = $node->taxonomy_forums;
    // If editing, give option to leave shadows
690
    $shadow = (count($forum_terms) > 1);
691
    $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.'));
692
    $form['forum_tid'] = array('#type' => 'value', '#value' => $node->forum_tid);
Dries's avatar
Dries committed
693
  }
Dries's avatar
 
Dries committed
694

695 696 697
  $form['#submit'][] = 'forum_submit';
  // Assign the forum topic submit handler.

698
  return $form;
Dries's avatar
 
Dries committed
699 700
}

701
/**
702
 * Implements hook_url_outbound_alter().
703
 */
704 705 706 707 708 709 710
function forum_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('!^taxonomy/term/(\d+)!', $path, $matches)) {
    $term = taxonomy_term_load($matches[1]);
    if ($term && $term->vocabulary_machine_name == 'forums') {
      $path = 'forum/' . $matches[1];
    }
  }
711 712
}

Dries's avatar
 
Dries committed
713 714 715
/**
 * Returns a list of all forums for a given taxonomy id
 *
716
 * Forum objects contain the following fields
Dries's avatar
 
Dries committed
717 718 719 720 721 722 723 724 725
 * -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
 *
 * @param $tid
 *   Taxonomy ID of the vocabulary that holds the forum list.
 * @return
 *   Array of object containing the forum information.
 */
Dries's avatar
 
Dries committed
726
function forum_get_forums($tid = 0) {
727 728 729 730 731
  $cache = &drupal_static(__FUNCTION__, array());

  if (isset($cache[$tid])) {
    return $cache[$tid];
  }
732

Dries's avatar
 
Dries committed
733
  $forums = array();
734
  $vid = variable_get('forum_nav_vocabulary', 0);
735
  $_forums = taxonomy_get_tree($vid, $tid);
Dries's avatar
 
Dries committed
736

Dries's avatar
 
Dries committed
737
  if (count($_forums)) {
738 739
    $query = db_select('node', 'n');
    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
740
    $query->join('forum', 'f', 'n.vid = f.vid');
741 742 743
    $query->addExpression('COUNT(n.nid)', 'topic_count');
    $query->addExpression('SUM(ncs.comment_count)', 'comment_count');
    $counts = $query
744
      ->fields('f', array('tid'))
745 746 747 748 749
      ->condition('status', 1)
      ->groupBy('tid')
      ->addTag('node_access')
      ->execute()
      ->fetchAllAssoc('tid');
Dries's avatar
 
Dries committed
750
  }
Dries's avatar
 
Dries committed
751

Dries's avatar
 
Dries committed
752 753 754 755
  foreach ($_forums as $forum) {
    if (in_array($forum->tid, variable_get('forum_containers', array()))) {
      $forum->container = 1;
    }
Dries's avatar
 
Dries committed
756

757
    if (!empty($counts[$forum->tid])) {
Dries's avatar
 
Dries committed
758 759 760 761 762 763 764 765
      $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;
    }

766 767
    $query = db_select('node', 'n');
    $query->join('users', 'u1', 'n.uid = u1.uid');
768
    $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $forum->tid));
769 770 771
    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
    $query->join('users', 'u2', 'ncs.last_comment_uid = u2.uid');
    $query->addExpression('IF (ncs.last_comment_uid != 0, u2.name, ncs.last_comment_name)', 'last_comment_name');
772

773 774 775 776 777 778 779 780
    $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();
781

782
    $last_post = new stdClass();
783
    if (!empty($topic->last_comment_timestamp)) {
784
      $last_post->created = $topic->last_comment_timestamp;
785 786 787
      $last_post->name = $topic->last_comment_name;
      $last_post->uid = $topic->last_comment_uid;
    }
Dries's avatar
 
Dries committed
788
    $forum->last_post = $last_post;
Dries's avatar
 
Dries committed
789

Dries's avatar
 
Dries committed
790 791 792