clean install

This commit is contained in:
2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 changed files with 3555714 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
<?php
namespace Drupal\forum\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\forum\ForumManagerInterface;
/**
* Provides a forum breadcrumb base class.
*
* This just holds the dependency-injected config, entity type manager, and
* forum manager objects.
*/
abstract class ForumBreadcrumbBuilderBase implements BreadcrumbBuilderInterface {
use StringTranslationTrait;
/**
* Configuration object for this builder.
*
* @var \Drupal\Core\Config\Config
*/
protected $config;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The forum manager service.
*
* @var \Drupal\forum\ForumManagerInterface
*/
protected $forumManager;
/**
* The taxonomy term storage.
*
* @var \Drupal\taxonomy\TermStorageInterface
*/
protected $termStorage;
/**
* Constructs a forum breadcrumb builder object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\forum\ForumManagerInterface $forum_manager
* The forum manager service.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ConfigFactoryInterface $config_factory, ForumManagerInterface $forum_manager, TranslationInterface $string_translation) {
$this->entityTypeManager = $entity_type_manager;
$this->config = $config_factory->get('forum.settings');
$this->forumManager = $forum_manager;
$this->setStringTranslation($string_translation);
$this->termStorage = $entity_type_manager->getStorage('taxonomy_term');
}
/**
* {@inheritdoc}
*/
public function build(RouteMatchInterface $route_match) {
$breadcrumb = new Breadcrumb();
$breadcrumb->addCacheContexts(['route']);
$links[] = Link::createFromRoute($this->t('Home'), '<front>');
$vocabulary = $this->entityTypeManager
->getStorage('taxonomy_vocabulary')
->load($this->config->get('vocabulary'));
$breadcrumb->addCacheableDependency($vocabulary);
$links[] = Link::createFromRoute($vocabulary->label(), 'forum.index');
return $breadcrumb->setLinks($links);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Drupal\forum\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Provides a breadcrumb builder base class for forum listing pages.
*/
class ForumListingBreadcrumbBuilder extends ForumBreadcrumbBuilderBase {
/**
* {@inheritdoc}
*/
public function applies(RouteMatchInterface $route_match) {
return $route_match->getRouteName() == 'forum.page' && $route_match->getParameter('taxonomy_term');
}
/**
* {@inheritdoc}
*/
public function build(RouteMatchInterface $route_match) {
$breadcrumb = parent::build($route_match);
$breadcrumb->addCacheContexts(['route']);
// Add all parent forums to breadcrumbs.
/** @var \Drupal\taxonomy\TermInterface $term */
$term = $route_match->getParameter('taxonomy_term');
$term_id = $term->id();
$breadcrumb->addCacheableDependency($term);
$parents = $this->termStorage->loadAllParents($term_id);
if ($parents) {
foreach (array_reverse($parents) as $parent) {
if ($parent->id() != $term_id) {
$breadcrumb->addCacheableDependency($parent);
$breadcrumb->addLink(Link::createFromRoute($parent->label(), 'forum.page', [
'taxonomy_term' => $parent->id(),
]));
}
}
}
return $breadcrumb;
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace Drupal\forum\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Breadcrumb builder for forum nodes.
*/
class ForumNodeBreadcrumbBuilder extends ForumBreadcrumbBuilderBase {
/**
* {@inheritdoc}
*/
public function applies(RouteMatchInterface $route_match) {
return $route_match->getRouteName() == 'entity.node.canonical'
&& $route_match->getParameter('node')
&& $this->forumManager->checkNodeType($route_match->getParameter('node'));
}
/**
* {@inheritdoc}
*/
public function build(RouteMatchInterface $route_match) {
$breadcrumb = parent::build($route_match);
$breadcrumb->addCacheContexts(['route']);
$parents = $this->termStorage->loadAllParents($route_match->getParameter('node')->forum_tid);
if ($parents) {
$parents = array_reverse($parents);
foreach ($parents as $parent) {
$breadcrumb->addCacheableDependency($parent);
$breadcrumb->addLink(Link::createFromRoute($parent->label(), 'forum.page',
[
'taxonomy_term' => $parent->id(),
]
));
}
}
return $breadcrumb;
}
}

View File

@@ -0,0 +1,348 @@
<?php
namespace Drupal\forum\Controller;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityAccessControlHandlerInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\forum\ForumManagerInterface;
use Drupal\taxonomy\TermInterface;
use Drupal\taxonomy\TermStorageInterface;
use Drupal\taxonomy\VocabularyStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Controller routines for forum routes.
*/
class ForumController extends ControllerBase {
/**
* Forum manager service.
*
* @var \Drupal\forum\ForumManagerInterface
*/
protected $forumManager;
/**
* Vocabulary storage.
*
* @var \Drupal\taxonomy\VocabularyStorageInterface
*/
protected $vocabularyStorage;
/**
* Term storage.
*
* @var \Drupal\taxonomy\TermStorageInterface
*/
protected $termStorage;
/**
* Node access control handler.
*
* @var \Drupal\Core\Entity\EntityAccessControlHandlerInterface
*/
protected $nodeAccess;
/**
* Field map of existing fields on the site.
*
* @var array
*/
protected $fieldMap;
/**
* Node type storage handler.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeTypeStorage;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* Node entity type, we need to get cache tags from here.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $nodeEntityTypeDefinition;
/**
* Comment entity type, we need to get cache tags from here.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $commentEntityTypeDefinition;
/**
* Constructs a ForumController object.
*
* @param \Drupal\forum\ForumManagerInterface $forum_manager
* The forum manager service.
* @param \Drupal\taxonomy\VocabularyStorageInterface $vocabulary_storage
* Vocabulary storage.
* @param \Drupal\taxonomy\TermStorageInterface $term_storage
* Term storage.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current logged in user.
* @param \Drupal\Core\Entity\EntityAccessControlHandlerInterface $node_access
* Node access control handler.
* @param array $field_map
* Array of active fields on the site.
* @param \Drupal\Core\Entity\EntityStorageInterface $node_type_storage
* Node type storage handler.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Drupal\Core\Entity\EntityTypeInterface $node_entity_type_definition
* Node entity type definition object
* @param \Drupal\Core\Entity\EntityTypeInterface $comment_entity_type_definition
* Comment entity type definition object
*/
public function __construct(ForumManagerInterface $forum_manager, VocabularyStorageInterface $vocabulary_storage, TermStorageInterface $term_storage, AccountInterface $current_user, EntityAccessControlHandlerInterface $node_access, array $field_map, EntityStorageInterface $node_type_storage, RendererInterface $renderer, EntityTypeInterface $node_entity_type_definition, EntityTypeInterface $comment_entity_type_definition) {
$this->forumManager = $forum_manager;
$this->vocabularyStorage = $vocabulary_storage;
$this->termStorage = $term_storage;
$this->currentUser = $current_user;
$this->nodeAccess = $node_access;
$this->fieldMap = $field_map;
$this->nodeTypeStorage = $node_type_storage;
$this->renderer = $renderer;
$this->nodeEntityTypeDefinition = $node_entity_type_definition;
$this->commentEntityTypeDefinition = $comment_entity_type_definition;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
$entity_type_manager = $container->get('entity_type.manager');
return new static(
$container->get('forum_manager'),
$entity_type_manager->getStorage('taxonomy_vocabulary'),
$entity_type_manager->getStorage('taxonomy_term'),
$container->get('current_user'),
$entity_type_manager->getAccessControlHandler('node'),
$container->get('entity_field.manager')->getFieldMap(),
$entity_type_manager->getStorage('node_type'),
$container->get('renderer'),
$entity_type_manager->getDefinition('node'),
$entity_type_manager->getDefinition('comment')
);
}
/**
* Returns forum page for a given forum.
*
* @param \Drupal\taxonomy\TermInterface $taxonomy_term
* The forum to render the page for.
*
* @return array
* A render array.
*/
public function forumPage(TermInterface $taxonomy_term) {
// Get forum details.
$taxonomy_term->forums = $this->forumManager->getChildren($this->config('forum.settings')->get('vocabulary'), $taxonomy_term->id());
$taxonomy_term->parents = $this->termStorage->loadAllParents($taxonomy_term->id());
if (empty($taxonomy_term->forum_container->value)) {
$build = $this->forumManager->getTopics($taxonomy_term->id(), $this->currentUser());
$topics = $build['topics'];
$header = $build['header'];
}
else {
$topics = [];
$header = [];
}
return $this->build($taxonomy_term->forums, $taxonomy_term, $topics, $taxonomy_term->parents, $header);
}
/**
* Returns forum index page.
*
* @return array
* A render array.
*/
public function forumIndex() {
$vocabulary = $this->vocabularyStorage->load($this->config('forum.settings')->get('vocabulary'));
$index = $this->forumManager->getIndex();
$build = $this->build($index->forums, $index);
if (empty($index->forums)) {
// Root of empty forum.
$build['#title'] = $this->t('No forums defined');
}
else {
// Set the page title to forum's vocabulary name.
$build['#title'] = $vocabulary->label();
$this->renderer->addCacheableDependency($build, $vocabulary);
}
return $build;
}
/**
* Returns a renderable forum index page array.
*
* @param array $forums
* A list of forums.
* @param \Drupal\taxonomy\TermInterface $term
* The taxonomy term of the forum.
* @param array $topics
* The topics of this forum.
* @param array $parents
* The parent forums in relation this forum.
* @param array $header
* Array of header cells.
*
* @return array
* A render array.
*/
protected function build($forums, TermInterface $term, $topics = [], $parents = [], $header = []) {
$config = $this->config('forum.settings');
$build = [
'#theme' => 'forums',
'#forums' => $forums,
'#topics' => $topics,
'#parents' => $parents,
'#header' => $header,
'#term' => $term,
'#sortby' => $config->get('topics.order'),
'#forums_per_page' => $config->get('topics.page_limit'),
];
if (empty($term->forum_container->value)) {
$build['#attached']['feed'][] = ['taxonomy/term/' . $term->id() . '/feed', 'RSS - ' . $term->getName()];
}
$this->renderer->addCacheableDependency($build, $config);
foreach ($forums as $forum) {
$this->renderer->addCacheableDependency($build, $forum);
}
foreach ($topics as $topic) {
$this->renderer->addCacheableDependency($build, $topic);
}
foreach ($parents as $parent) {
$this->renderer->addCacheableDependency($build, $parent);
}
$this->renderer->addCacheableDependency($build, $term);
$is_forum = empty($term->forum_container->value);
return [
'action' => ($is_forum) ? $this->buildActionLinks($config->get('vocabulary'), $term) : [],
'forum' => $build,
'#cache' => [
'tags' => Cache::mergeTags($this->nodeEntityTypeDefinition->getListCacheTags(), $this->commentEntityTypeDefinition->getListCacheTags()),
],
];
}
/**
* Returns add forum entity form.
*
* @return array
* Render array for the add form.
*/
public function addForum() {
$vid = $this->config('forum.settings')->get('vocabulary');
$taxonomy_term = $this->termStorage->create([
'vid' => $vid,
]);
return $this->entityFormBuilder()->getForm($taxonomy_term, 'forum');
}
/**
* Returns add container entity form.
*
* @return array
* Render array for the add form.
*/
public function addContainer() {
$vid = $this->config('forum.settings')->get('vocabulary');
$taxonomy_term = $this->termStorage->create([
'vid' => $vid,
'forum_container' => 1,
]);
return $this->entityFormBuilder()->getForm($taxonomy_term, 'container');
}
/**
* Generates an action link to display at the top of the forum listing.
*
* @param string $vid
* Vocabulary ID.
* @param \Drupal\taxonomy\TermInterface $forum_term
* The term for which the links are to be built.
*
* @return array
* Render array containing the links.
*/
protected function buildActionLinks($vid, ?TermInterface $forum_term = NULL) {
$user = $this->currentUser();
$links = [];
// Loop through all bundles for forum taxonomy vocabulary field.
foreach ($this->fieldMap['node']['taxonomy_forums']['bundles'] as $type) {
if ($this->nodeAccess->createAccess($type)) {
$node_type = $this->nodeTypeStorage->load($type);
$links[$type] = [
'#theme' => 'menu_local_action',
'#link' => [
'title' => $this->t('Add new @node_type', [
'@node_type' => $this->nodeTypeStorage->load($type)->label(),
]),
'url' => Url::fromRoute('node.add', ['node_type' => $type]),
],
'#cache' => [
'tags' => $node_type->getCacheTags(),
],
];
if ($forum_term && $forum_term->bundle() == $vid) {
// We are viewing a forum term (specific forum), append the tid to
// the URL.
$links[$type]['#link']['localized_options']['query']['forum_id'] = $forum_term->id();
}
}
}
if (empty($links)) {
// Authenticated user does not have access to create new topics.
if ($user->isAuthenticated()) {
$links['disallowed'] = [
'#markup' => $this->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'] = [
'#theme' => 'menu_local_action',
'#link' => [
'title' => $this->t('Log in to post new content in the forum.'),
'url' => Url::fromRoute('user.login', [], ['query' => $this->getDestinationArray()]),
],
// Without this workaround, the action links will be rendered as <li>
// with no wrapping <ul> element.
// @todo Find a better way for this in https://www.drupal.org/node/3181052.
'#prefix' => '<ul class="action-links">',
'#suffix' => '</ul>',
];
}
}
else {
// Without this workaround, the action links will be rendered as <li> with
// no wrapping <ul> element.
// @todo Find a better way for this in https://www.drupal.org/node/3181052.
$links['#prefix'] = '<ul class="action-links">';
$links['#suffix'] = '</ul>';
}
return $links;
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Drupal\forum\Form;
use Drupal\Core\Form\FormStateInterface;
/**
* Base form for container term edit forms.
*
* @internal
*/
class ContainerForm extends ForumForm {
/**
* Reusable URL stub to use in watchdog messages.
*
* @var string
*/
protected $urlStub = 'container';
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
// Build the bulk of the form from the parent forum form.
$form = parent::form($form, $form_state);
// Set the title and description of the name field.
$form['name']['#title'] = $this->t('Container name');
$form['name']['#description'] = $this->t('Short but meaningful name for this collection of related forums.');
// Alternate description for the container parent.
$form['parent'][0]['#description'] = $this->t('Containers are usually placed at the top (root) level, but may also be placed inside another container or forum.');
$this->forumFormType = $this->t('forum container');
return $form;
}
/**
* {@inheritdoc}
*/
public function buildEntity(array $form, FormStateInterface $form_state) {
$entity = parent::buildEntity($form, $form_state);
$entity->forum_container = TRUE;
return $entity;
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Drupal\forum\Form;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\taxonomy\TermInterface;
/**
* Builds the form to delete a forum term.
*
* @internal
*/
class DeleteForm extends ConfirmFormBase {
/**
* The taxonomy term being deleted.
*
* @var \Drupal\taxonomy\TermInterface
*/
protected $taxonomyTerm;
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'forum_confirm_delete';
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete the forum %label?', ['%label' => $this->taxonomyTerm->label()]);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('forum.overview');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?TermInterface $taxonomy_term = NULL) {
$this->taxonomyTerm = $taxonomy_term;
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->taxonomyTerm->delete();
$this->messenger()->addStatus($this->t('The forum %label and all sub-forums have been deleted.', ['%label' => $this->taxonomyTerm->label()]));
$this->logger('forum')->notice('forum: deleted %label and all its sub-forums.', ['%label' => $this->taxonomyTerm->label()]);
$form_state->setRedirectUrl($this->getCancelUrl());
}
}

View File

@@ -0,0 +1,170 @@
<?php
namespace Drupal\forum\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\taxonomy\TermForm;
/**
* Base form for forum term edit forms.
*
* @internal
*/
class ForumForm extends TermForm {
/**
* Reusable type field to use in status messages.
*
* @var string
*/
protected $forumFormType;
/**
* Reusable URL stub to use in watchdog messages.
*
* @var string
*/
protected $urlStub = 'forum';
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
// Build the bulk of the form from the parent taxonomy term form.
$form = parent::form($form, $form_state);
// Set the title and description of the name field.
$form['name']['#title'] = $this->t('Forum name');
$form['name']['#description'] = $this->t('Short but meaningful name for this collection of threaded discussions.');
// Change the description.
$form['description']['#description'] = $this->t('Description and guidelines for discussions within this forum.');
// Re-use the weight field.
$form['weight'] = $form['relations']['weight'];
// Remove the remaining relations fields.
unset($form['relations']);
// Our parent field is different to the taxonomy term.
$form['parent']['#tree'] = TRUE;
$form['parent'][0] = $this->forumParentSelect($this->entity->id(), $this->t('Parent'));
$form['#theme_wrappers'] = ['form__forum'];
$this->forumFormType = $this->t('forum');
return $form;
}
/**
* {@inheritdoc}
*/
public function buildEntity(array $form, FormStateInterface $form_state) {
$term = parent::buildEntity($form, $form_state);
// Assign parents from forum parent select field.
$term->parent = [$form_state->getValue(['parent', 0])];
return $term;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$term = $this->entity;
$term_storage = $this->entityTypeManager->getStorage('taxonomy_term');
$status = $term_storage->save($term);
$route_name = $this->urlStub == 'container' ? 'entity.taxonomy_term.forum_edit_container_form' : 'entity.taxonomy_term.forum_edit_form';
$route_parameters = ['taxonomy_term' => $term->id()];
$link = Link::fromTextAndUrl($this->t('Edit'), new Url($route_name, $route_parameters))->toString();
$view_link = $term->toLink($term->getName())->toString();
switch ($status) {
case SAVED_NEW:
$this->messenger()->addStatus($this->t('Created new @type %term.', ['%term' => $view_link, '@type' => $this->forumFormType]));
$this->logger('forum')->notice('Created new @type %term.', ['%term' => $term->getName(), '@type' => $this->forumFormType, 'link' => $link]);
$form_state->setValue('tid', $term->id());
break;
case SAVED_UPDATED:
$this->messenger()->addStatus($this->t('The @type %term has been updated.', ['%term' => $term->getName(), '@type' => $this->forumFormType]));
$this->logger('forum')->notice('Updated @type %term.', ['%term' => $term->getName(), '@type' => $this->forumFormType, 'link' => $link]);
break;
}
$form_state->setRedirect('forum.overview');
return $term;
}
/**
* {@inheritdoc}
*/
protected function actions(array $form, FormStateInterface $form_state) {
$actions = parent::actions($form, $form_state);
if (!$this->entity->isNew() && $this->entity->hasLinkTemplate('forum-delete-form')) {
$actions['delete']['#url'] = $this->entity->toUrl('forum-delete-form');
}
else {
unset($actions['delete']);
}
return $actions;
}
/**
* Returns a select box for available parent terms.
*
* @param int $tid
* ID of the term that is being added or edited.
* @param string $title
* Title for the select box.
*
* @return array
* A select form element.
*/
protected function forumParentSelect($tid, $title) {
$taxonomy_storage = $this->entityTypeManager->getStorage('taxonomy_term');
$parents = $taxonomy_storage->loadParents($tid);
if ($parents) {
$parent = array_shift($parents);
$parent = $parent->id();
}
else {
$parent = 0;
}
$vid = $this->config('forum.settings')->get('vocabulary');
$children = $taxonomy_storage->loadTree($vid, $tid, NULL, TRUE);
// A term can't be the child of itself, nor of its children.
foreach ($children as $child) {
$exclude[] = $child->tid;
}
$exclude[] = $tid;
$tree = $taxonomy_storage->loadTree($vid, 0, NULL, TRUE);
$options[0] = '<' . $this->t('root') . '>';
if ($tree) {
foreach ($tree as $term) {
if (!in_array($term->id(), $exclude)) {
$options[$term->id()] = str_repeat(' -- ', $term->depth) . $term->getName();
}
}
}
$description = $this->t('Forums may be placed at the top (root) level, or inside another container or forum.');
return [
'#type' => 'select',
'#title' => $title,
'#default_value' => $parent,
'#options' => $options,
'#description' => $description,
'#required' => TRUE,
];
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace Drupal\forum\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Url;
use Drupal\taxonomy\Form\OverviewTerms;
use Drupal\taxonomy\VocabularyInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Provides forum overview form for the forum vocabulary.
*
* @internal
*/
class Overview extends OverviewTerms {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'forum_overview';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?VocabularyInterface $taxonomy_vocabulary = NULL) {
$forum_config = $this->config('forum.settings');
$vid = $forum_config->get('vocabulary');
$vocabulary = $this->entityTypeManager->getStorage('taxonomy_vocabulary')->load($vid);
if (!$vocabulary) {
throw new NotFoundHttpException();
}
// Build base taxonomy term overview.
$form = parent::buildForm($form, $form_state, $vocabulary);
foreach (Element::children($form['terms']) as $key) {
if (isset($form['terms'][$key]['#term'])) {
/** @var \Drupal\taxonomy\TermInterface $term */
$term = $form['terms'][$key]['#term'];
$form['terms'][$key]['term']['#url'] = Url::fromRoute('forum.page', ['taxonomy_term' => $term->id()]);
if (!empty($term->forum_container->value)) {
$title = $this->t('edit container');
$url = Url::fromRoute('entity.taxonomy_term.forum_edit_container_form', ['taxonomy_term' => $term->id()]);
}
else {
$title = $this->t('edit forum');
$url = Url::fromRoute('entity.taxonomy_term.forum_edit_form', ['taxonomy_term' => $term->id()]);
}
// Re-create the operations column and add only the edit link.
$form['terms'][$key]['operations'] = [
'#type' => 'operations',
'#links' => [
'edit' => [
'title' => $title,
'url' => $url,
],
],
];
}
}
// Remove the alphabetical reset.
unset($form['actions']['reset_alphabetical']);
// Use the existing taxonomy overview submit handler.
$form['terms']['#empty'] = $this->t('No containers or forums available. <a href=":container">Add container</a> or <a href=":forum">Add forum</a>.', [
':container' => Url::fromRoute('forum.add_container')->toString(),
':forum' => Url::fromRoute('forum.add_forum')->toString(),
]);
return $form;
}
}

View File

@@ -0,0 +1,164 @@
<?php
namespace Drupal\forum;
use Drupal\comment\CommentInterface;
use Drupal\Core\Database\Connection;
use Drupal\node\NodeInterface;
/**
* Handles CRUD operations to {forum_index} table.
*/
class ForumIndexStorage implements ForumIndexStorageInterface {
/**
* The active database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Constructs a ForumIndexStorage object.
*
* @param \Drupal\Core\Database\Connection $database
* The current database connection.
*/
public function __construct(Connection $database) {
$this->database = $database;
}
/**
* {@inheritdoc}
*/
public function getOriginalTermId(NodeInterface $node) {
return $this->database->queryRange("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, [':nid' => $node->id()])->fetchField();
}
/**
* {@inheritdoc}
*/
public function create(NodeInterface $node) {
$this->database->insert('forum')
->fields([
'tid' => $node->forum_tid,
'vid' => $node->getRevisionId(),
'nid' => $node->id(),
])
->execute();
}
/**
* {@inheritdoc}
*/
public function read(array $vids) {
return $this->database->select('forum', 'f')
->fields('f', ['nid', 'tid'])
->condition('f.vid', $vids, 'IN')
->execute();
}
/**
* {@inheritdoc}
*/
public function delete(NodeInterface $node) {
$this->database->delete('forum')
->condition('nid', $node->id())
->execute();
}
/**
* {@inheritdoc}
*/
public function deleteRevision(NodeInterface $node) {
$this->database->delete('forum')
->condition('nid', $node->id())
->condition('vid', $node->getRevisionId())
->execute();
}
/**
* {@inheritdoc}
*/
public function update(NodeInterface $node) {
$this->database->update('forum')
->fields(['tid' => $node->forum_tid])
->condition('vid', $node->getRevisionId())
->execute();
}
/**
* {@inheritdoc}
*/
public function updateIndex(NodeInterface $node) {
$nid = $node->id();
$count = $this->database->query("SELECT COUNT([cid]) FROM {comment_field_data} [c] INNER JOIN {forum_index} [i] ON [c].[entity_id] = [i].[nid] WHERE [c].[entity_id] = :nid AND [c].[field_name] = 'comment_forum' AND [c].[entity_type] = 'node' AND [c].[status] = :status AND [c].[default_langcode] = 1", [
':nid' => $nid,
':status' => CommentInterface::PUBLISHED,
])->fetchField();
if ($count > 0) {
// Comments exist.
$last_reply = $this->database->queryRange("SELECT [cid], [name], [created], [uid] FROM {comment_field_data} WHERE [entity_id] = :nid AND [field_name] = 'comment_forum' AND [entity_type] = 'node' AND [status] = :status AND [default_langcode] = 1 ORDER BY [cid] DESC", 0, 1, [
':nid' => $nid,
':status' => CommentInterface::PUBLISHED,
])->fetchObject();
$this->database->update('forum_index')
->fields([
'comment_count' => $count,
'last_comment_timestamp' => $last_reply->created,
])
->condition('nid', $nid)
->execute();
}
else {
// Comments do not exist.
// @todo This should be actually filtering on the desired node language
$this->database->update('forum_index')
->fields([
'comment_count' => 0,
'last_comment_timestamp' => $node->getCreatedTime(),
])
->condition('nid', $nid)
->execute();
}
}
/**
* {@inheritdoc}
*/
public function createIndex(NodeInterface $node) {
$query = $this->database->insert('forum_index')
->fields(['nid', 'title', 'tid', 'sticky', 'created', 'comment_count', 'last_comment_timestamp']);
foreach ($node->getTranslationLanguages() as $langcode => $language) {
$translation = $node->getTranslation($langcode);
foreach ($translation->taxonomy_forums as $item) {
$query->values([
'nid' => $node->id(),
'title' => $translation->label(),
'tid' => $item->target_id,
'sticky' => (int) $node->isSticky(),
'created' => $node->getCreatedTime(),
'comment_count' => 0,
'last_comment_timestamp' => $node->getCreatedTime(),
]);
}
}
$query->execute();
// The logic for determining last_comment_count is fairly complex, so
// update the index too.
if ($node->isNew()) {
$this->updateIndex($node);
}
}
/**
* {@inheritdoc}
*/
public function deleteIndex(NodeInterface $node) {
$this->database->delete('forum_index')
->condition('nid', $node->id())
->execute();
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Drupal\forum;
use Drupal\node\NodeInterface;
/**
* Handles CRUD operations to {forum_index} table.
*/
interface ForumIndexStorageInterface {
/**
* Returns the forum term id associated with an existing forum node.
*
* @param \Drupal\node\NodeInterface $node
* The existing forum node.
*
* @return int
* The forum term id currently associated with the node.
*/
public function getOriginalTermId(NodeInterface $node);
/**
* Creates a record in {forum} table for the given node.
*
* @param \Drupal\node\NodeInterface $node
* The node for which the record is to be created.
*/
public function create(NodeInterface $node);
/**
* Reads an array of {forum} records for the given revision ids.
*
* @param array $vids
* An array of node revision ids.
*
* @return \Drupal\Core\Database\StatementInterface
* The records from {forum} for the given vids.
*/
public function read(array $vids);
/**
* Updates the {forum} table for the given node.
*
* @param \Drupal\node\NodeInterface $node
* The node for which the record is to be updated.
*/
public function update(NodeInterface $node);
/**
* Deletes the records in {forum} table for the given node.
*
* @param \Drupal\node\NodeInterface $node
* The node for which the records are to be deleted.
*/
public function delete(NodeInterface $node);
/**
* Deletes the records in {forum} table for a given node revision.
*
* @param \Drupal\node\NodeInterface $node
* The node revision for which the records are to be deleted.
*/
public function deleteRevision(NodeInterface $node);
/**
* Creates a {forum_index} entry for the given node.
*
* @param \Drupal\node\NodeInterface $node
* The node for which the index records are to be created.
*/
public function createIndex(NodeInterface $node);
/**
* Updates the {forum_index} records for a given node.
*
* @param \Drupal\node\NodeInterface $node
* The node for which the index records are to be updated.
*/
public function updateIndex(NodeInterface $node);
/**
* Deletes the {forum_index} records for a given node.
*
* @param \Drupal\node\NodeInterface $node
* The node for which the index records are to be deleted.
*/
public function deleteIndex(NodeInterface $node);
}

View File

@@ -0,0 +1,525 @@
<?php
namespace Drupal\forum;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\PagerSelectExtender;
use Drupal\Core\Database\Query\TableSortExtender;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\comment\CommentManagerInterface;
use Drupal\node\NodeInterface;
/**
* Provides forum manager service.
*/
class ForumManager implements ForumManagerInterface {
use StringTranslationTrait;
use DependencySerializationTrait {
__wakeup as defaultWakeup;
__sleep as defaultSleep;
}
/**
* Forum sort order, newest first.
*/
const NEWEST_FIRST = 1;
/**
* Forum sort order, oldest first.
*/
const OLDEST_FIRST = 2;
/**
* Forum sort order, posts with most comments first.
*/
const MOST_POPULAR_FIRST = 3;
/**
* Forum sort order, posts with the least comments first.
*/
const LEAST_POPULAR_FIRST = 4;
/**
* Forum settings config object.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* Entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Database connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* The comment manager service.
*
* @var \Drupal\comment\CommentManagerInterface
*/
protected $commentManager;
/**
* Array of last post information keyed by forum (term) id.
*
* @var array
*/
protected $lastPostData = [];
/**
* Array of forum statistics keyed by forum (term) id.
*
* @var array
*/
protected $forumStatistics = [];
/**
* Array of forum children keyed by parent forum (term) id.
*
* @var array
*/
protected $forumChildren = [];
/**
* Array of history keyed by nid.
*
* @var array
*/
protected $history = [];
/**
* Cached forum index.
*
* @var \Drupal\taxonomy\TermInterface
*/
protected $index;
/**
* Constructs the forum manager service.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Database\Connection $connection
* The current database connection.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The translation manager service.
* @param \Drupal\comment\CommentManagerInterface $comment_manager
* The comment manager service.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
*/
public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, Connection $connection, TranslationInterface $string_translation, CommentManagerInterface $comment_manager, EntityFieldManagerInterface $entity_field_manager) {
$this->configFactory = $config_factory;
$this->entityTypeManager = $entity_type_manager;
$this->connection = $connection;
$this->stringTranslation = $string_translation;
$this->commentManager = $comment_manager;
$this->entityFieldManager = $entity_field_manager;
}
/**
* {@inheritdoc}
*/
public function getTopics($tid, AccountInterface $account) {
$config = $this->configFactory->get('forum.settings');
$forum_per_page = $config->get('topics.page_limit');
$sortby = $config->get('topics.order');
$header = [
['data' => $this->t('Topic'), 'field' => 'f.title'],
['data' => $this->t('Replies'), 'field' => 'f.comment_count'],
['data' => $this->t('Last reply'), 'field' => 'f.last_comment_timestamp'],
];
$order = $this->getTopicOrder($sortby);
for ($i = 0; $i < count($header); $i++) {
if ($header[$i]['field'] == $order['field']) {
$header[$i]['sort'] = $order['sort'];
}
}
$query = $this->connection->select('forum_index', 'f')
->extend(PagerSelectExtender::class)
->extend(TableSortExtender::class);
$query->fields('f');
$query
->condition('f.tid', $tid)
->addTag('node_access')
->addMetaData('base_table', 'forum_index')
->orderBy('f.sticky', 'DESC')
->orderByHeader($header)
->limit($forum_per_page);
$count_query = $this->connection->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 = [];
foreach ($result as $record) {
$nids[] = $record->nid;
}
if ($nids) {
$nodes = $this->entityTypeManager->getStorage('node')->loadMultiple($nids);
$query = $this->connection->select('node_field_data', 'n')
->extend(TableSortExtender::class);
$query->fields('n', ['nid']);
$query->join('comment_entity_statistics', 'ces', "[n].[nid] = [ces].[entity_id] AND [ces].[field_name] = 'comment_forum' AND [ces].[entity_type] = 'node'");
$query->fields('ces', [
'cid',
'last_comment_uid',
'last_comment_timestamp',
'comment_count',
]);
$query->join('forum_index', 'f', '[f].[nid] = [n].[nid]');
$query->addField('f', 'tid', 'forum_tid');
$query->join('users_field_data', 'u', '[n].[uid] = [u].[uid] AND [u].[default_langcode] = 1');
$query->addField('u', 'name');
$query->join('users_field_data', 'u2', '[ces].[last_comment_uid] = [u2].[uid] AND [u].[default_langcode] = 1');
$query->addExpression('CASE [ces].[last_comment_uid] WHEN 0 THEN [ces].[last_comment_name] ELSE [u2].[name] END', 'last_comment_name');
$query
->orderBy('f.sticky', 'DESC')
->orderByHeader($header)
->condition('n.nid', $nids, 'IN')
// @todo This should be actually filtering on the desired node language
// and just fall back to the default language.
->condition('n.default_langcode', 1);
$result = [];
foreach ($query->execute() as $row) {
$topic = $nodes[$row->nid];
$topic->comment_mode = $topic->comment_forum->status;
foreach ($row as $key => $value) {
$topic->{$key} = $value;
}
$result[] = $topic;
}
}
else {
$result = [];
}
$topics = [];
$first_new_found = FALSE;
foreach ($result as $topic) {
if ($account->isAuthenticated()) {
// 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 = $this->lastVisit($topic->id(), $account);
$topic->new_replies = $this->commentManager->getCountNewComments($topic, 'comment_forum', $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->id()] = $topic;
}
return ['topics' => $topics, 'header' => $header];
}
/**
* Gets topic sorting information based on an integer code.
*
* @param int $sortby
* One of the following integers indicating the sort criteria:
* - ForumManager::NEWEST_FIRST: Date - newest first.
* - ForumManager::OLDEST_FIRST: Date - oldest first.
* - ForumManager::MOST_POPULAR_FIRST: Posts with the most comments first.
* - ForumManager::LEAST_POPULAR_FIRST: Posts with the least comments first.
*
* @return array
* An array with the following values:
* - field: A field for an SQL query.
* - sort: 'asc' or 'desc'.
*/
protected function getTopicOrder($sortby) {
switch ($sortby) {
case static::NEWEST_FIRST:
return ['field' => 'f.last_comment_timestamp', 'sort' => 'desc'];
case static::OLDEST_FIRST:
return ['field' => 'f.last_comment_timestamp', 'sort' => 'asc'];
case static::MOST_POPULAR_FIRST:
return ['field' => 'f.comment_count', 'sort' => 'desc'];
case static::LEAST_POPULAR_FIRST:
return ['field' => 'f.comment_count', 'sort' => 'asc'];
}
}
/**
* Gets the last time the user viewed a node.
*
* @param int $nid
* The node ID.
* @param \Drupal\Core\Session\AccountInterface $account
* Account to fetch last time for.
*
* @return int
* The timestamp when the user last viewed this node, if the user has
* previously viewed the node; otherwise HISTORY_READ_LIMIT.
*/
protected function lastVisit($nid, AccountInterface $account) {
if (empty($this->history[$nid])) {
$result = $this->connection->select('history', 'h')
->fields('h', ['nid', 'timestamp'])
->condition('uid', $account->id())
->execute();
foreach ($result as $t) {
$this->history[$t->nid] = $t->timestamp > HISTORY_READ_LIMIT ? $t->timestamp : HISTORY_READ_LIMIT;
}
}
return $this->history[$nid] ?? HISTORY_READ_LIMIT;
}
/**
* Provides the last post information for the given forum tid.
*
* @param int $tid
* The forum tid.
*
* @return object
* The last post for the given forum.
*/
protected function getLastPost($tid) {
if (!empty($this->lastPostData[$tid])) {
return $this->lastPostData[$tid];
}
// Query "Last Post" information for this forum.
$query = $this->connection->select('node_field_data', 'n');
$query->join('forum', 'f', '[n].[vid] = [f].[vid] AND [f].[tid] = :tid', [':tid' => $tid]);
$query->join('comment_entity_statistics', 'ces', "[n].[nid] = [ces].[entity_id] AND [ces].[field_name] = 'comment_forum' AND [ces].[entity_type] = 'node'");
$query->join('users_field_data', 'u', '[ces].[last_comment_uid] = [u].[uid] AND [u].[default_langcode] = 1');
$query->addExpression('CASE [ces].[last_comment_uid] WHEN 0 THEN [ces].[last_comment_name] ELSE [u].[name] END', 'last_comment_name');
$topic = $query
->fields('ces', ['last_comment_timestamp', 'last_comment_uid'])
->condition('n.status', 1)
->orderBy('last_comment_timestamp', 'DESC')
->range(0, 1)
->addTag('node_access')
->execute()
->fetchObject();
// Build 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;
}
$this->lastPostData[$tid] = $last_post;
return $last_post;
}
/**
* Provides statistics for a forum.
*
* @param int $tid
* The forum tid.
*
* @return object|null
* Statistics for the given forum if statistics exist, else NULL.
*/
protected function getForumStatistics($tid) {
if (empty($this->forumStatistics)) {
// Prime the statistics.
$query = $this->connection->select('node_field_data', 'n');
$query->join('comment_entity_statistics', 'ces', "[n].[nid] = [ces].[entity_id] AND [ces].[field_name] = 'comment_forum' AND [ces].[entity_type] = 'node'");
$query->join('forum', 'f', '[n].[vid] = [f].[vid]');
$query->addExpression('COUNT([n].[nid])', 'topic_count');
$query->addExpression('SUM([ces].[comment_count])', 'comment_count');
$this->forumStatistics = $query
->fields('f', ['tid'])
->condition('n.status', 1)
->condition('n.default_langcode', 1)
->groupBy('tid')
->addTag('node_access')
->execute()
->fetchAllAssoc('tid');
}
if (!empty($this->forumStatistics[$tid])) {
return $this->forumStatistics[$tid];
}
}
/**
* {@inheritdoc}
*/
public function getChildren($vid, $tid) {
if (!empty($this->forumChildren[$tid])) {
return $this->forumChildren[$tid];
}
$forums = [];
$_forums = $this->entityTypeManager->getStorage('taxonomy_term')->loadTree($vid, $tid, NULL, TRUE);
foreach ($_forums as $forum) {
if (!$forum->access('view')) {
continue;
}
// Merge in the topic and post counters.
if (($count = $this->getForumStatistics($forum->id()))) {
$forum->num_topics = $count->topic_count;
$forum->num_posts = $count->topic_count + $count->comment_count;
}
else {
$forum->num_topics = 0;
$forum->num_posts = 0;
}
// Merge in last post details.
$forum->last_post = $this->getLastPost($forum->id());
$forums[$forum->id()] = $forum;
}
$this->forumChildren[$tid] = $forums;
return $forums;
}
/**
* {@inheritdoc}
*/
public function getIndex() {
if ($this->index) {
return $this->index;
}
$vid = $this->configFactory->get('forum.settings')->get('vocabulary');
$index = $this->entityTypeManager->getStorage('taxonomy_term')->create([
'tid' => 0,
'container' => 1,
'parents' => [],
'isIndex' => TRUE,
'vid' => $vid,
]);
// Load the tree below.
$index->forums = $this->getChildren($vid, 0);
$this->index = $index;
return $index;
}
/**
* {@inheritdoc}
*/
public function resetCache() {
// Reset the index.
$this->index = NULL;
// Reset history.
$this->history = [];
}
/**
* {@inheritdoc}
*/
public function checkNodeType(NodeInterface $node) {
// Fetch information about the forum field.
$field_definitions = $this->entityFieldManager->getFieldDefinitions('node', $node->bundle());
return !empty($field_definitions['taxonomy_forums']);
}
/**
* {@inheritdoc}
*/
public function unreadTopics($term, $uid) {
$query = $this->connection->select('node_field_data', 'n');
$query->join('forum', 'f', '[n].[vid] = [f].[vid] AND [f].[tid] = :tid', [':tid' => $term]);
$query->leftJoin('history', 'h', '[n].[nid] = [h].[nid] AND [h].[uid] = :uid', [':uid' => $uid]);
$query->addExpression('COUNT([n].[nid])', 'count');
return $query
->condition('status', 1)
// @todo This should be actually filtering on the desired node status
// field language and just fall back to the default language.
->condition('n.default_langcode', 1)
->condition('n.created', HISTORY_READ_LIMIT, '>')
->isNull('h.nid')
->addTag('node_access')
->execute()
->fetchField();
}
/**
* {@inheritdoc}
*/
public function __sleep() {
$vars = $this->defaultSleep();
// Do not serialize static cache.
unset($vars['history'], $vars['index'], $vars['lastPostData'], $vars['forumChildren'], $vars['forumStatistics']);
return $vars;
}
/**
* {@inheritdoc}
*/
public function __wakeup() {
$this->defaultWakeup();
// Initialize static cache.
$this->history = [];
$this->lastPostData = [];
$this->forumChildren = [];
$this->forumStatistics = [];
$this->index = NULL;
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace Drupal\forum;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
/**
* Provides forum manager interface.
*/
interface ForumManagerInterface {
/**
* Gets list of forum topics.
*
* @param int $tid
* Term ID.
* @param \Drupal\Core\Session\AccountInterface $account
* Account to fetch topics for.
*
* @return array
* Array with keys 'topics' and 'header'.
*/
public function getTopics($tid, AccountInterface $account);
/**
* Utility method to fetch the child forums for a given forum.
*
* @param int $vid
* The forum vocabulary ID.
* @param int $tid
* The forum ID to fetch the children for.
*
* @return array
* Array of children.
*/
public function getChildren($vid, $tid);
/**
* Generates and returns the forum index.
*
* The forum index is a pseudo term that provides an overview of all forums.
*
* @return \Drupal\taxonomy\TermInterface
* A pseudo term representing the overview of all forums.
*/
public function getIndex();
/**
* Resets the ForumManager index and history.
*/
public function resetCache();
/**
* Checks whether a node can be used in a forum, based on its content type.
*
* @param \Drupal\node\NodeInterface $node
* A node entity.
*
* @return bool
* Boolean indicating if the node can be assigned to a forum.
*/
public function checkNodeType(NodeInterface $node);
/**
* 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 int $term
* The term ID of the forum.
* @param int $uid
* The user ID.
*
* @return int
* The number of new posts in the forum that have not been read by the user.
*/
public function unreadTopics($term, $uid);
}

View File

@@ -0,0 +1,81 @@
<?php
namespace Drupal\forum;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Configure forum settings for this site.
*
* @internal
*/
class ForumSettingsForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'forum_admin_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['forum.settings'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('forum.settings');
$options = [5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 80, 100, 150, 200, 250, 300, 350, 400, 500];
$form['forum_hot_topic'] = [
'#type' => 'select',
'#title' => $this->t('Hot topic threshold'),
'#default_value' => $config->get('topics.hot_threshold'),
'#options' => array_combine($options, $options),
'#description' => $this->t('The number of replies a topic must have to be considered "hot".'),
];
$options = [10, 25, 50, 75, 100];
$form['forum_per_page'] = [
'#type' => 'select',
'#title' => $this->t('Topics per page'),
'#default_value' => $config->get('topics.page_limit'),
'#options' => array_combine($options, $options),
'#description' => $this->t('Default number of forum topics displayed per page.'),
];
$order = [
1 => $this->t('Date - newest first'),
2 => $this->t('Date - oldest first'),
3 => $this->t('Posts - most active first'),
4 => $this->t('Posts - least active first'),
];
$form['forum_order'] = [
'#type' => 'radios',
'#title' => $this->t('Default order'),
'#default_value' => $config->get('topics.order'),
'#options' => $order,
'#description' => $this->t('Default display order for topics.'),
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config('forum.settings')
->set('topics.hot_threshold', $form_state->getValue('forum_hot_topic'))
->set('topics.page_limit', $form_state->getValue('forum_per_page'))
->set('topics.order', $form_state->getValue('forum_order'))
->save();
parent::submitForm($form, $form_state);
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace Drupal\forum;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleUninstallValidatorInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\taxonomy\VocabularyInterface;
/**
* Prevents forum module from being uninstalled under certain conditions.
*
* These conditions are when any forum nodes exist or there are any terms in the
* forum vocabulary.
*/
class ForumUninstallValidator implements ModuleUninstallValidatorInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* Constructs a new ForumUninstallValidator.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ConfigFactoryInterface $config_factory, TranslationInterface $string_translation) {
$this->entityTypeManager = $entity_type_manager;
$this->configFactory = $config_factory;
$this->stringTranslation = $string_translation;
}
/**
* {@inheritdoc}
*/
public function validate($module) {
$reasons = [];
if ($module == 'forum') {
if ($this->hasForumNodes()) {
$reasons[] = $this->t('To uninstall Forum, first delete all <em>Forum</em> content');
}
$vocabulary = $this->getForumVocabulary();
if (!empty($vocabulary) && $this->hasTermsForVocabulary($vocabulary)) {
if ($vocabulary->access('view')) {
$reasons[] = $this->t('To uninstall Forum, first delete all <a href=":url">%vocabulary</a> terms', [
'%vocabulary' => $vocabulary->label(),
':url' => $vocabulary->toUrl('overview-form')->toString(),
]);
}
else {
$reasons[] = $this->t('To uninstall Forum, first delete all %vocabulary terms', [
'%vocabulary' => $vocabulary->label(),
]);
}
}
}
return $reasons;
}
/**
* Determines if there are any forum nodes or not.
*
* @return bool
* TRUE if there are forum nodes, FALSE otherwise.
*/
protected function hasForumNodes() {
$nodes = $this->entityTypeManager->getStorage('node')->getQuery()
->condition('type', 'forum')
->accessCheck(FALSE)
->range(0, 1)
->execute();
return !empty($nodes);
}
/**
* Determines if there are any taxonomy terms for a specified vocabulary.
*
* @param \Drupal\taxonomy\VocabularyInterface $vocabulary
* The vocabulary to check for terms.
*
* @return bool
* TRUE if there are terms for this vocabulary, FALSE otherwise.
*/
protected function hasTermsForVocabulary(VocabularyInterface $vocabulary) {
$terms = $this->entityTypeManager->getStorage('taxonomy_term')->getQuery()
->condition('vid', $vocabulary->id())
->accessCheck(FALSE)
->range(0, 1)
->execute();
return !empty($terms);
}
/**
* Returns the vocabulary configured for forums.
*
* @return \Drupal\taxonomy\VocabularyInterface
* The vocabulary entity for forums.
*/
protected function getForumVocabulary() {
$vid = $this->configFactory->get('forum.settings')->get('vocabulary');
if (!empty($vid)) {
return $this->entityTypeManager->getStorage('taxonomy_vocabulary')->load($vid);
}
else {
return NULL;
}
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace Drupal\forum\Plugin\Block;
use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Database\Database;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Provides an 'Active forum topics' block.
*/
#[Block(
id: "forum_active_block",
admin_label: new TranslatableMarkup("Active forum topics"),
category: new TranslatableMarkup("Lists (Views)")
)]
class ActiveTopicsBlock extends ForumBlockBase {
/**
* {@inheritdoc}
*/
protected function buildForumQuery() {
return Database::getConnection()->select('forum_index', 'f')
->fields('f')
->addTag('node_access')
->addMetaData('base_table', 'forum_index')
->orderBy('f.last_comment_timestamp', 'DESC')
->range(0, $this->configuration['block_count']);
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace Drupal\forum\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
/**
* Provides a base class for Forum blocks.
*/
abstract class ForumBlockBase extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$result = $this->buildForumQuery()->execute();
$elements = [];
if ($node_title_list = node_title_list($result)) {
$elements['forum_list'] = $node_title_list;
$elements['forum_more'] = [
'#type' => 'more_link',
'#url' => Url::fromRoute('forum.index'),
'#attributes' => ['title' => $this->t('Read the latest forum topics.')],
];
}
return $elements;
}
/**
* Builds the select query to use for this forum block.
*
* @return \Drupal\Core\Database\Query\Select
* A Select object.
*/
abstract protected function buildForumQuery();
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'properties' => [
'administrative' => TRUE,
],
'block_count' => 5,
];
}
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account) {
return AccessResult::allowedIfHasPermission($account, 'access content');
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$range = range(2, 20);
$form['block_count'] = [
'#type' => 'select',
'#title' => $this->t('Number of topics'),
'#default_value' => $this->configuration['block_count'],
'#options' => array_combine($range, $range),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['block_count'] = $form_state->getValue('block_count');
}
/**
* {@inheritdoc}
*/
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), ['user.node_grants:view']);
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
return Cache::mergeTags(parent::getCacheTags(), ['node_list']);
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace Drupal\forum\Plugin\Block;
use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Database\Database;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Provides a 'New forum topics' block.
*/
#[Block(
id: "forum_new_block",
admin_label: new TranslatableMarkup("New forum topics"),
category: new TranslatableMarkup("Lists (Views)")
)]
class NewTopicsBlock extends ForumBlockBase {
/**
* {@inheritdoc}
*/
protected function buildForumQuery() {
return Database::getConnection()->select('forum_index', 'f')
->fields('f')
->addTag('node_access')
->addMetaData('base_table', 'forum_index')
->orderBy('f.created', 'DESC')
->range(0, $this->configuration['block_count']);
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace Drupal\forum\Plugin\Validation\Constraint;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
/**
* Checks that the node is assigned only a "leaf" term in the forum taxonomy.
*/
#[Constraint(
id: 'ForumLeaf',
label: new TranslatableMarkup('Forum leaf', [], ['context' => 'Validation'])
)]
class ForumLeafConstraint extends SymfonyConstraint {
public $selectForum = 'Select a forum.';
public $noLeafMessage = 'The item %forum is a forum container, not a forum. Select one of the forums below instead.';
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Drupal\forum\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the ForumLeaf constraint.
*/
class ForumLeafConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
$item = $items->first();
if (!isset($item)) {
return NULL;
}
// Verify that a term has been selected.
if (!$item->entity) {
$this->context->addViolation($constraint->selectForum);
}
// The forum_container flag must not be set.
if (!empty($item->entity->forum_container->value)) {
$this->context->addViolation($constraint->noLeafMessage, ['%forum' => $item->entity->getName()]);
}
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Drupal\forum\Plugin\migrate\process;
use Drupal\migrate\Attribute\MigrateProcess;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
/**
* Checks if the vocabulary being migrated is the one used for forums.
*
* Drupal 8 Forum is expecting specific machine names for its field and
* vocabulary names. This process plugin forces a given machine name to the
* field or vocabulary that is being migrated.
*
* The 'forum_vocabulary' source property is evaluated in the
* d6_taxonomy_vocabulary or d7_taxonomy_vocabulary source plugins and is set to
* true if the vocabulary vid being migrated is the same as the one in the
* 'forum_nav_vocabulary' variable on the source site.
*
* Example:
*
* @code
* process:
* field_name:
* plugin: forum_vocabulary
* machine_name: taxonomy_forums
* @endcode
*/
#[MigrateProcess('forum_vocabulary')]
class ForumVocabulary extends ProcessPluginBase {
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
if ($row->getSourceProperty('forum_vocabulary') && !empty($this->configuration['machine_name'])) {
$value = $this->configuration['machine_name'];
}
return $value;
}
}

View File

@@ -0,0 +1,88 @@
<?php
// phpcs:ignoreFile
/**
* This file was generated via php core/scripts/generate-proxy-class.php 'Drupal\forum\ForumUninstallValidator' "core/modules/forum/src".
*/
namespace Drupal\forum\ProxyClass {
/**
* Provides a proxy class for \Drupal\forum\ForumUninstallValidator.
*
* @see \Drupal\Component\ProxyBuilder
*/
class ForumUninstallValidator implements \Drupal\Core\Extension\ModuleUninstallValidatorInterface
{
use \Drupal\Core\DependencyInjection\DependencySerializationTrait;
/**
* The id of the original proxied service.
*
* @var string
*/
protected $drupalProxyOriginalServiceId;
/**
* The real proxied service, after it was lazy loaded.
*
* @var \Drupal\forum\ForumUninstallValidator
*/
protected $service;
/**
* The service container.
*
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected $container;
/**
* Constructs a ProxyClass Drupal proxy object.
*
* @param \Symfony\Component\DependencyInjection\ContainerInterface $container
* The container.
* @param string $drupal_proxy_original_service_id
* The service ID of the original service.
*/
public function __construct(\Symfony\Component\DependencyInjection\ContainerInterface $container, $drupal_proxy_original_service_id)
{
$this->container = $container;
$this->drupalProxyOriginalServiceId = $drupal_proxy_original_service_id;
}
/**
* Lazy loads the real service from the container.
*
* @return object
* Returns the constructed real service.
*/
protected function lazyLoadItself()
{
if (!isset($this->service)) {
$this->service = $this->container->get($this->drupalProxyOriginalServiceId);
}
return $this->service;
}
/**
* {@inheritdoc}
*/
public function validate($module)
{
return $this->lazyLoadItself()->validate($module);
}
/**
* {@inheritdoc}
*/
public function setStringTranslation(\Drupal\Core\StringTranslation\TranslationInterface $translation)
{
return $this->lazyLoadItself()->setStringTranslation($translation);
}
}
}