summaryrefslogtreecommitdiffstats
path: root/core/modules/forum/forum.module
blob: dfe04f219deb5358972b5674531fb632714aa116 (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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
<?php

/**
 * @file
 * Provides discussion forums.
 */

use Drupal\Core\Entity\EntityInterface;
use Drupal\entity\Plugin\Core\Entity\EntityDisplay;
use Drupal\taxonomy\Plugin\Core\Entity\Term;

/**
 * Implements hook_help().
 */
function forum_help($path, $arg) {
  switch ($path) {
    case 'admin/help#forum':
      $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/documentation/modules/forum')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $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>';
      $output .= '<dt>' . t('Forum navigation') . '</dt>';
      $output .= '<dd>' . t('Enabling the Forum module provides a default <em>Forums</em> menu item in the Tools menu that links to the <a href="@forums">Forums page</a>.', array('@forums' => url('forum'))) . '</dd>';
      $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>';
      $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>';
      $output .= '</dl>';
      return $output;
    case 'admin/structure/forum':
      $output = '<p>' . t('Forums contain forum topics. Use containers to group related forums.') . '</p>';
      $output .= theme('more_help_link', array('url' => 'admin/help/forum'));
      return $output;
    case 'admin/structure/forum/add/container':
      return '<p>' . t('Use containers to group related forums.') . '</p>';
    case 'admin/structure/forum/add/forum':
      return '<p>' . t('A forum holds related forum topics.') . '</p>';
    case 'admin/structure/forum/settings':
      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>';
  }
}

/**
 * Implements hook_theme().
 */
function forum_theme() {
  return array(
    'forums' => array(
      'template' => 'forums',
      'variables' => array('forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
    ),
    'forum_list' => array(
      'template' => 'forum-list',
      'variables' => array('forums' => NULL, 'parents' => NULL, 'tid' => NULL),
    ),
    'forum_topic_list' => array(
      'template' => 'forum-topic-list',
      'variables' => array('tid' => NULL, 'topics' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),
    ),
    'forum_icon' => array(
      'template' => 'forum-icon',
      'variables' => array('new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0, 'first_new' => FALSE),
    ),
    'forum_submitted' => array(
      'template' => 'forum-submitted',
      'variables' => array('topic' => NULL),
    ),
    'forum_form' => array(
      'render element' => 'form',
      'file' => 'forum.admin.inc',
    ),
  );
}

/**
 * Implements hook_menu().
 */
function forum_menu() {
  $items['forum'] = array(
    'title' => 'Forums',
    'page callback' => 'forum_page',
    'access arguments' => array('access content'),
    'file' => 'forum.pages.inc',
  );
  $items['forum/%forum_forum'] = array(
    'title' => 'Forums',
    'title callback' => 'entity_page_label',
    'title arguments' => array(1),
    'page callback' => 'forum_page',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'file' => 'forum.pages.inc',
  );
  $items['admin/structure/forum'] = array(
    'title' => 'Forums',
    'description' => 'Control forum hierarchy settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('forum_overview'),
    'access arguments' => array('administer forums'),
    'file' => 'forum.admin.inc',
  );
  $items['admin/structure/forum/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/structure/forum/add/container'] = array(
    'title' => 'Add container',
    'page callback' => 'forum_form_main',
    'page arguments' => array('container'),
    'access arguments' => array('administer forums'),
    'type' => MENU_LOCAL_ACTION,
    'parent' => 'admin/structure/forum',
    'file' => 'forum.admin.inc',
  );
  $items['admin/structure/forum/add/forum'] = array(
    'title' => 'Add forum',
    'page callback' => 'forum_form_main',
    'page arguments' => array('forum'),
    'access arguments' => array('administer forums'),
    'type' => MENU_LOCAL_ACTION,
    'parent' => 'admin/structure/forum',
    'file' => 'forum.admin.inc',
  );
  $items['admin/structure/forum/settings'] = array(
    'title' => 'Settings',
    'weight' => 100,
    'type' => MENU_LOCAL_TASK,
    'parent' => 'admin/structure/forum',
    'route_name' => 'forum_settings',
  );
  $items['admin/structure/forum/edit/container/%taxonomy_term'] = array(
    'title' => 'Edit container',
    'page callback' => 'forum_form_main',
    'page arguments' => array('container', 5),
    'access arguments' => array('administer forums'),
    'file' => 'forum.admin.inc',
  );
  $items['admin/structure/forum/edit/forum/%taxonomy_term'] = array(
    'title' => 'Edit forum',
    'page callback' => 'forum_form_main',
    'page arguments' => array('forum', 5),
    'access arguments' => array('administer forums'),
    'file' => 'forum.admin.inc',
  );
  return $items;
}

/**
 * Implements hook_menu_local_tasks().
 */
function forum_menu_local_tasks(&$data, $router_item, $root_path) {
  global $user;

  // Add action link to 'node/add/forum' on 'forum' sub-pages.
  if ($root_path == 'forum' || $root_path == 'forum/%') {
    $tid = (isset($router_item['page_arguments'][0]) ? $router_item['page_arguments'][0]->id() : 0);
    $forum_term = forum_forum_load($tid);
    if ($forum_term) {
      $links = array();
      // Loop through all bundles for forum taxonomy vocabulary field.
      $field = field_info_field('taxonomy_forums');
      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_label($type))),
              'href' => 'node/add/' . $type . '/' . $forum_term->id(),
            ),
          );
        }
      }
      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">Log in</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'] += $links;
    }
  }
}

/**
 * Implements hook_menu_local_tasks_alter().
 *
 * Remove the 'Add Forum' and 'Add container' local tasks on the delete form.
 */
function forum_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($root_path == 'admin/structure/forum' && !empty($router_item['map'][3]) &&
      $router_item['map'][3] == 'delete') {
    $data = array();
  }
}

/**
 * Implements hook_entity_bundle_info_alter().
 */
function forum_entity_bundle_info_alter(&$bundles) {
  // Take over URI construction for taxonomy terms that are forums.
  if ($vid = config('forum.settings')->get('vocabulary')) {
    if (isset($bundles['taxonomy_term'][$vid])) {
      $bundles['taxonomy_term'][$vid]['uri_callback'] = 'forum_uri';
    }
  }
}

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

/**
 * Checks whether a node can be used in a forum, based on its content type.
 *
 * @param \Drupal\Core\Entity\EntityInterface $node
 *   A node entity.
 *
 * @return
 *   Boolean indicating if the node can be assigned to a forum.
 */
function _forum_node_check_node_type(EntityInterface $node) {
  // Fetch information about the forum field.
  $instance = field_info_instance('node', 'taxonomy_forums', $node->type);
  return !empty($instance);
}

/**
 * Implements hook_node_view().
 */
function forum_node_view(EntityInterface $node, EntityDisplay $display, $view_mode) {
  $vid = config('forum.settings')->get('vocabulary');
  $vocabulary = taxonomy_vocabulary_load($vid);
  if (_forum_node_check_node_type($node)) {
    if ($view_mode == 'full' && node_is_page($node)) {
      // Breadcrumb navigation
      $breadcrumb[] = l(t('Home'), NULL);
      $breadcrumb[] = l($vocabulary->name, 'forum');
      if ($parents = taxonomy_term_load_parents_all($node->forum_tid)) {
        $parents = array_reverse($parents);
        foreach ($parents as $parent) {
          $breadcrumb[] = l($parent->label(), 'forum/' . $parent->id());
        }
      }
      drupal_set_breadcrumb($breadcrumb);

    }
  }
}

/**
 * Implements hook_node_validate().
 *
 * Checks in particular that the node is assigned only a "leaf" term in the
 * forum taxonomy.
 */
function forum_node_validate(EntityInterface $node, $form) {
  if (_forum_node_check_node_type($node)) {
    $langcode = $form['taxonomy_forums']['#language'];
    // vocabulary is selected, not a "container" term.
    if (!empty($node->taxonomy_forums[$langcode])) {
      // Extract the node's proper topic ID.
      $containers = config('forum.settings')->get('containers');
      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;
        }
        $term = taxonomy_term_load($item['tid']);
        if (!$term) {
          form_set_error('taxonomy_forums', t('Select a forum.'));
          continue;
        }
        $used = db_query_range('SELECT 1 FROM {taxonomy_term_data} WHERE tid = :tid AND vid = :vid', 0, 1, array(
          ':tid' => $term->id(),
          ':vid' => $term->bundle(),
        ))->fetchField();
        if ($used && in_array($term->id(), $containers)) {
          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->label())));
        }
      }
    }
  }
}

/**
 * Implements hook_node_presave().
 *
 * Assigns the forum taxonomy when adding a topic from within a forum.
 */
function forum_node_presave(EntityInterface $node) {
  if (_forum_node_check_node_type($node)) {
    // Make sure all fields are set properly:
    $node->icon = !empty($node->icon) ? $node->icon : '';
    reset($node->taxonomy_forums);
    $langcode = key($node->taxonomy_forums);
    if (!empty($node->taxonomy_forums[$langcode])) {
      $node->forum_tid = $node->taxonomy_forums[$langcode][0]['tid'];
      // Only do a shadow copy check if this is not a new node.
      if (!$node->isNew()) {
        $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();
        if ($old_tid && isset($node->forum_tid) && ($node->forum_tid != $old_tid) && !empty($node->shadow)) {
          // A shadow copy needs to be created. Retain new term and add old term.
          $node->taxonomy_forums[$langcode][] = array('tid' => $old_tid);
        }
      }
    }
  }
}

/**
 * Implements hook_node_update().
 */
function forum_node_update(EntityInterface $node) {
  if (_forum_node_check_node_type($node)) {
    // If this is not a new revision and does exist, update the forum record,
    // otherwise insert a new one.
    if ($node->getRevisionId() == $node->original->getRevisionId() && db_query('SELECT tid FROM {forum} WHERE nid=:nid', array(':nid' => $node->nid))->fetchField()) {
      if (!empty($node->forum_tid)) {
        db_update('forum')
          ->fields(array('tid' => $node->forum_tid))
          ->condition('vid', $node->vid)
          ->execute();
      }
      // The node is removed from the forum.
      else {
        db_delete('forum')
          ->condition('nid', $node->nid)
          ->execute();
      }
    }
    else {
      if (!empty($node->forum_tid)) {
        db_insert('forum')
          ->fields(array(
            'tid' => $node->forum_tid,
            'vid' => $node->vid,
            'nid' => $node->nid,
          ))
          ->execute();
      }
    }
    // If the node has a shadow forum topic, update the record for this
    // revision.
    if (!empty($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();
     }
  }
}

/**
 * Implements hook_node_insert().
 */
function forum_node_insert(EntityInterface $node) {
  if (_forum_node_check_node_type($node)) {
    if (!empty($node->forum_tid)) {
      $nid = db_insert('forum')
        ->fields(array(
          'tid' => $node->forum_tid,
          'vid' => $node->vid,
          'nid' => $node->nid,
        ))
        ->execute();
    }
  }
}

/**
 * Implements hook_node_predelete().
 */
function forum_node_predelete(EntityInterface $node) {
  if (_forum_node_check_node_type($node)) {
    db_delete('forum')
      ->condition('nid', $node->nid)
      ->execute();
    db_delete('forum_index')
      ->condition('nid', $node->nid)
      ->execute();
  }
}

/**
 * Implements hook_node_load().
 */
function forum_node_load($nodes) {
  $node_vids = array();
  foreach ($nodes as $node) {
    if (_forum_node_check_node_type($node)) {
      $node_vids[] = $node->vid;
    }
  }
  if (!empty($node_vids)) {
    $query = db_select('forum', 'f');
    $query
      ->fields('f', array('nid', 'tid'))
      ->condition('f.vid', $node_vids);
    $result = $query->execute();
    foreach ($result as $record) {
      $nodes[$record->nid]->forum_tid = $record->tid;
    }
  }
}

/**
 * Implements hook_node_info().
 */
function forum_node_info() {
  return array(
    'forum' => array(
      'name' => t('Forum topic'),
      'base' => 'forum',
      'description' => t('A <em>forum topic</em> starts a new discussion thread within a forum.'),
      'title_label' => t('Subject'),
    )
  );
}

/**
 * Implements hook_permission().
 */
function forum_permission() {
  $perms = array(
    'administer forums' => array(
      'title' => t('Administer forums'),
    ),
  );
  return $perms;
}

/**
 * Implements hook_taxonomy_term_delete().
 */
function forum_taxonomy_term_delete(Term $term) {
  // For containers, remove the tid from the forum_containers variable.
  $config = config('forum.settings');
  $containers = $config->get('containers');
  $key = array_search($term->id(), $containers);
  if ($key !== FALSE) {
    unset($containers[$key]);
  }
  $config->set('containers', $containers)->save();
}

/**
 * Implements hook_comment_publish().
 *
 * This actually handles the insertion 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->target_id);
}

/**
 * Implements hook_comment_update().
 *
 * The 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 need to handle all other values here.
  if (!$comment->status->value) {
    _forum_update_forum_index($comment->nid->target_id);
  }
}

/**
 * Implements hook_comment_unpublish().
 */
function forum_comment_unpublish($comment) {
  _forum_update_forum_index($comment->nid->target_id);
}

/**
 * Implements hook_comment_delete().
 */
function forum_comment_delete($comment) {
  _forum_update_forum_index($comment->nid->target_id);
}

/**
 * Implements hook_field_storage_pre_insert().
 */
function forum_field_storage_pre_insert(EntityInterface $entity, &$skip_fields) {
  if ($entity->entityType() == 'node' && $entity->status && _forum_node_check_node_type($entity)) {
    $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
    foreach ($entity->getTranslationLanguages() as $langcode => $language) {
      $translation = $entity->getTranslation($langcode, FALSE);
      $query->values(array(
        'nid' => $entity->id(),
        'title' => $translation->title->value,
        'tid' => $translation->taxonomy_forums->tid,
        'sticky' => $entity->sticky,
        'created' => $entity->created,
        'comment_count' => 0,
        'last_comment_timestamp' => $entity->created,
      ));
    }
    $query->execute();
  }
}

/**
 * Implements hook_field_storage_pre_update().
 */
function forum_field_storage_pre_update(EntityInterface $entity, &$skip_fields) {
  $first_call = &drupal_static(__FUNCTION__, array());

  if ($entity->entityType() == 'node' && _forum_node_check_node_type($entity)) {

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

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

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

  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function forum_form_taxonomy_vocabulary_form_alter(&$form, &$form_state, $form_id) {
  $vid = config('forum.settings')->get('vocabulary');
  $vocabulary = $form_state['controller']->getEntity();
  if ($vid == $vocabulary->id()) {
    $form['help_forum_vocab'] = array(
      '#markup' => t('This is the designated forum vocabulary. Some of the normal vocabulary options have been removed.'),
      '#weight' => -1,
    );
    // Forum's vocabulary always has single hierarchy. Forums and containers
    // have only one parent or no parent for root items. By default this value
    // is 0.
    $form['hierarchy']['#value'] = TAXONOMY_HIERARCHY_SINGLE;
    // Do not allow to delete forum's vocabulary.
    $form['actions']['delete']['#access'] = FALSE;
    // Do not allow to change a vid of forum's vocabulary.
    $form['vid']['#disabled'] = TRUE;
  }
}

/**
 * Implements hook_form_FORM_ID_alter() for taxonomy_term_form().
 */
function forum_form_taxonomy_term_form_alter(&$form, &$form_state, $form_id) {
  $vid = config('forum.settings')->get('vocabulary');
  if (isset($form['vid']['#value']) && $form['vid']['#value'] == $vid) {
    // Hide multiple parents select from forum terms.
    $form['relations']['parent']['#access'] = FALSE;
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
 */
function forum_form_node_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['taxonomy_forums'])) {
    $langcode = $form['taxonomy_forums']['#language'];
    // Make the vocabulary required for 'real' forum-nodes.
    $form['taxonomy_forums'][$langcode]['#required'] = TRUE;
    $form['taxonomy_forums'][$langcode]['#multiple'] = FALSE;
    if (empty($form['taxonomy_forums'][$langcode]['#default_value'])) {
      // If there is no default forum already selected, try to get the forum
      // 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).
      $requested_forum_id = arg(3);
      $form['taxonomy_forums'][$langcode]['#default_value'] = is_numeric($requested_forum_id) ? $requested_forum_id : '';
    }
  }
}

/**
 * Render API callback: Lists nodes based on the element's #query property.
 *
 * This function can be used as a #pre_render callback.
 *
 * @see \Drupal\forum\Plugin\block\block\NewTopicsBlock::blockBuild()
 * @see \Drupal\forum\Plugin\block\block\ActiveTopicsBlock::blockBuild()
 */
function forum_block_view_pre_render($elements) {
  $result = $elements['#query']->execute();
  if ($node_title_list = node_title_list($result)) {
    $elements['forum_list'] = $node_title_list;
    $elements['forum_more'] = array('#theme' => 'more_link', '#url' => 'forum', '#title' => t('Read the latest forum topics.'));
  }
  return $elements;
}

/**
 * Implements hook_form().
 */
function forum_form(EntityInterface $node, &$form_state) {
  $type = node_type_load($node->type);
  $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)) {
    $forum_terms = $node->taxonomy_forums;
    // 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['forum_tid'] = array('#type' => 'value', '#value' => $node->forum_tid);
  }

  return $form;
}

/**
 * Returns a tree of all forums for a given taxonomy term ID.
 *
 * @param $tid
 *   (optional) Taxonomy term ID of the forum. If not given all forums will be
 *   returned.
 *
 * @return
 *   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.
 */
function forum_forum_load($tid = NULL) {
  $cache = &drupal_static(__FUNCTION__, array());

  // Return a cached forum tree if available.
  if (!isset($tid)) {
    $tid = 0;
  }
  if (isset($cache[$tid])) {
    return $cache[$tid];
  }

  $config = config('forum.settings');
  $vid = $config->get('vocabulary');

  // Load and validate the parent term.
  if ($tid) {
    $forum_term = taxonomy_term_load($tid);
    if (!$forum_term || ($forum_term->bundle() != $vid)) {
      return $cache[$tid] = FALSE;
    }
  }
  // If $tid is 0, create an empty entity to hold the child terms.
  elseif ($tid === 0) {
    $forum_term = entity_create('taxonomy_term', array(
      'tid' => 0,
      'vid' => $vid,
    ));
  }

  // Determine if the requested term is a container.
  if (!$forum_term->id() || in_array($forum_term->id(), $config->get('containers'))) {
    $forum_term->container = 1;
  }

  // Load parent terms.
  $forum_term->parents = taxonomy_term_load_parents_all($forum_term->id());

  // Load the tree below.
  $forums = array();
  $_forums = taxonomy_get_tree($vid, $tid, NULL, TRUE);

  if (count($_forums)) {
    $query = db_select('node', 'n');
    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
    $query->join('forum', 'f', 'n.vid = f.vid');
    $query->addExpression('COUNT(n.nid)', 'topic_count');
    $query->addExpression('SUM(ncs.comment_count)', 'comment_count');
    $counts = $query
      ->fields('f', array('tid'))
      ->condition('n.status', 1)
      ->groupBy('tid')
      ->addTag('node_access')
      ->execute()
      ->fetchAllAssoc('tid');
  }

  foreach ($_forums as $forum) {
    // Determine if the child term is a container.
    if (in_array($forum->id(), $config->get('containers'))) {
      $forum->container = 1;
    }

    // Merge in the topic and post counters.
    if (!empty($counts[$forum->id()])) {
      $forum->num_topics = $counts[$forum->id()]->topic_count;
      $forum->num_posts = $counts[$forum->id()]->topic_count + $counts[$forum->id()]->comment_count;
    }
    else {
      $forum->num_topics = 0;
      $forum->num_posts = 0;
    }

    // Query "Last Post" information for this forum.
    $query = db_select('node', 'n');
    $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $forum->id()));
    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
    $query->join('users', 'u', 'ncs.last_comment_uid = u.uid');
    $query->addExpression('CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u.name END', 'last_comment_name');

    $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();

    // Merge in the "Last Post" information.
    $last_post = new stdClass();
    if (!empty($topic->last_comment_timestamp)) {
      $last_post->created = $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->id()] = $forum;
  }

  // Cache the result, and return the tree.
  $forum_term->forums = $forums;
  $cache[$tid] = $forum_term;
  return $forum_term;
}

/**
 * Calculates the number of new posts in a forum that the user has not yet read.
 *
 * Nodes are new if they are newer than HISTORY_READ_LIMIT.
 *
 * @param $term
 *   The term ID of the forum.
 * @param $uid
 *   The user ID.
 *
 * @return
 *   The number of new posts in the forum that have not been read by the user.
 */
function _forum_topics_unread($term, $uid) {
  $query = db_select('node', 'n');
  $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $term));
  $query->leftJoin('history', 'h', 'n.nid = h.nid AND h.uid = :uid', array(':uid' => $uid));
  $query->addExpression('COUNT(n.nid)', 'count');
  return $query
    ->condition('status', 1)
    ->condition('n.created', HISTORY_READ_LIMIT, '>')
    ->isNull('h.nid')
    ->addTag('node_access')
    ->execute()
    ->fetchField();
}

/**
 * Gets all the topics in a forum.
 *
 * @param $tid
 *   The term ID of the forum.
 * @param $sortby
 *   One of the following integers indicating the sort criteria:
 *   - 1: Date - newest first.
 *   - 2: Date - oldest first.
 *   - 3: Posts with the most comments first.
 *   - 4: Posts with the least comments first.
 * @param $forum_per_page
 *   The maximum number of topics to display per page.
 *
 * @return
 *   A list of all the topics in a forum.
 */
function forum_get_topics($tid, $sortby, $forum_per_page) {
  global $user, $forum_topic_list_header;

  $forum_topic_list_header = array(
    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'),
  );

  $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'];
    }
  }

  $query = db_select('forum_index', 'f')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
    ->extend('Drupal\Core\Database\Query\TableSortExtender');
  $query->fields('f');
  $query
    ->condition('f.tid', $tid)
    ->addTag('node_access')
    ->addMetaData('base_table', 'forum_index')
    ->orderBy('f.sticky', 'DESC')
    ->orderByHeader($forum_topic_list_header)
    ->limit($forum_per_page);

  $count_query = db_select('forum_index', 'f');
  $count_query->condition('f.tid', $tid);
  $count_query->addExpression('COUNT(*)');
  $count_query->addTag('node_access');
  $count_query->addMetaData('base_table', 'forum_index');

  $query->setCountQuery($count_query);
  $result = $query->execute();
  $nids = array();
  foreach ($result as $record) {
    $nids[] = $record->nid;
  }
  if ($nids) {
    $nodes = node_load_multiple($nids);

    $query = db_select('node', 'n')
      ->extend('Drupal\Core\Database\Query\TableSortExtender');
    $query->fields('n', array('nid'));

    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
    $query->fields('ncs', array('cid', 'last_comment_uid', 'last_comment_timestamp', 'comment_count'));

    $query->join('forum_index', 'f', 'f.nid = ncs.nid');
    $query->addField('f', 'tid', 'forum_tid');

    $query->join('users', 'u', 'n.uid = u.uid');
    $query->addField('u', 'name');

    $query->join('users', 'u2', 'ncs.last_comment_uid = u2.uid');

    $query->addExpression('CASE ncs.last_comment_uid WHEN 0 THEN ncs.last_comment_name ELSE u2.name END', 'last_comment_name');

    $query
      ->orderBy('f.sticky', 'DESC')
      ->orderByHeader($forum_topic_list_header)
      ->condition('n.nid', $nids);

    $result = array();
    foreach ($query->execute() as $row) {
      $topic = $nodes[$row->nid];
      $topic->comment_mode = $topic->comment;

      foreach ($row as $key => $value) {
        $topic->{$key} = $value;
      }
      $result[] = $topic;
    }
  }
  else {
    $result = array();
  }

  $topics = array();
  $first_new_found = FALSE;
  foreach ($result as $topic) {
    if ($user->uid) {
      // A forum is new if the topic is new, or if there are new comments since
      // the user's last visit.
      if ($topic->forum_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->last_comment_timestamp > $history);
      }
    }
    else {
      // Do not track "new replies" status for topics if the user is anonymous.
      $topic->new_replies = 0;
      $topic->new = 0;
    }

    // Make sure only one topic is indicated as the first new topic.
    $topic->first_new = FALSE;
    if ($topic->new != 0 && !$first_new_found) {
      $topic->first_new = TRUE;
      $first_new_found = TRUE;
    }

    if ($topic->comment_count > 0) {
      $last_reply = new stdClass();
      $last_reply->created = $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->nid] = $topic;
  }

  return $topics;
}

/**
 * Implements hook_preprocess_HOOK() for block.tpl.php.
 */
function forum_preprocess_block(&$variables) {
  if ($variables['configuration']['module'] == 'forum') {
    $variables['attributes']['role'] = 'navigation';
  }
}

/**
 * Prepares variables for forums templates.
 *
 * Default template: forums.html.twig.
 *
 * @param array $variables
 *   An array containing the following elements:
 *   - forums: An array of all forum objects to display for the given taxonomy
 *     term ID. If tid = 0 then all the top-level forums are displayed.
 *   - topics: An array of all the topics in the current forum.
 *   - parents: An array of taxonomy term objects that are ancestors of the
 *     current term ID.
 *   - tid: Taxonomy term ID of the current forum.
 *   - sortby: One of the following integers indicating the sort criteria:
 *     - 1: Date - newest first.
 *     - 2: Date - oldest first.
 *     - 3: Posts with the most comments first.
 *     - 4: Posts with the least comments first.
 *   - forum_per_page: The maximum number of topics to display per page.
 */
function template_preprocess_forums(&$variables) {
  if ($variables['forums_defined'] = count($variables['forums']) || count($variables['parents'])) {
    if (!empty($variables['forums'])) {
      $variables['forums'] = array(
        '#theme' => 'forum_list',
        '#forums' => $variables['forums'],
        '#parents' => $variables['parents'],
        '#tid' => $variables['tid'],
      );
    }
    else {
      $variables['forums'] = array();
    }

    if ($variables['tid'] && array_search($variables['tid'], config('forum.settings')->get('containers')) === FALSE) {
      $variables['topics'] = array(
        '#theme' => 'forum_topic_list',
        '#tid' => $variables['tid'],
        '#topics' => $variables['topics'],
        '#sortby' => $variables['sortby'],
        '#forum_per_page' => $variables['forum_per_page'],
      );
    }
    else {
      $variables['topics'] = array();
    }

    // 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['theme_hook_suggestions'][] = 'forums__containers';
      $variables['theme_hook_suggestions'][] = 'forums__' . $variables['tid'];
      $variables['theme_hook_suggestions'][] = 'forums__containers__' . $variables['tid'];
    }
    elseif (!$variables['forums'] && $variables['topics']) {
      $variables['theme_hook_suggestions'][] = 'forums__topics';
      $variables['theme_hook_suggestions'][] = 'forums__' . $variables['tid'];
      $variables['theme_hook_suggestions'][] = 'forums__topics__' . $variables['tid'];
    }
    else {
      $variables['theme_hook_suggestions'][] = 'forums__' . $variables['tid'];
    }

  }
  else {
    $variables['forums'] = array();
    $variables['topics'] = array();
  }
}

/**
 * Prepares variables for forum list templates.
 *
 * Default template: forum-list.html.twig.
 *
 * @param array $variables
 *   An array containing the following elements:
 *   - forums: An array of all forum objects to display for the given taxonomy
 *     term ID. If tid = 0 then all the top-level forums are displayed.
 *   - parents: An array of taxonomy term objects that are ancestors of the
 *     current term ID.
 *   - tid: Taxonomy term ID of the current forum.
 */
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 = filter_xss_admin($forum->description->value);
    $variables['forums'][$id]->link = url("forum/" . $forum->id());
    $variables['forums'][$id]->name = check_plain($forum->label());
    $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;
    $variables['forums'][$id]->icon_class = 'default';
    $variables['forums'][$id]->icon_title = t('No new posts');
    if ($user->uid) {
      $variables['forums'][$id]->new_topics = _forum_topics_unread($forum->id(), $user->uid);
      if ($variables['forums'][$id]->new_topics) {
        $variables['forums'][$id]->new_text = format_plural($variables['forums'][$id]->new_topics, '1 new post<span class="element-invisible"> in forum %title</span>', '@count new posts<span class="element-invisible"> in forum %title</span>', array('%title' => $variables['forums'][$id]->label()));
        $variables['forums'][$id]->new_url = url('forum/' . $forum->id(), array('fragment' => 'new'));
        $variables['forums'][$id]->icon_class = 'new';
        $variables['forums'][$id]->icon_title = t('New posts');
      }
      $variables['forums'][$id]->old_topics = $forum->num_topics - $variables['forums'][$id]->new_topics;
    }
    $variables['forums'][$id]->last_reply = theme('forum_submitted', array('topic' => $forum->last_post));
  }

  $variables['pager'] = array(
   '#theme' => 'pager',
  );

  // Give meaning to $tid for themers. $tid actually stands for term ID.
  $variables['forum_id'] = $variables['tid'];
  unset($variables['tid']);
}

/**
 * Prepares variables for forum topic list templates.
 *
 * Default template: forum-topic-list.html.twig.
 *
 * @param array $variables
 *   An array containing the following elements:
 *   - tid: Taxonomy term ID of the current forum.
 *   - topics: An array of all the topics in the current forum.
 *   - forum_per_page: The maximum number of topics to display per page.
 */
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 = array(
        '#theme' => 'forum_icon',
        '#new_posts' => $topic->new,
        '#num_posts' => $topic->comment_count,
        '#comment_mode' => $topic->comment_mode,
        '#sticky' => $topic->sticky,
        '#first_new' => $topic->first_new,
      );
      $variables['topics'][$id]->zebra = $row % 2 == 0 ? 'odd' : 'even';
      $row++;

      // We keep the actual tid in forum table, if it's different from the
      // current tid then it means the topic appears in two forums, one of
      // them is a shadow copy.
      if ($variables['tid'] != $topic->forum_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->forum_tid");
      }
      else {
        $variables['topics'][$id]->moved = FALSE;
        $variables['topics'][$id]->title = l($topic->title, "node/$topic->nid");
        $variables['topics'][$id]->message = '';
      }
      $variables['topics'][$id]->created = theme('forum_submitted', array('topic' => $topic));
      $variables['topics'][$id]->last_reply = theme('forum_submitted', array('topic' => 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 = format_plural($topic->new_replies, '1 new post<span class="element-invisible"> in topic %title</span>', '@count new posts<span class="element-invisible"> in topic %title</span>', array('%title' => $variables['topics'][$id]->title));
        $variables['topics'][$id]->new_url = url("node/$topic->nid", array('query' => comment_new_page_count($topic->comment_count, $topic->new_replies, $topic), 'fragment' => 'new'));
      }

    }
  }
  else {
    // Make this safe for the template.
    $variables['topics'] = array();
  }
  // Give meaning to $tid for themers. $tid actually stands for term id.
  $variables['topic_id'] = $variables['tid'];
  unset($variables['tid']);

  $variables['pager'] = array(
    '#theme' => 'pager',
  );
}

/**
 * Prepares variables for forum icon templates.
 *
 * Default template: forum-icon.html.twig.
 *
 * @param array $variables
 *   An array containing the following elements:
 *   - new_posts: Indicates whether or not the topic contains new posts.
 *   - num_posts: The total number of posts in all topics.
 *   - comment_mode: An integer indicating whether comments are open, closed,
 *     or hidden.
 *   - sticky: Indicates whether the topic is sticky.
 *   - first_new: Indicates whether this is the first topic with new posts.
 */
function template_preprocess_forum_icon(&$variables) {
  $variables['hot_threshold'] = config('forum.settings')->get('topics.hot_threshold');

  if ($variables['num_posts'] > $variables['hot_threshold']) {
    $icon_status_class = $variables['new_posts'] ? 'hot-new' : 'hot';
    $variables['icon_title'] = $variables['new_posts'] ? t('Hot topic, new comments') : t('Hot topic');
  }
  else {
    $icon_status_class = $variables['new_posts'] ? 'new' : 'default';
    $variables['icon_title'] = $variables['new_posts'] ? t('New comments') : t('Normal topic');
  }

  if ($variables['comment_mode'] == COMMENT_NODE_CLOSED || $variables['comment_mode'] == COMMENT_NODE_HIDDEN) {
    $icon_status_class = 'closed';
    $variables['icon_title'] = t('Closed topic');
  }

  if ($variables['sticky'] == 1) {
    $icon_status_class = 'sticky';
    $variables['icon_title'] = t('Sticky topic');
  }

  $variables['attributes']['class'][] = 'icon';
  $variables['attributes']['class'][] = 'topic-status-' . $icon_status_class;
  $variables['attributes']['title'] = $variables['icon_title'];
}

/**
 * Prepares variables for forum submission information templates.
 *
 * The submission information will be displayed in the forum list and topic
 * list.
 *
 * Default template: forum-submitted.html.twig.
 *
 * @param array $variables
 *   An array containing the following elements:
 *   - topic: The topic object.
 */
function template_preprocess_forum_submitted(&$variables) {
  $variables['author'] = isset($variables['topic']->uid) ? theme('username', array('account' => $variables['topic'])) : '';
  $variables['time'] = isset($variables['topic']->created) ? format_interval(REQUEST_TIME - $variables['topic']->created) : '';
}

/**
 * Gets the last time the user viewed a node.
 *
 * @param $nid
 *   The node ID.
 *
 * @return
 *   The timestamp when the user last viewed this node, if the user has
 *   previously viewed the node; otherwise HISTORY_READ_LIMIT.
 */
function _forum_user_last_visit($nid) {
  global $user;
  $history = &drupal_static(__FUNCTION__, array());

  if (empty($history)) {
    $result = db_query('SELECT nid, timestamp FROM {history} WHERE uid = :uid', array(':uid' => $user->uid));
    foreach ($result as $t) {
      $history[$t->nid] = $t->timestamp > HISTORY_READ_LIMIT ? $t->timestamp : HISTORY_READ_LIMIT;
    }
  }
  return isset($history[$nid]) ? $history[$nid] : HISTORY_READ_LIMIT;
}

/**
 * Gets topic sorting information based on an integer code.
 *
 * @param $sortby
 *   One of the following integers indicating the sort criteria:
 *   - 1: Date - newest first.
 *   - 2: Date - oldest first.
 *   - 3: Posts with the most comments first.
 *   - 4: Posts with the least comments first.
 *
 * @return
 *   An array with the following values:
 *   - field: A field for an SQL query.
 *   - sort: 'asc' or 'desc'.
 */
function _forum_get_topic_order($sortby) {
  switch ($sortby) {
    case 1:
      return array('field' => 'f.last_comment_timestamp', 'sort' => 'desc');
      break;
    case 2:
      return array('field' => 'f.last_comment_timestamp', 'sort' => 'asc');
      break;
    case 3:
      return array('field' => 'f.comment_count', 'sort' => 'desc');
      break;
    case 4:
      return array('field' => 'f.comment_count', 'sort' => 'asc');
      break;
  }
}

/**
 * Updates the taxonomy index for a given node.
 *
 * @param $nid
 *   The ID of the node to update.
 */
function _forum_update_forum_index($nid) {
  $count = db_query('SELECT COUNT(cid) FROM {comment} c INNER JOIN {forum_index} i ON c.nid = i.nid WHERE c.nid = :nid AND c.status = :status', array(
    ':nid' => $nid,
    ':status' => COMMENT_PUBLISHED,
  ))->fetchField();

  if ($count > 0) {
    // Comments exist.
    $last_reply = db_query_range('SELECT cid, name, created, uid FROM {comment} WHERE nid = :nid AND status = :status ORDER BY cid DESC', 0, 1, array(
      ':nid' => $nid,
      ':status' => COMMENT_PUBLISHED,
    ))->fetchObject();
    db_update('forum_index')
      ->fields( array(
        'comment_count' => $count,
        'last_comment_timestamp' => $last_reply->created,
      ))
      ->condition('nid', $nid)
      ->execute();
  }
  else {
    // Comments do not exist.
    $node = db_query('SELECT uid, created FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchObject();
    db_update('forum_index')
      ->fields( array(
        'comment_count' => 0,
        'last_comment_timestamp' => $node->created,
      ))
      ->condition('nid', $nid)
      ->execute();
  }
}

/**
 * Implements hook_rdf_mapping().
 */
function forum_rdf_mapping() {
  return array(
    array(
      'type' => 'node',
      'bundle' => 'forum',
      'mapping' => array(
        'rdftype' => array('sioc:Post', 'sioct:BoardPost'),
        'taxonomy_forums' => array(
          'predicates' => array('sioc:has_container'),
          'type' => 'rel',
        ),
      ),
    ),
    array(
      'type' => 'taxonomy_term',
      'bundle' => 'forums',
      'mapping' => array(
        'rdftype' => array('sioc:Container', 'sioc:Forum'),
      ),
    ),
  );
}