forum.module 46.1 KB
Newer Older
Dries's avatar
Dries committed
1 2
<?php

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

8
use Drupal\Core\Entity\EntityInterface;
9
use Drupal\entity\Plugin\Core\Entity\EntityDisplay;
10
use Drupal\taxonomy\Plugin\Core\Entity\Term;
11

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

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

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

166
/**
167
 * Implements hook_menu_local_tasks().
168
 */
169
function forum_menu_local_tasks(&$data, $router_item, $root_path) {
170 171
  global $user;

172 173 174
  // Add action link to 'node/add/forum' on 'forum' sub-pages.
  if ($root_path == 'forum' || $root_path == 'forum/%') {
    $tid = (isset($router_item['page_arguments'][0]) ? $router_item['page_arguments'][0]->tid : 0);
175 176
    $forum_term = forum_forum_load($tid);
    if ($forum_term) {
177 178
      $links = array();
      // Loop through all bundles for forum taxonomy vocabulary field.
179
      $field = field_info_field('taxonomy_forums');
180 181 182 183 184
      foreach ($field['bundles']['node'] as $type) {
        if (node_access('create', $type)) {
          $links[$type] = array(
            '#theme' => 'menu_local_action',
            '#link' => array(
185
              'title' => t('Add new @node_type', array('@node_type' => node_type_get_label($type))),
186
              'href' => 'node/add/' . $type . '/' . $forum_term->tid,
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
            ),
          );
        }
      }
      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(
206
              'title' => t('<a href="@login">Log in</a> to post new content in the forum.', array(
207 208 209 210 211 212 213
                '@login' => url('user/login', array('query' => drupal_get_destination())),
              )),
              'localized_options' => array('html' => TRUE),
            ),
          );
        }
      }
214
      $data['actions'] += $links;
215 216 217
    }
  }
}
218

219
/**
220
 * Implements hook_entity_bundle_info_alter().
221
 */
222
function forum_entity_bundle_info_alter(&$bundles) {
223
  // Take over URI construction for taxonomy terms that are forums.
224
  if ($vid = config('forum.settings')->get('vocabulary')) {
225 226
    if (isset($bundles['taxonomy_term'][$vid])) {
      $bundles['taxonomy_term'][$vid]['uri_callback'] = 'forum_uri';
227 228 229 230 231
    }
  }
}

/**
232
 * Entity URI callback used in forum_entity_info_alter().
233 234 235 236 237 238 239
 */
function forum_uri($forum) {
  return array(
    'path' => 'forum/' . $forum->tid,
  );
}

240
/**
241
 * Checks whether a node can be used in a forum, based on its content type.
242
 *
243
 * @param \Drupal\Core\Entity\EntityInterface $node
244
 *   A node entity.
245
 *
246 247
 * @return
 *   Boolean indicating if the node can be assigned to a forum.
248
 */
249
function _forum_node_check_node_type(EntityInterface $node) {
250
  // Fetch information about the forum field.
251 252
  $instance = field_info_instance('node', 'taxonomy_forums', $node->type);
  return !empty($instance);
253
}
254

255
/**
256
 * Implements hook_node_view().
257
 */
258
function forum_node_view(EntityInterface $node, EntityDisplay $display, $view_mode) {
259
  $vid = config('forum.settings')->get('vocabulary');
260
  $vocabulary = taxonomy_vocabulary_load($vid);
261
  if (_forum_node_check_node_type($node)) {
262
    if ($view_mode == 'full' && node_is_page($node)) {
263 264 265
      // Breadcrumb navigation
      $breadcrumb[] = l(t('Home'), NULL);
      $breadcrumb[] = l($vocabulary->name, 'forum');
266
      if ($parents = taxonomy_term_load_parents_all($node->forum_tid)) {
267
        $parents = array_reverse($parents);
268
        foreach ($parents as $parent) {
269
          $breadcrumb[] = l($parent->label(), 'forum/' . $parent->tid);
270 271 272
        }
      }
      drupal_set_breadcrumb($breadcrumb);
273

274 275 276
    }
  }
}
277

278
/**
279
 * Implements hook_node_validate().
280
 *
281 282
 * Checks in particular that the node is assigned only a "leaf" term in the
 * forum taxonomy.
283
 */
284
function forum_node_validate(EntityInterface $node, $form) {
285 286
  if (_forum_node_check_node_type($node)) {
    $langcode = $form['taxonomy_forums']['#language'];
287
    // vocabulary is selected, not a "container" term.
288
    if (!empty($node->taxonomy_forums[$langcode])) {
289
      // Extract the node's proper topic ID.
290
      $containers = config('forum.settings')->get('containers');
291 292 293 294 295 296 297
      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;
        }
298
        $term = taxonomy_term_load($item['tid']);
299 300 301 302
        if (!$term) {
          form_set_error('taxonomy_forums', t('Select a forum.'));
          continue;
        }
303
        $used = db_query_range('SELECT 1 FROM {taxonomy_term_data} WHERE tid = :tid AND vid = :vid', 0, 1, array(
304
          ':tid' => $term->tid,
305
          ':vid' => $term->bundle(),
306
        ))->fetchField();
307
        if ($used && in_array($term->tid, $containers)) {
308
          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())));
309 310
        }
      }
311 312 313
    }
  }
}
314

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

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

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

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

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

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

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

466
/**
467
 * Implements hook_taxonomy_term_delete().
468
 */
469
function forum_taxonomy_term_delete(Term $term) {
470
  // For containers, remove the tid from the forum_containers variable.
471 472
  $config = config('forum.settings');
  $containers = $config->get('containers');
473
  $key = array_search($term->tid, $containers);
474 475 476
  if ($key !== FALSE) {
    unset($containers[$key]);
  }
477
  $config->set('containers', $containers)->save();
478
}
479

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

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

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

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

/**
519
 * Implements hook_field_storage_pre_insert().
520
 */
521 522
function forum_field_storage_pre_insert(EntityInterface $entity, &$skip_fields) {
  if ($entity->entityType() == 'node' && $entity->status && _forum_node_check_node_type($entity)) {
523
    $query = db_insert('forum_index')->fields(array('nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp'));
524 525 526 527 528 529 530 531 532 533 534
    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,
      ));
535 536 537 538 539 540
    }
    $query->execute();
  }
}

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

546
  if ($entity->entityType() == 'node' && _forum_node_check_node_type($entity)) {
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

    // 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,
          ));
        }
571
      }
572 573 574 575
      $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);
576
    }
577 578 579 580 581 582

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

583 584
  }
}
585

586
/**
587
 * Implements hook_form_BASE_FORM_ID_alter().
588
 */
589
function forum_form_taxonomy_vocabulary_form_alter(&$form, &$form_state, $form_id) {
590
  $vid = config('forum.settings')->get('vocabulary');
591 592
  $vocabulary = $form_state['controller']->getEntity($form_state);
  if ($vid == $vocabulary->id()) {
593 594 595 596 597 598 599 600 601 602
    $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;
603 604
    // Do not allow to change a vid of forum's vocabulary.
    $form['vid']['#disabled'] = TRUE;
605 606 607 608
  }
}

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

/**
620
 * Implements hook_form_BASE_FORM_ID_alter() for node_form().
621 622 623
 */
function forum_form_node_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['taxonomy_forums'])) {
624
    $langcode = $form['taxonomy_forums']['#language'];
625
    // Make the vocabulary required for 'real' forum-nodes.
626 627
    $form['taxonomy_forums'][$langcode]['#required'] = TRUE;
    $form['taxonomy_forums'][$langcode]['#multiple'] = FALSE;
628 629
    if (empty($form['taxonomy_forums'][$langcode]['#default_value'])) {
      // If there is no default forum already selected, try to get the forum
630 631
      // 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).
632
      $requested_forum_id = arg(3);
633
      $form['taxonomy_forums'][$langcode]['#default_value'] = is_numeric($requested_forum_id) ? $requested_forum_id : '';
634
    }
635
  }
636 637
}

638
/**
639 640 641 642 643 644
 * Render API callback: Lists nodes based on the element's #query property.
 *
 * This function can be used as a #pre_render callback.
 *
 * @see forum_block_view()
 */
645 646 647
function forum_block_view_pre_render($elements) {
  $result = $elements['#query']->execute();
  if ($node_title_list = node_title_list($result)) {
648
    $elements['forum_list'] = $node_title_list;
649
    $elements['forum_more'] = array('#theme' => 'more_link', '#url' => 'forum', '#title' => t('Read the latest forum topics.'));
650
  }
651
  return $elements;
652 653
}

654
/**
655
 * Implements hook_form().
656
 */
657
function forum_form(EntityInterface $node, &$form_state) {
658
  $type = node_type_load($node->type);
659 660 661 662 663 664
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => check_plain($type->title_label),
    '#default_value' => !empty($node->title) ? $node->title : '',
    '#required' => TRUE, '#weight' => -5
  );
665

666
  if (!empty($node->nid)) {
667
    $forum_terms = $node->taxonomy_forums;
668
    // If editing, give option to leave shadows.
669
    $shadow = (count($forum_terms) > 1);
670
    $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.'));
671
    $form['forum_tid'] = array('#type' => 'value', '#value' => $node->forum_tid);
Dries's avatar
Dries committed
672
  }
673

674
  return $form;
Dries's avatar
Dries committed
675 676
}

677
/**
678
 * Returns a tree of all forums for a given taxonomy term ID.
679 680
 *
 * @param $tid
681 682 683
 *   (optional) Taxonomy term ID of the forum. If not given all forums will be
 *   returned.
 *
684
 * @return
685
 *   A tree of taxonomy objects, with the following additional properties:
686 687 688 689
 *   - 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.
690
 */
691
function forum_forum_load($tid = NULL) {
692 693
  $cache = &drupal_static(__FUNCTION__, array());

694 695 696 697
  // Return a cached forum tree if available.
  if (!isset($tid)) {
    $tid = 0;
  }
698 699 700
  if (isset($cache[$tid])) {
    return $cache[$tid];
  }
701

702 703
  $config = config('forum.settings');
  $vid = $config->get('vocabulary');
704 705 706 707

  // Load and validate the parent term.
  if ($tid) {
    $forum_term = taxonomy_term_load($tid);
708
    if (!$forum_term || ($forum_term->bundle() != $vid)) {
709 710 711
      return $cache[$tid] = FALSE;
    }
  }
712
  // If $tid is 0, create an empty entity to hold the child terms.
713
  elseif ($tid === 0) {
714
    $forum_term = entity_create('taxonomy_term', array(
715
      'tid' => 0,
716
    ));
717 718 719
  }

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

  // Load parent terms.
725
  $forum_term->parents = taxonomy_term_load_parents_all($forum_term->tid);
726 727 728

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

731
  if (count($_forums)) {
732 733
    $query = db_select('node', 'n');
    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
734
    $query->join('forum', 'f', 'n.vid = f.vid');
735 736 737
    $query->addExpression('COUNT(n.nid)', 'topic_count');
    $query->addExpression('SUM(ncs.comment_count)', 'comment_count');
    $counts = $query
738
      ->fields('f', array('tid'))
739
      ->condition('n.status', 1)
740 741 742 743
      ->groupBy('tid')
      ->addTag('node_access')
      ->execute()
      ->fetchAllAssoc('tid');
744
  }
745

746
  foreach ($_forums as $forum) {
747
    // Determine if the child term is a container.
748
    if (in_array($forum->tid, $config->get('containers'))) {
749 750
      $forum->container = 1;
    }
751

752
    // Merge in the topic and post counters.
753
    if (!empty($counts[$forum->tid])) {
754 755 756 757 758 759 760 761
      $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;
    }

762
    // Query "Last Post" information for this forum.
763
    $query = db_select('node', 'n');
764
    $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $forum->tid));
765
    $query->join('node_comment_statistics', 'ncs', 'n.nid = ncs.nid');
766 767
    $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');
768

769 770 771 772 773 774 775 776
    $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();
777

778
    // Merge in the "Last Post" information.
779
    $last_post = new stdClass();
780
    if (!empty($topic->last_comment_timestamp)) {
781
      $last_post->created = $topic->last_comment_timestamp;
782 783 784
      $last_post->name = $topic->last_comment_name;
      $last_post->uid = $topic->last_comment_uid;
    }
785
    $forum->last_post = $last_post;
786

787 788 789
    $forums[$forum->tid] = $forum;
  }

790 791 792 793
  // Cache the result, and return the tree.
  $forum_term->forums = $forums;
  $cache[$tid] = $forum_term;
  return $forum_term;
794 795
}

796
/**
797 798
 * Calculates the number of new posts in a forum that the user has not yet read.
 *
799
 * Nodes are new if they are newer than HISTORY_READ_LIMIT.
800 801 802 803 804 805 806 807
 *
 * @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.
808 809
 */
function _forum_topics_unread($term, $uid) {
810
  $query = db_select('node', 'n');
811
  $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $term));
812
  $query->leftJoin('history', 'h', 'n.nid = h.nid AND h.uid = :uid', array(':uid' => $uid));
813 814 815
  $query->addExpression('COUNT(n.nid)', 'count');
  return $query
    ->condition('status', 1)
816
    ->condition('n.created', HISTORY_READ_LIMIT, '>')
817 818 819 820
    ->isNull('h.nid')
    ->addTag('node_access')
    ->execute()
    ->fetchField();
821 822
}

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
/**
 * 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.
 */
Dries's avatar
Dries committed
840
function forum_get_topics($tid, $sortby, $forum_per_page) {
841
  global $user, $forum_topic_list_header;
842

843
  $forum_topic_list_header = array(
844 845 846
    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'),
847
  );
848

Dries's avatar
Dries committed
849
  $order = _forum_get_topic_order($sortby);
850
  for ($i = 0; $i < count($forum_topic_list_header); $i++) {
Dries's avatar
Dries committed
851 852
    if ($forum_topic_list_header[$i]['field'] == $order['field']) {
      $forum_topic_list_header[$i]['sort'] = $order['sort'];
853 854 855
    }
  }

856 857
  $query = db_select('forum_index', 'f')
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
858
    ->extend('Drupal\Core\Database\Query\TableSortExtender');
859
  $query->fields('f');