summaryrefslogtreecommitdiff
path: root/modules/forum/forum.module
blob: 9701ec266fd27a8925b2b47073c4bd5fb7dddf85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
211
212
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
<?php
// $Id$

/**
 * @file
 * Enable threaded discussions about general topics.
 */

/**
 * Implementation of hook_help().
 */
function forum_help($path, $arg) {
  switch ($path) {
    case 'admin/help#forum':
      $output = '<p>'. t('The forum module lets you create threaded discussion forums for a particular topic on your site. This is similar to a message board system such as phpBB. Forums are very useful because they allow community members to discuss topics with one another, and they are archived for future reference.') .'</p>';
      $output .= '<p>'. t('Forums can be organized under what are called <em>containers</em>. Containers hold forums and, in turn, forums hold threaded discussions. Both containers and forums can be placed inside other containers and forums. By planning the structure of your containers and forums well, you make it easier for users to find a topic area of interest to them. Forum topics can be moved by selecting a different forum and can be left in the existing forum by selecting <em>leave a shadow copy</em>. Forum topics can also have their own URL.') .'</p>';
      $output .= '<p>'. t('Forums module <strong>requires Taxonomy and Comments module</strong> be enabled.') .'</p>';
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@forum">Forum page</a>.', array('@forum' => 'http://drupal.org/handbook/modules/forum/')) .'</p>';
      return $output;
    case 'admin/content/forum':
      return '<p>'. t('This is a list of existing containers and forums that you can edit. Containers hold forums and, in turn, forums hold threaded discussions. Both containers and forums can be placed inside other containers and forums. By planning the structure of your containers and forums well, you make it easier for users to find a topic area of interest to them.') .'</p>';
    case 'admin/content/forum/add/container':
      return '<p>'. t('Containers help you organize your forums. The job of a container is to hold, or contain, other forums that are related. For example, a container named "Food" might hold two forums named "Fruit" and "Vegetables".') .'</p>';
    case 'admin/content/forum/add/forum':
      return '<p>'. t('A forum holds discussion topics that are related. For example, a forum named "Fruit" might contain topics titled "Apples" and "Bananas".') .'</p>';
    case 'admin/content/forum/settings':
      return '<p>'. t('These settings provide the ability to fine tune the display of your forum topics. Choose the content types to use in the forums by editing the options for the <a href="@forum_vocab">forum vocabulary</a>.', array('@forum_vocab' => url('admin/content/taxonomy/edit/vocabulary/'. variable_get('forum_nav_vocabulary', '')))) .'</p>';
  }
}

/**
 * Implementation of hook_theme()
 */
function forum_theme() {
  return array(
    'forums' => array(
      'template' => 'forums',
      'arguments' => array('forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
    ),
    'forum_list' => array(
      'template' => 'forum-list',
      'arguments' => array('forums' => NULL, 'parents' => NULL, 'tid' => NULL),
    ),
    'forum_topic_list' => array(
      'template' => 'forum-topic-list',
      'arguments' => array('tid' => NULL, 'topics' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
    ),
    'forum_icon' => array(
      'template' => 'forum-icon',
      'arguments' => array('new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0),
    ),
    'forum_topic_navigation' => array(
      'template' => 'forum-topic-navigation',
      'arguments' => array('node' => NULL),
    ),
    'forum_submitted' => array(
      'template' => 'forum-submitted',
      'arguments' => array('topic' => NULL),
    ),
  );
}

/**
 * Implementation of hook_menu().
 */
function forum_menu() {
  $items['node/add/forum'] = array(
    'title' => 'Forum topic',
    'access arguments' => array('create forum topics'),
  );
  $items['forum'] = array(
    'title' => 'Forums',
    'page callback' => 'forum_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'forum.pages.inc',
  );
  $items['admin/content/forum'] = array(
    'title' => 'Forums',
    'description' => 'Control forums and their hierarchy and change forum settings.',
    'page callback' => 'forum_overview',
    'access arguments' => array('administer forums'),
    'file' => 'forum.admin.inc',
  );
  $items['admin/content/forum/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/content/forum/add/container'] = array(
    'title' => 'Add container',
    'page callback' => 'forum_form_main',
    'page arguments' => array('container'),
    'type' => MENU_LOCAL_TASK,
    'parent' => 'admin/content/forum',
    'file' => 'forum.admin.inc',
  );
  $items['admin/content/forum/add/forum'] = array(
    'title' => 'Add forum',
    'page callback' => 'forum_form_main',
    'page arguments' => array('forum'),
    'type' => MENU_LOCAL_TASK,
    'parent' => 'admin/content/forum',
    'file' => 'forum.admin.inc',
  );
  $items['admin/content/forum/settings'] = array(
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('forum_admin_settings'),
    'weight' => 5,
    'type' => MENU_LOCAL_TASK,
    'parent' => 'admin/content/forum',
    'file' => 'forum.admin.inc',
  );
  $items['admin/content/forum/edit/%forum_term'] = array(
    'page callback' => 'forum_form_main',
    'type' => MENU_CALLBACK,
    'file' => 'forum.admin.inc',
  );
  $items['admin/content/forum/edit/container/%forum_term'] = array(
    'title' => 'Edit container',
    'page callback' => 'forum_form_main',
    'page arguments' => array('container', 5),
    'type' => MENU_CALLBACK,
    'file' => 'forum.admin.inc',
  );
  $items['admin/content/forum/edit/forum/%forum_term'] = array(
    'title' => 'Edit forum',
    'page callback' => 'forum_form_main',
    'page arguments' => array('forum', 5),
    'type' => MENU_CALLBACK,
    'file' => 'forum.admin.inc',
  );
  return $items;
}


/**
 * Implementation of hook_init().
 */
function forum_init() {
  drupal_add_css(drupal_get_path('module', 'forum') .'/forum.css');
}

/**
 * Implementation of hook_nodeapi().
 */
function forum_nodeapi(&$node, $op, $teaser, $page) {
  $vid = variable_get('forum_nav_vocabulary', '');
  $vocabulary = taxonomy_vocabulary_load($vid);

  // Operate only on node types assigned for the forum vocabulary.
  if (!in_array($node->type, $vocabulary->nodes)) {
    return;
  }

  switch ($op) {
    case 'view':
      if ($page && $node->taxonomy) {
        // Get the forum terms from the (cached) tree
        $tree = taxonomy_get_tree($vid);
        if ($tree) {
          foreach ($tree as $term) {
            $forum_terms[] = $term->tid;
          }
        }
        foreach ($node->taxonomy as $term_id => $term) {
          if (in_array($term_id, $forum_terms)) {
            $node->tid = $term_id;
          }
        }
        // Breadcrumb navigation
        $breadcrumb = array();
        $breadcrumb[] = array('path' => 'forum', 'title' => $vocabulary->name);
        if ($parents = taxonomy_get_parents_all($node->tid)) {
          $parents = array_reverse($parents);
          foreach ($parents as $p) {
            $breadcrumb[] = array('path' => 'forum/'. $p->tid, 'title' => $p->name);
          }
        }
        $breadcrumb[] = array('path' => 'node/'. $node->nid);
        menu_set_location($breadcrumb);

        $node = node_prepare($node, $teaser);
        if (!$teaser) {
          $node->content['forum_navigation'] = array(
            '#value' => theme('forum_topic_navigation', $node),
            '#weight' => 100,
          );
        }
      }
      return $node;
      break;

    case 'prepare':
      if (empty($node->nid)) {
        // New topic
        $node->taxonomy[arg(3)]->vid = $vid;
        $node->taxonomy[arg(3)]->tid = arg(3);
      }
      return $node;
      break;

    // Check in particular that only a "leaf" term in the associated taxonomy
    // vocabulary is selected, not a "container" term.
    case 'validate':
      if ($node->taxonomy) {
        // Extract the node's proper topic ID.
        $vocabulary = $vid;
        $containers = variable_get('forum_containers', array());
        foreach ($node->taxonomy as $term) {
          if (db_result(db_query('SELECT COUNT(*) FROM {term_data} WHERE tid = %d AND vid = %d', $term, $vocabulary))) {
            if (in_array($term, $containers)) {
              $term = taxonomy_get_term($term);
              form_set_error('taxonomy', t('The item %forum is only a container for forums. Please select one of the forums below it.', array('%forum' => $term->name)));
            }
          }
        }
      }
      break;

    // Assign forum taxonomy when adding a topic from within a forum.
    case 'submit':
      // Make sure all fields are set properly:
      $node->icon = !empty($node->icon) ? $node->icon : '';

      if ($node->taxonomy) {
        // Get the forum terms from the (cached) tree
        $tree = taxonomy_get_tree($vid);
        if ($tree) {
          foreach ($tree as $term) {
            $forum_terms[] = $term->tid;
          }
        }
        foreach ($node->taxonomy as $term_id => $term) {
          if (in_array($term_id, $forum_terms)) {
            $node->tid = $term_id;
          }
        }
        $old_tid = db_result(db_query_range("SELECT t.tid FROM {term_data} t INNER JOIN {node} n WHERE t.vid = n.vid AND n.nid = %d ORDER BY t.vid DESC", $node->nid, 0, 1));
        if ($old_tid) {
          if (($node->tid != $old_tid) && $node->shadow) {
            // A shadow copy needs to be created. Retain new term and add old term.
            $node->taxonomy[] = $old_tid;
          }
        }
      }
      break;
  }

  return;
}

/**
 * Implementation of hook_node_info().
 */
function forum_node_info() {
  return array(
    'forum' => array(
      'name' => t('Forum topic'),
      'module' => 'forum',
      'description' => t('Create a new topic for discussion in the forums.'),
      'title_label' => t('Subject'),
    )
  );
}

/**
 * Implementation of hook_access().
 */
function forum_access($op, $node) {
  global $user;

  if ($op == 'create') {
    return user_access('create forum topics');
  }

  if ($op == 'update' || $op == 'delete') {
    if (user_access('edit own forum topics') && ($user->uid == $node->uid)) {
      return TRUE;
    }
  }
}

/**
 * Implementation of hook_perm().
 */
function forum_perm() {
  return array('create forum topics', 'edit own forum topics', 'administer forums');
}

/**
 * Implementation of hook_taxonomy().
 */
function forum_taxonomy($op, $type, $term = NULL) {
  if ($op == 'delete' && $term['vid'] == variable_get('forum_nav_vocabulary', '')) {
    switch ($type) {
      case 'term':
        $results = db_query('SELECT tn.nid FROM {term_node} tn WHERE tn.tid = %d', $term['tid']);
        while ($node = db_fetch_object($results)) {
          // node_delete will also remove any association with non-forum vocabularies.
          node_delete($node->nid);
        }

        // For containers, remove the tid from the forum_containers variable.
        $containers = variable_get('forum_containers', array());
        $key = array_search($term['tid'], $containers);
        if ($key !== FALSE) {
          unset($containers[$key]);
        }
        variable_set('forum_containers', $containers);
        break;
      case 'vocabulary':
        variable_del('forum_nav_vocabulary');
    }
  }
}

/**
 * Implementation of hook_form_alter().
 */
function forum_form_alter(&$form, $form_state, $form_id) {
  // Hide critical options from forum vocabulary
  if ($form_id == 'taxonomy_form_vocabulary') {
    $vid = variable_get('forum_nav_vocabulary', '');
    if (isset($form['vid']) && $form['vid']['#value'] == $vid) {
      $form['help_forum_vocab'] = array(
        '#value' => t('This is the designated forum vocabulary. Some of the normal vocabulary options have been removed.'),
        '#weight' => -1,
      );
      $form['nodes']['#required'] = TRUE;
      $form['hierarchy'] = array('#type' => 'value', '#value' => 1);
      unset($form['relations']);
      unset($form['tags']);
      unset($form['multiple']);
      $form['required'] = array('#type' => 'value', '#value' => 1);
    }
  }
}

/**
 * Implementation of hook_load().
 */
function forum_load($node) {
  $forum = db_fetch_object(db_query('SELECT * FROM {term_node} WHERE vid = %d', $node->vid));

  return $forum;
}

/**
 * Implementation of hook_block().
 *
 * Generates a block containing the currently active forum topics and the
 * most recently added forum topics.
 */
function forum_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $blocks[0]['info'] = t('Active forum topics');
      $blocks[1]['info'] = t('New forum topics');
      return $blocks;

    case 'configure':
      $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;

    case 'save':
      variable_set('forum_block_num_'. $delta, $edit['forum_block_num_'. $delta]);
      break;

    case 'view':
      if (user_access('access content')) {
        switch ($delta) {
          case 0:
            $title = t('Active forum topics');
            $sql = db_rewrite_sql("SELECT n.nid, n.title, l.comment_count, l.last_comment_timestamp FROM {node} n INNER JOIN {term_node} tn ON tn.nid = n.nid INNER JOIN {term_data} td ON td.tid = tn.tid INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND td.vid = %d ORDER BY l.last_comment_timestamp DESC");
            $result = db_query_range($sql, variable_get('forum_nav_vocabulary', ''), 0, variable_get('forum_block_num_0', '5'));
            $content = node_title_list($result);
            break;

          case 1:
            $title = t('New forum topics');
            $sql = db_rewrite_sql("SELECT n.nid, n.title, l.comment_count FROM {node} n INNER JOIN {term_node} tn ON tn.nid = n.nid INNER JOIN {term_data} td ON td.tid = tn.tid INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND td.vid = %d ORDER BY n.nid DESC");
            $result = db_query_range($sql, variable_get('forum_nav_vocabulary', ''), 0, variable_get('forum_block_num_1', '5'));
            $content = node_title_list($result);
            break;
        }

        if (!empty($content)) {
          $content .= '<div class="more-link">'. l(t('more'), 'forum', array('title' => t('Read the latest forum topics.'))) .'</div>';
          $block['subject'] = $title;
          $block['content'] = $content;
          return $block;
        }
      }
  }
}

/**
 * Implementation of hook_form().
 */
function forum_form(&$node, $form_state) {
  $type = node_get_types('type', $node);
  $form['title'] = array('#type' => 'textfield', '#title' => check_plain($type->title_label), '#default_value' => !empty($node->title) ? $node->title : '', '#required' => TRUE, '#weight' => -5);

  if (!empty($node->nid)) {
    $vid = variable_get('forum_nav_vocabulary', '');
    $forum_terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);
    // if editing, give option to leave shadows
    $shadow = (count($forum_terms) > 1);
    $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.'));
  }

  $form['body_field'] = node_body_field($node, $type->body_label, 1);

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

  return $form;
}

function forum_link_alter(&$links, $node) {
  foreach ($links as $module => $link) {
    if (strstr($module, 'taxonomy_term')) {
      // Link back to the forum and not the taxonomy term page. We'll only
      // do this if the taxonomy term in question belongs to forums.
      $tid = str_replace('taxonomy/term/', '', $link['href']);
      $vid = variable_get('forum_nav_vocabulary', '');
      $term = taxonomy_get_term($tid);
      if ($term->vid == $vid) {
        $links[$module]['href'] = str_replace('taxonomy/term', 'forum', $link['href']);
      }
    }
  }
}

/**
 * Returns a list of all forums for a given taxonomy id
 *
 * Forum objects contain the following fields
 * -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.
 */
function forum_get_forums($tid = 0) {

  $forums = array();
  $vid = variable_get('forum_nav_vocabulary', '');
  $_forums = taxonomy_get_tree($vid, $tid);

  if (count($_forums)) {

    $counts = array();

    $sql = "SELECT r.tid, COUNT(n.nid) AS topic_count, SUM(l.comment_count) AS comment_count FROM {node} n INNER JOIN {node_comment_statistics} l ON n.nid = l.nid INNER JOIN {term_node} r ON n.nid = r.nid WHERE n.status = 1 GROUP BY r.tid";
    $sql = db_rewrite_sql($sql);
    $_counts = db_query($sql);
    while ($count = db_fetch_object($_counts)) {
      $counts[$count->tid] = $count;
    }
  }

  foreach ($_forums as $forum) {
    if (in_array($forum->tid, variable_get('forum_containers', array()))) {
      $forum->container = 1;
    }

    if (!empty($counts[$forum->tid])) {
      $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;
    }

    // This query does not use full ANSI syntax since MySQL 3.x does not support
    // table1 INNER JOIN table2 INNER JOIN table3 ON table2_criteria ON table3_criteria
    // used to join node_comment_statistics to users.
    $sql = "SELECT ncs.last_comment_timestamp, IF (ncs.last_comment_uid != 0, u2.name, ncs.last_comment_name) AS last_comment_name, ncs.last_comment_uid FROM {node} n INNER JOIN {users} u1 ON n.uid = u1.uid INNER JOIN {term_node} tn ON n.nid = tn.nid INNER JOIN {node_comment_statistics} ncs ON n.nid = ncs.nid INNER JOIN {users} u2 ON ncs.last_comment_uid=u2.uid WHERE n.status = 1 AND tn.tid = %d ORDER BY ncs.last_comment_timestamp DESC";
    $sql = db_rewrite_sql($sql);
    $topic = db_fetch_object(db_query_range($sql, $forum->tid, 0, 1));

    $last_post = new stdClass();
    if (!empty($topic->last_comment_timestamp)) {
      $last_post->timestamp = $topic->last_comment_timestamp;
      $last_post->name = $topic->last_comment_name;
      $last_post->uid = $topic->last_comment_uid;
    }
    $forum->last_post = $last_post;

    $forums[$forum->tid] = $forum;
  }

  return $forums;
}

/**
 * Calculate the number of nodes the user has not yet read and are newer
 * than NODE_NEW_LIMIT.
 */
function _forum_topics_unread($term, $uid) {
  $sql = "SELECT COUNT(n.nid) FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid AND tn.tid = %d LEFT JOIN {history} h ON n.nid = h.nid AND h.uid = %d WHERE n.status = 1 AND n.created > %d AND h.nid IS NULL";
  $sql = db_rewrite_sql($sql);
  return db_result(db_query($sql, $term, $uid, NODE_NEW_LIMIT));
}

function forum_get_topics($tid, $sortby, $forum_per_page) {
  global $user, $forum_topic_list_header;

  $forum_topic_list_header = array(
    array('data' => '&nbsp;', 'field' => NULL),
    array('data' => t('Topic'), 'field' => 'n.title'),
    array('data' => t('Replies'), 'field' => 'l.comment_count'),
    array('data' => t('Created'), 'field' => 'n.created'),
    array('data' => t('Last reply'), 'field' => 'l.last_comment_timestamp'),
  );

  $order = _forum_get_topic_order($sortby);
  for ($i = 0; $i < count($forum_topic_list_header); $i++) {
    if ($forum_topic_list_header[$i]['field'] == $order['field']) {
      $forum_topic_list_header[$i]['sort'] = $order['sort'];
    }
  }

  $term = taxonomy_get_term($tid);

  $sql = db_rewrite_sql("SELECT n.nid, r.tid, n.title, n.sticky, u.name, u.uid, n.created AS timestamp, n.comment AS comment_mode, l.last_comment_timestamp, IF(l.last_comment_uid != 0, cu.name, l.last_comment_name) AS last_comment_name, l.last_comment_uid, l.comment_count AS num_comments FROM {node_comment_statistics} l, {users} cu, {term_node} r, {users} u, {node} n WHERE n.status = 1 AND l.last_comment_uid = cu.uid AND n.nid = l.nid AND n.nid = r.nid AND r.tid = %d AND n.uid = u.uid AND n.vid = r.vid");
  $sql .= tablesort_sql($forum_topic_list_header, 'n.sticky DESC,');
  $sql .= ', n.created DESC';  // Always add a secondary sort order so that the news forum topics are on top.

  $sql_count = db_rewrite_sql("SELECT COUNT(n.nid) FROM {node} n INNER JOIN {term_node} r ON n.nid = r.nid AND r.tid = %d WHERE n.status = 1");

  $result = pager_query($sql, $forum_per_page, 0, $sql_count, $tid);
  $topics = array();
  while ($topic = db_fetch_object($result)) {
    if ($user->uid) {
      // folder is new if topic is new or there are new comments since last visit
      if ($topic->tid != $tid) {
        $topic->new = 0;
      }
      else {
        $history = _forum_user_last_visit($topic->nid);
        $topic->new_replies = comment_num_new($topic->nid, $history);
        $topic->new = $topic->new_replies || ($topic->timestamp > $history);
      }
    }
    else {
      // Do not track "new replies" status for topics if the user is anonymous.
      $topic->new_replies = 0;
      $topic->new = 0;
    }

    if ($topic->num_comments > 0) {
      $last_reply = new stdClass();
      $last_reply->timestamp = $topic->last_comment_timestamp;
      $last_reply->name = $topic->last_comment_name;
      $last_reply->uid = $topic->last_comment_uid;
      $topic->last_reply = $last_reply;
    }
    $topics[] = $topic;
  }

  return $topics;
}

/**
 * Finds the first unread node for a given forum.
 */
function _forum_new($tid) {
  global $user;

  $sql = "SELECT n.nid FROM {node} n LEFT JOIN {history} h ON n.nid = h.nid AND h.uid = %d INNER JOIN {term_node} r ON n.nid = r.nid AND r.tid = %d WHERE n.status = 1 AND h.nid IS NULL AND n.created > %d ORDER BY created";
  $sql = db_rewrite_sql($sql);
  $nid = db_result(db_query_range($sql, $user->uid, $tid, NODE_NEW_LIMIT, 0, 1));

  return $nid ? $nid : 0;
}

/**
 * Process variables for forums.tpl.php
 *
 * The $variables array contains the following arguments:
 * - $forums
 * - $topics
 * - $parents
 * - $tid
 * - $sortby
 * - $forum_per_page
 *
 * @see forums.tpl.php
 */
function template_preprocess_forums(&$variables) {
  global $user;

  $vid = variable_get('forum_nav_vocabulary', '');
  $vocabulary = taxonomy_vocabulary_load($vid);
  $title = !empty($vocabulary->name) ? $vocabulary->name : '';

  // Breadcrumb navigation:
  $breadcrumb = array();
  if ($variables['tid']) {
    $breadcrumb[] = array('path' => 'forum', 'title' => $title);
  }

  if ($variables['parents']) {
    $variables['parents'] = array_reverse($variables['parents']);
    foreach ($variables['parents'] as $p) {
      if ($p->tid == $variables['tid']) {
        $title = $p->name;
      }
      else {
        $breadcrumb[] = array('path' => 'forum/'. $p->tid, 'title' => $p->name);
      }
    }
  }

  drupal_set_title(check_plain($title));

  $breadcrumb[] = array('path' => $_GET['q']);
  menu_set_location($breadcrumb);

  if ($variables['forums_defined'] = count($variables['forums']) || count($variables['parents'])) {
    // Format the "post new content" links listing.
    $forum_types = array();

    // Loop through all node types for forum vocabulary.
    foreach ($vocabulary->nodes as $type) {
      // Check if the current user has the 'create' permission for this node type.
      if (node_access('create', $type)) {
        // Fetch the "General" name of the content type;
        // Push the link with title and url to the array.
        $forum_types[$type] = array('title' => t('Post new @node_type', array('@node_type' => node_get_types('name', $type))), 'href' => "node/add/$type/$variables[tid]");
      }
    }

    if (empty($forum_types)) {
      // The user is logged-in; but denied access to create any new forum content type.
      if ($user->uid) {
        $forum_types['disallowed'] = array('title' => t('You are not allowed to post new content in forum.'));
      }
      // The user is not logged-in; and denied access to create any new forum content type.
      else {
        $forum_types['login'] = array('title' => t('<a href="@login">Login</a> to post new content in forum.', array('@login' => url('user/login', array('query' => drupal_get_destination())))), 'html' => TRUE);
      }
    }
    $variables['links'] = $forum_types;

    if (!empty($variables['forums'])) {
      $variables['forums'] = theme('forum_list', $variables['forums'], $variables['parents'], $variables['tid']);
    }
    else {
      $variables['forums'] = '';
    }

    if ($variables['tid'] && !in_array($variables['tid'], variable_get('forum_containers', array()))) {
      $variables['topics'] = theme('forum_topic_list', $variables['tid'], $variables['topics'], $variables['sortby'], $variables['forum_per_page']);
      drupal_add_feed(url('taxonomy/term/'. $variables['tid'] .'/0/feed'), 'RSS - '. $title);
    }
    else {
      $variables['topics'] = '';
    }

    // Provide separate template suggestions based on what's being output. Topic id is also accounted for.
    // Check both variables to be safe then the inverse. Forums with topic ID's take precedence.
    if ($variables['forums'] && !$variables['topics']) {
      $variables['template_files'][] = 'forums-containers';
      $variables['template_files'][] = 'forums-'. $variables['tid'];
      $variables['template_files'][] = 'forums-containers-'. $variables['tid'];
    }
    elseif (!$variables['forums'] && $variables['topics']) {
      $variables['template_files'][] = 'forums-topics';
      $variables['template_files'][] = 'forums-'. $variables['tid'];
      $variables['template_files'][] = 'forums-topics-'. $variables['tid'];
    }
    else {
      $variables['template_files'][] = 'forums-'. $variables['tid'];
    }

  }
  else {
    drupal_set_title(t('No forums defined'));
    $variables['links'] = array();
    $variables['forums'] = '';
    $variables['topics'] = '';
  }
}

/**
 * Process variables to format a forum listing.
 *
 * $variables contains the following information:
 * - $forums
 * - $parents
 * - $tid
 *
 * @see forum-list.tpl.php
 * @see theme_forum_list()
 */
function template_preprocess_forum_list(&$variables) {
  global $user;
  $row = 0;
  // Sanitize each forum so that the template can safely print the data.
  foreach ($variables['forums'] as $id => $forum) {
    $variables['forums'][$id]->description = !empty($forum->description) ? filter_xss_admin($forum->description) : '';
    $variables['forums'][$id]->link = url("forum/$forum->tid");
    $variables['forums'][$id]->name = check_plain($forum->name);
    $variables['forums'][$id]->is_container = !empty($forum->container);
    $variables['forums'][$id]->zebra = $row % 2 == 0 ? 'odd' : 'even';
    $row++;

    $variables['forums'][$id]->new_text = '';
    $variables['forums'][$id]->new_url = '';
    $variables['forums'][$id]->new_topics = 0;
    $variables['forums'][$id]->old_topics = $forum->num_topics;
    if ($user->uid) {
      $variables['forums'][$id]->new_topics = _forum_topics_unread($forum->tid, $user->uid);
      if ($variables['forums'][$id]->new_topics) {
        $variables['forums'][$id]->new_text = t('!count new', array('!count' => $variables['forums'][$id]->new_topics));
        $variables['forums'][$id]->new_url = url("forum/$forum->tid", array('fragment' => 'new'));
      }
      $variables['forums'][$id]->old_topics = $forum->num_topics - $variables['forums'][$id]->new_topics;
    }
    $variables['forums'][$id]->last_reply = theme('forum_submitted', $forum->last_post);
  }
}

/**
 * Preprocess variables to format the topic listing.
 *
 * $variables contains the following data:
 * - $tid
 * - $topics
 * - $sortby
 * - $forum_per_page
 *
 * @see forum-topic-list.tpl.php
 * @see theme_forum_topic_list()
 */
function template_preprocess_forum_topic_list(&$variables) {
  global $forum_topic_list_header;

  // Create the tablesorting header.
  $ts = tablesort_init($forum_topic_list_header);
  $header = '';
  foreach ($forum_topic_list_header as $cell) {
    $cell = tablesort_header($cell, $forum_topic_list_header, $ts);
    $header .= _theme_table_cell($cell, TRUE);
  }
  $variables['header'] = $header;

  if (!empty($variables['topics'])) {
    $row = 0;
    foreach ($variables['topics'] as $id => $topic) {
      $variables['topics'][$id]->icon = theme('forum_icon', $topic->new, $topic->num_comments, $topic->comment_mode, $topic->sticky);
      $variables['topics'][$id]->zebra = $row % 2 == 0 ? 'odd' : 'even';
      $row++;

      $variables['topics'][$id]->title = l($topic->title, "node/$topic->nid");
      $variables['topics'][$id]->created = theme('forum_submitted', $topic);
      $variables['topics'][$id]->last_reply = theme('forum_submitted', isset($topic->last_reply) ? $topic->last_reply : NULL);

      $variables['topics'][$id]->new_text = '';
      $variables['topics'][$id]->new_url = '';
      if ($topic->new_replies) {
        $variables['topics'][$id]->new_text = t('!count new', array('!count' => $variables['forums'][$id]->new_topics));
        $variables['topics'][$id]->new_url = url("node/$topic->nid", array('fragment' => 'new'));
      }

      $variables['topics'][$id]->moved = FALSE;
      $variables['topics'][$id]->message = '';
      if ($topic->tid != $variables['tid']) {
        $variables['topics'][$id]->moved = TRUE;
        $variables['topics'][$id]->title = check_plain($topic->title);
        $variables['topics'][$id]->message = l(t('This topic has been moved'), "forum/$topic->tid");
      }
    }
  }
  else {
    // Make this safe for the template
    $variables['topics'] = array();
  }

  $variables['pager'] = theme('pager', NULL, $variables['forum_per_page'], 0);
}

/**
 * Process variables to format the icon for each individual topic.
 *
 * $variables contains the following data:
 * - $new_posts
 * - $num_posts = 0
 * - $comment_mode = 0
 * - $sticky = 0
 *
 * @see forum-icon.tpl.php
 * @see theme_forum_icon()
 */
function template_preprocess_forum_icon(&$variables) {
  $variables['hot_threshold'] = variable_get('forum_hot_topic', 15);
  if ($variables['num_posts'] > $variables['hot_threshold']) {
    $variables['icon'] = $variables['new_posts'] ? 'hot-new' : 'hot';
  }
  else {
    $variables['icon'] = $variables['new_posts'] ? 'new' : 'default';
  }

  if ($variables['comment_mode'] == COMMENT_NODE_READ_ONLY || $variables['comment_mode'] == COMMENT_NODE_DISABLED) {
    $variables['icon'] = 'closed';
  }

  if ($variables['sticky'] == 1) {
    $variables['icon'] = 'sticky';
  }
}

/**
 * Preprocess variables to format the next/previous forum topic navigation links.
 *
 * $variables contains $node.
 *
 * @see forum-topic-navigation.tpl.php
 * @see theme_forum_topic_navigation
 */
function template_preprocess_forum_topic_navigation(&$variables) {
  $output = '';

  // get previous and next topic
  $sql = "SELECT n.nid, n.title, n.sticky, l.comment_count, l.last_comment_timestamp FROM {node} n INNER JOIN {node_comment_statistics} l ON n.nid = l.nid INNER JOIN {term_node} r ON n.nid = r.nid AND r.tid = %d WHERE n.status = 1 ORDER BY n.sticky DESC, ". _forum_get_topic_order_sql(variable_get('forum_order', 1));
  $result = db_query(db_rewrite_sql($sql), isset($variables['node']->tid) ? $variables['node']->tid : 0);

  $stop = $variables['prev'] = $variables['next'] = 0;

  while ($topic = db_fetch_object($result)) {
    if ($stop == 1) {
      $variables['next'] = $topic->nid;
      $variables['next_title'] = check_plain($topic->title);
      $variables['next_url'] = url("node/$topic->nid");
      break;
    }
    if ($topic->nid == $variables['node']->nid) {
      $stop = 1;
    }
    else {
      $variables['prev'] = $topic->nid;
      $variables['prev_title'] = check_plain($topic->title);
      $variables['prev_url'] = url("node/$topic->nid");
    }
  }
}

/**
 * Process variables to format submission info for display in the forum list and topic list.
 *
 * $variables will contain: $topic
 *
 * @see forum-submitted.tpl.php
 * @see theme_forum_submitted
 */
function template_preprocess_forum_submitted(&$variables) {
  $variables['author'] = isset($variables['topic']->uid) ? theme('username', $variables['topic']) : '';
  $variables['time'] = isset($variables['topic']->timestamp) ? format_interval(time() - $variables['topic']->timestamp) : '';
}

function _forum_user_last_visit($nid) {
  global $user;
  static $history = array();

  if (empty($history)) {
    $result = db_query('SELECT nid, timestamp FROM {history} WHERE uid = %d', $user->uid);
    while ($t = db_fetch_object($result)) {
      $history[$t->nid] = $t->timestamp > NODE_NEW_LIMIT ? $t->timestamp : NODE_NEW_LIMIT;
    }
  }
  return isset($history[$nid]) ? $history[$nid] : NODE_NEW_LIMIT;
}

function _forum_get_topic_order($sortby) {
  switch ($sortby) {
    case 1:
      return array('field' => 'l.last_comment_timestamp', 'sort' => 'desc');
      break;
    case 2:
      return array('field' => 'l.last_comment_timestamp', 'sort' => 'asc');
      break;
    case 3:
      return array('field' => 'l.comment_count', 'sort' => 'desc');
      break;
    case 4:
      return array('field' => 'l.comment_count', 'sort' => 'asc');
      break;
  }
}

function _forum_get_topic_order_sql($sortby) {
  $order = _forum_get_topic_order($sortby);
  return $order['field'] .' '. $order['sort'];
}