first commit
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics;
|
||||
|
||||
use Drupal\Core\Database\Connection;
|
||||
use Drupal\Core\State\StateInterface;
|
||||
use Symfony\Component\HttpFoundation\RequestStack;
|
||||
|
||||
/**
|
||||
* Provides the default database storage backend for statistics.
|
||||
*/
|
||||
class NodeStatisticsDatabaseStorage implements StatisticsStorageInterface {
|
||||
|
||||
/**
|
||||
* The database connection used.
|
||||
*
|
||||
* @var \Drupal\Core\Database\Connection
|
||||
*/
|
||||
protected $connection;
|
||||
|
||||
/**
|
||||
* The state service.
|
||||
*
|
||||
* @var \Drupal\Core\State\StateInterface
|
||||
*/
|
||||
protected $state;
|
||||
|
||||
/**
|
||||
* The request stack.
|
||||
*
|
||||
* @var \Symfony\Component\HttpFoundation\RequestStack
|
||||
*/
|
||||
protected $requestStack;
|
||||
|
||||
/**
|
||||
* Constructs the statistics storage.
|
||||
*
|
||||
* @param \Drupal\Core\Database\Connection $connection
|
||||
* The database connection for the node view storage.
|
||||
* @param \Drupal\Core\State\StateInterface $state
|
||||
* The state service.
|
||||
*/
|
||||
public function __construct(Connection $connection, StateInterface $state, RequestStack $request_stack) {
|
||||
$this->connection = $connection;
|
||||
$this->state = $state;
|
||||
$this->requestStack = $request_stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function recordView($id) {
|
||||
return (bool) $this->connection
|
||||
->merge('node_counter')
|
||||
->key('nid', $id)
|
||||
->fields([
|
||||
'daycount' => 1,
|
||||
'totalcount' => 1,
|
||||
'timestamp' => $this->getRequestTime(),
|
||||
])
|
||||
->expression('daycount', 'daycount + 1')
|
||||
->expression('totalcount', 'totalcount + 1')
|
||||
->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function fetchViews($ids) {
|
||||
$views = $this->connection
|
||||
->select('node_counter', 'nc')
|
||||
->fields('nc', ['totalcount', 'daycount', 'timestamp'])
|
||||
->condition('nid', $ids, 'IN')
|
||||
->execute()
|
||||
->fetchAll();
|
||||
foreach ($views as $id => $view) {
|
||||
$views[$id] = new StatisticsViewsResult($view->totalcount, $view->daycount, $view->timestamp);
|
||||
}
|
||||
return $views;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function fetchView($id) {
|
||||
$views = $this->fetchViews([$id]);
|
||||
return reset($views);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function fetchAll($order = 'totalcount', $limit = 5) {
|
||||
assert(in_array($order, ['totalcount', 'daycount', 'timestamp']), "Invalid order argument.");
|
||||
|
||||
return $this->connection
|
||||
->select('node_counter', 'nc')
|
||||
->fields('nc', ['nid'])
|
||||
->orderBy($order, 'DESC')
|
||||
->range(0, $limit)
|
||||
->execute()
|
||||
->fetchCol();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function deleteViews($id) {
|
||||
return (bool) $this->connection
|
||||
->delete('node_counter')
|
||||
->condition('nid', $id)
|
||||
->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function resetDayCount() {
|
||||
$statistics_timestamp = $this->state->get('statistics.day_timestamp') ?: 0;
|
||||
if (($this->getRequestTime() - $statistics_timestamp) >= 86400) {
|
||||
$this->state->set('statistics.day_timestamp', $this->getRequestTime());
|
||||
$this->connection->update('node_counter')
|
||||
->fields(['daycount' => 0])
|
||||
->execute();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function maxTotalCount() {
|
||||
$query = $this->connection->select('node_counter', 'nc');
|
||||
$query->addExpression('MAX(totalcount)');
|
||||
$max_total_count = (int)$query->execute()->fetchField();
|
||||
return $max_total_count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current request time.
|
||||
*
|
||||
* @return int
|
||||
* Unix timestamp for current server request time.
|
||||
*/
|
||||
protected function getRequestTime() {
|
||||
return $this->requestStack->getCurrentRequest()->server->get('REQUEST_TIME');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics\Plugin\Block;
|
||||
|
||||
use Drupal\Core\Access\AccessResult;
|
||||
use Drupal\Core\Block\BlockBase;
|
||||
use Drupal\Core\Entity\EntityRepositoryInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Render\RendererInterface;
|
||||
use Drupal\Core\Session\AccountInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
|
||||
use Drupal\statistics\StatisticsStorageInterface;
|
||||
|
||||
/**
|
||||
* Provides a 'Popular content' block.
|
||||
*
|
||||
* @Block(
|
||||
* id = "statistics_popular_block",
|
||||
* admin_label = @Translation("Popular content")
|
||||
* )
|
||||
*/
|
||||
class StatisticsPopularBlock extends BlockBase implements ContainerFactoryPluginInterface {
|
||||
|
||||
/**
|
||||
* The entity type manager.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
|
||||
*/
|
||||
protected $entityTypeManager;
|
||||
|
||||
/**
|
||||
* The entity repository service.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityRepositoryInterface
|
||||
*/
|
||||
protected $entityRepository;
|
||||
|
||||
/**
|
||||
* The storage for statistics.
|
||||
*
|
||||
* @var \Drupal\statistics\StatisticsStorageInterface
|
||||
*/
|
||||
protected $statisticsStorage;
|
||||
|
||||
/**
|
||||
* @var \Drupal\Core\Render\RendererInterface
|
||||
*/
|
||||
protected $renderer;
|
||||
|
||||
/**
|
||||
* Constructs an StatisticsPopularBlock object.
|
||||
*
|
||||
* @param array $configuration
|
||||
* A configuration array containing information about the plugin instance.
|
||||
* @param string $plugin_id
|
||||
* The plugin_id for the plugin instance.
|
||||
* @param mixed $plugin_definition
|
||||
* The plugin implementation definition.
|
||||
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
|
||||
* The entity type manager.
|
||||
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
|
||||
* The entity repository service
|
||||
* @param \Drupal\statistics\StatisticsStorageInterface $statistics_storage
|
||||
* The storage for statistics.
|
||||
*/
|
||||
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityRepositoryInterface $entity_repository, StatisticsStorageInterface $statistics_storage, RendererInterface $renderer) {
|
||||
parent::__construct($configuration, $plugin_id, $plugin_definition);
|
||||
$this->entityTypeManager = $entity_type_manager;
|
||||
$this->entityRepository = $entity_repository;
|
||||
$this->statisticsStorage = $statistics_storage;
|
||||
$this->renderer = $renderer;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
|
||||
return new static(
|
||||
$configuration,
|
||||
$plugin_id,
|
||||
$plugin_definition,
|
||||
$container->get('entity_type.manager'),
|
||||
$container->get('entity.repository'),
|
||||
$container->get('statistics.storage.node'),
|
||||
$container->get('renderer')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function defaultConfiguration() {
|
||||
return [
|
||||
'top_day_num' => 0,
|
||||
'top_all_num' => 0,
|
||||
'top_last_num' => 0
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function blockAccess(AccountInterface $account) {
|
||||
return AccessResult::allowedIfHasPermission($account, 'access content');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function blockForm($form, FormStateInterface $form_state) {
|
||||
// Popular content block settings.
|
||||
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40];
|
||||
$numbers = ['0' => $this->t('Disabled')] + array_combine($numbers, $numbers);
|
||||
$form['statistics_block_top_day_num'] = [
|
||||
'#type' => 'select',
|
||||
'#title' => $this->t("Number of day's top views to display"),
|
||||
'#default_value' => $this->configuration['top_day_num'],
|
||||
'#options' => $numbers,
|
||||
'#description' => $this->t('How many content items to display in "day" list.'),
|
||||
];
|
||||
$form['statistics_block_top_all_num'] = [
|
||||
'#type' => 'select',
|
||||
'#title' => $this->t('Number of all time views to display'),
|
||||
'#default_value' => $this->configuration['top_all_num'],
|
||||
'#options' => $numbers,
|
||||
'#description' => $this->t('How many content items to display in "all time" list.'),
|
||||
];
|
||||
$form['statistics_block_top_last_num'] = [
|
||||
'#type' => 'select',
|
||||
'#title' => $this->t('Number of most recent views to display'),
|
||||
'#default_value' => $this->configuration['top_last_num'],
|
||||
'#options' => $numbers,
|
||||
'#description' => $this->t('How many content items to display in "recently viewed" list.'),
|
||||
];
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function blockSubmit($form, FormStateInterface $form_state) {
|
||||
$this->configuration['top_day_num'] = $form_state->getValue('statistics_block_top_day_num');
|
||||
$this->configuration['top_all_num'] = $form_state->getValue('statistics_block_top_all_num');
|
||||
$this->configuration['top_last_num'] = $form_state->getValue('statistics_block_top_last_num');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function build() {
|
||||
$content = [];
|
||||
|
||||
if ($this->configuration['top_day_num'] > 0) {
|
||||
$nids = $this->statisticsStorage->fetchAll('daycount', $this->configuration['top_day_num']);
|
||||
if ($nids) {
|
||||
$content['top_day'] = $this->nodeTitleList($nids, $this->t("Today's:"));
|
||||
$content['top_day']['#suffix'] = '<br />';
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->configuration['top_all_num'] > 0) {
|
||||
$nids = $this->statisticsStorage->fetchAll('totalcount', $this->configuration['top_all_num']);
|
||||
if ($nids) {
|
||||
$content['top_all'] = $this->nodeTitleList($nids, $this->t('All time:'));
|
||||
$content['top_all']['#suffix'] = '<br />';
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->configuration['top_last_num'] > 0) {
|
||||
$nids = $this->statisticsStorage->fetchAll('timestamp', $this->configuration['top_last_num']);
|
||||
$content['top_last'] = $this->nodeTitleList($nids, $this->t('Last viewed:'));
|
||||
$content['top_last']['#suffix'] = '<br />';
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the ordered array of node links for build().
|
||||
*
|
||||
* @param int[] $nids
|
||||
* An ordered array of node ids.
|
||||
* @param string $title
|
||||
* The title for the list.
|
||||
*
|
||||
* @return array
|
||||
* A render array for the list.
|
||||
*/
|
||||
protected function nodeTitleList(array $nids, $title) {
|
||||
$nodes = $this->entityTypeManager->getStorage('node')->loadMultiple($nids);
|
||||
|
||||
$items = [];
|
||||
foreach ($nids as $nid) {
|
||||
$node = $this->entityRepository->getTranslationFromContext($nodes[$nid]);
|
||||
$item = [
|
||||
'#type' => 'link',
|
||||
'#title' => $node->getTitle(),
|
||||
'#url' => $node->urlInfo('canonical'),
|
||||
];
|
||||
$this->renderer->addCacheableDependency($item, $node);
|
||||
$items[] = $item;
|
||||
}
|
||||
|
||||
return [
|
||||
'#theme' => 'item_list__node',
|
||||
'#items' => $items,
|
||||
'#title' => $title,
|
||||
'#cache' => [
|
||||
'tags' => $this->entityTypeManager->getDefinition('node')->getListCacheTags(),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics\Plugin\views\field;
|
||||
|
||||
use Drupal\views\Plugin\views\field\Date;
|
||||
use Drupal\Core\Session\AccountInterface;
|
||||
|
||||
/**
|
||||
* Field handler to display the most recent time the node has been viewed.
|
||||
*
|
||||
* @ingroup views_field_handlers
|
||||
*
|
||||
* @ViewsField("node_counter_timestamp")
|
||||
*/
|
||||
class NodeCounterTimestamp extends Date {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function access(AccountInterface $account) {
|
||||
return $account->hasPermission('view post access counter');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics\Plugin\views\field;
|
||||
|
||||
use Drupal\views\Plugin\views\field\NumericField;
|
||||
use Drupal\Core\Session\AccountInterface;
|
||||
|
||||
/**
|
||||
* Field handler to display numeric values from the statistics module.
|
||||
*
|
||||
* @ingroup views_field_handlers
|
||||
*
|
||||
* @ViewsField("statistics_numeric")
|
||||
*/
|
||||
class StatisticsNumeric extends NumericField {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function access(AccountInterface $account) {
|
||||
return $account->hasPermission('view post access counter');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics;
|
||||
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Configure statistics settings for this site.
|
||||
*/
|
||||
class StatisticsSettingsForm extends ConfigFormBase {
|
||||
|
||||
/**
|
||||
* The module handler.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* Constructs a \Drupal\user\StatisticsSettingsForm object.
|
||||
*
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The factory for configuration objects.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler.
|
||||
*/
|
||||
public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler) {
|
||||
parent::__construct($config_factory);
|
||||
|
||||
$this->moduleHandler = $module_handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('config.factory'),
|
||||
$container->get('module_handler')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'statistics_settings_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getEditableConfigNames() {
|
||||
return ['statistics.settings'];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$config = $this->config('statistics.settings');
|
||||
|
||||
// Content counter settings.
|
||||
$form['content'] = [
|
||||
'#type' => 'details',
|
||||
'#title' => t('Content viewing counter settings'),
|
||||
'#open' => TRUE,
|
||||
];
|
||||
$form['content']['statistics_count_content_views'] = [
|
||||
'#type' => 'checkbox',
|
||||
'#title' => t('Count content views'),
|
||||
'#default_value' => $config->get('count_content_views'),
|
||||
'#description' => t('Increment a counter each time content is viewed.'),
|
||||
];
|
||||
|
||||
return parent::buildForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$this->config('statistics.settings')
|
||||
->set('count_content_views', $form_state->getValue('statistics_count_content_views'))
|
||||
->save();
|
||||
|
||||
// The popular statistics block is dependent on these settings, so clear the
|
||||
// block plugin definitions cache.
|
||||
if ($this->moduleHandler->moduleExists('block')) {
|
||||
\Drupal::service('plugin.manager.block')->clearCachedDefinitions();
|
||||
}
|
||||
|
||||
parent::submitForm($form, $form_state);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics;
|
||||
|
||||
/**
|
||||
* Provides an interface defining Statistics Storage.
|
||||
*
|
||||
* Stores the views per day, total views and timestamp of last view
|
||||
* for entities.
|
||||
*/
|
||||
interface StatisticsStorageInterface {
|
||||
|
||||
/**
|
||||
* Count a entity view.
|
||||
*
|
||||
* @param int $id
|
||||
* The ID of the entity to count.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if the entity view has been counted.
|
||||
*/
|
||||
public function recordView($id);
|
||||
|
||||
/**
|
||||
* Returns the number of times entities have been viewed.
|
||||
*
|
||||
* @param array $ids
|
||||
* An array of IDs of entities to fetch the views for.
|
||||
*
|
||||
* @return array \Drupal\statistics\StatisticsViewsResult
|
||||
*/
|
||||
public function fetchViews($ids);
|
||||
|
||||
/**
|
||||
* Returns the number of times a single entity has been viewed.
|
||||
*
|
||||
* @param int $id
|
||||
* The ID of the entity to fetch the views for.
|
||||
*
|
||||
* @return \Drupal\statistics\StatisticsViewsResult
|
||||
*/
|
||||
public function fetchView($id);
|
||||
|
||||
/**
|
||||
* Returns the number of times a entity has been viewed.
|
||||
*
|
||||
* @param string $order
|
||||
* The counter name to order by:
|
||||
* - 'totalcount' The total number of views.
|
||||
* - 'daycount' The number of views today.
|
||||
* - 'timestamp' The unix timestamp of the last view.
|
||||
*
|
||||
* @param int $limit
|
||||
* The number of entity IDs to return.
|
||||
*
|
||||
* @return array
|
||||
* An ordered array of entity IDs.
|
||||
*/
|
||||
public function fetchAll($order = 'totalcount', $limit = 5);
|
||||
|
||||
/**
|
||||
* Delete counts for a specific entity.
|
||||
*
|
||||
* @param int $id
|
||||
* The ID of the entity which views to delete.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if the entity views have been deleted.
|
||||
*/
|
||||
public function deleteViews($id);
|
||||
|
||||
/**
|
||||
* Reset the day counter for all entities once every day.
|
||||
*/
|
||||
public function resetDayCount();
|
||||
|
||||
/**
|
||||
* Returns the highest 'totalcount' value.
|
||||
*
|
||||
* @return int
|
||||
* The highest 'totalcount' value.
|
||||
*/
|
||||
public function maxTotalCount();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics;
|
||||
|
||||
/**
|
||||
* Value object for passing statistic results.
|
||||
*/
|
||||
class StatisticsViewsResult {
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $totalCount;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $dayCount;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $timestamp;
|
||||
|
||||
public function __construct($total_count, $day_count, $timestamp) {
|
||||
$this->totalCount = $total_count;
|
||||
$this->dayCount = $day_count;
|
||||
$this->timestamp = $timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Total number of times the entity has been viewed.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getTotalCount() {
|
||||
return $this->totalCount;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Total number of times the entity has been viewed "today".
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getDayCount() {
|
||||
return $this->dayCount;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Timestamp of when the entity was last viewed.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getTimestamp() {
|
||||
return $this->timestamp;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests the statistics admin.
|
||||
*
|
||||
* @group statistics
|
||||
*/
|
||||
class StatisticsAdminTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['node', 'statistics'];
|
||||
|
||||
/**
|
||||
* A user that has permission to administer statistics.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $privilegedUser;
|
||||
|
||||
/**
|
||||
* A page node for which to check content statistics.
|
||||
*
|
||||
* @var \Drupal\node\NodeInterface
|
||||
*/
|
||||
protected $testNode;
|
||||
|
||||
/**
|
||||
* The Guzzle HTTP client.
|
||||
*
|
||||
* @var \GuzzleHttp\Client;
|
||||
*/
|
||||
protected $client;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Set the max age to 0 to simplify testing.
|
||||
$this->config('statistics.settings')->set('display_max_age', 0)->save();
|
||||
|
||||
// Create Basic page node type.
|
||||
if ($this->profile != 'standard') {
|
||||
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
|
||||
}
|
||||
$this->privilegedUser = $this->drupalCreateUser(['administer statistics', 'view post access counter', 'create page content']);
|
||||
$this->drupalLogin($this->privilegedUser);
|
||||
$this->testNode = $this->drupalCreateNode(['type' => 'page', 'uid' => $this->privilegedUser->id()]);
|
||||
$this->client = \Drupal::httpClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies that the statistics settings page works.
|
||||
*/
|
||||
public function testStatisticsSettings() {
|
||||
$config = $this->config('statistics.settings');
|
||||
$this->assertFalse($config->get('count_content_views'), 'Count content view log is disabled by default.');
|
||||
|
||||
// Enable counter on content view.
|
||||
$edit['statistics_count_content_views'] = 1;
|
||||
$this->drupalPostForm('admin/config/system/statistics', $edit, t('Save configuration'));
|
||||
$config = $this->config('statistics.settings');
|
||||
$this->assertTrue($config->get('count_content_views'), 'Count content view log is enabled.');
|
||||
|
||||
// Hit the node.
|
||||
$this->drupalGet('node/' . $this->testNode->id());
|
||||
// Manually calling statistics.php, simulating ajax behavior.
|
||||
$nid = $this->testNode->id();
|
||||
$post = ['nid' => $nid];
|
||||
global $base_url;
|
||||
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
|
||||
$this->client->post($stats_path, ['form_params' => $post]);
|
||||
|
||||
// Hit the node again (the counter is incremented after the hit, so
|
||||
// "1 view" will actually be shown when the node is hit the second time).
|
||||
$this->drupalGet('node/' . $this->testNode->id());
|
||||
$this->client->post($stats_path, ['form_params' => $post]);
|
||||
$this->assertText('1 view', 'Node is viewed once.');
|
||||
|
||||
$this->drupalGet('node/' . $this->testNode->id());
|
||||
$this->client->post($stats_path, ['form_params' => $post]);
|
||||
$this->assertText('2 views', 'Node is viewed 2 times.');
|
||||
|
||||
// Increase the max age to test that nodes are no longer immediately
|
||||
// updated, visit the node once more to populate the cache.
|
||||
$this->config('statistics.settings')->set('display_max_age', 3600)->save();
|
||||
$this->drupalGet('node/' . $this->testNode->id());
|
||||
$this->assertText('3 views', 'Node is viewed 3 times.');
|
||||
|
||||
$this->client->post($stats_path, ['form_params' => $post]);
|
||||
$this->drupalGet('node/' . $this->testNode->id());
|
||||
$this->assertText('3 views', 'Views counter was not updated.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that when a node is deleted, the node counter is deleted too.
|
||||
*/
|
||||
public function testDeleteNode() {
|
||||
$this->config('statistics.settings')->set('count_content_views', 1)->save();
|
||||
|
||||
$this->drupalGet('node/' . $this->testNode->id());
|
||||
// Manually calling statistics.php, simulating ajax behavior.
|
||||
$nid = $this->testNode->id();
|
||||
$post = ['nid' => $nid];
|
||||
global $base_url;
|
||||
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
|
||||
$this->client->post($stats_path, ['form_params' => $post]);
|
||||
|
||||
$result = db_select('node_counter', 'n')
|
||||
->fields('n', ['nid'])
|
||||
->condition('n.nid', $this->testNode->id())
|
||||
->execute()
|
||||
->fetchAssoc();
|
||||
$this->assertEqual($result['nid'], $this->testNode->id(), 'Verifying that the node counter is incremented.');
|
||||
|
||||
$this->testNode->delete();
|
||||
|
||||
$result = db_select('node_counter', 'n')
|
||||
->fields('n', ['nid'])
|
||||
->condition('n.nid', $this->testNode->id())
|
||||
->execute()
|
||||
->fetchAssoc();
|
||||
$this->assertFalse($result, 'Verifying that the node counter is deleted.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that cron clears day counts and expired access logs.
|
||||
*/
|
||||
public function testExpiredLogs() {
|
||||
$this->config('statistics.settings')
|
||||
->set('count_content_views', 1)
|
||||
->save();
|
||||
\Drupal::state()->set('statistics.day_timestamp', 8640000);
|
||||
|
||||
$this->drupalGet('node/' . $this->testNode->id());
|
||||
// Manually calling statistics.php, simulating ajax behavior.
|
||||
$nid = $this->testNode->id();
|
||||
$post = ['nid' => $nid];
|
||||
global $base_url;
|
||||
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
|
||||
$this->client->post($stats_path, ['form_params' => $post]);
|
||||
$this->drupalGet('node/' . $this->testNode->id());
|
||||
$this->client->post($stats_path, ['form_params' => $post]);
|
||||
$this->assertText('1 view', 'Node is viewed once.');
|
||||
|
||||
// statistics_cron() will subtract
|
||||
// statistics.settings:accesslog.max_lifetime config from REQUEST_TIME in
|
||||
// the delete query, so wait two secs here to make sure the access log will
|
||||
// be flushed for the node just hit.
|
||||
sleep(2);
|
||||
$this->cronRun();
|
||||
|
||||
$this->drupalGet('admin/reports/pages');
|
||||
$this->assertNoText('node/' . $this->testNode->id(), 'No hit URL found.');
|
||||
|
||||
$result = db_select('node_counter', 'nc')
|
||||
->fields('nc', ['daycount'])
|
||||
->condition('nid', $this->testNode->id(), '=')
|
||||
->execute()
|
||||
->fetchField();
|
||||
$this->assertFalse($result, 'Daycounter is zero.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests request logging for cached and uncached pages.
|
||||
*
|
||||
* We subclass WebTestBase rather than StatisticsTestBase, because we
|
||||
* want to test requests from an anonymous user.
|
||||
*
|
||||
* @group statistics
|
||||
*/
|
||||
class StatisticsLoggingTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['node', 'statistics', 'block', 'locale'];
|
||||
|
||||
/**
|
||||
* User with permissions to create and edit pages.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $authUser;
|
||||
|
||||
/**
|
||||
* Associative array representing a hypothetical Drupal language.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $language;
|
||||
|
||||
/**
|
||||
* The Guzzle HTTP client.
|
||||
*
|
||||
* @var \GuzzleHttp\Client;
|
||||
*/
|
||||
protected $client;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Create Basic page node type.
|
||||
if ($this->profile != 'standard') {
|
||||
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
|
||||
}
|
||||
|
||||
$this->authUser = $this->drupalCreateUser([
|
||||
// For node creation.
|
||||
'access content',
|
||||
'create page content',
|
||||
'edit own page content',
|
||||
// For language negotiation administration.
|
||||
'administer languages',
|
||||
'access administration pages',
|
||||
]);
|
||||
|
||||
// Ensure we have a node page to access.
|
||||
$this->node = $this->drupalCreateNode(['title' => $this->randomMachineName(255), 'uid' => $this->authUser->id()]);
|
||||
|
||||
// Add a custom language and enable path-based language negotiation.
|
||||
$this->drupalLogin($this->authUser);
|
||||
$this->language = [
|
||||
'predefined_langcode' => 'custom',
|
||||
'langcode' => 'xx',
|
||||
'label' => $this->randomMachineName(16),
|
||||
'direction' => 'ltr',
|
||||
];
|
||||
$this->drupalPostForm('admin/config/regional/language/add', $this->language, t('Add custom language'));
|
||||
$this->drupalPostForm('admin/config/regional/language/detection', ['language_interface[enabled][language-url]' => 1], t('Save settings'));
|
||||
$this->drupalLogout();
|
||||
|
||||
// Enable access logging.
|
||||
$this->config('statistics.settings')
|
||||
->set('count_content_views', 1)
|
||||
->save();
|
||||
|
||||
// Clear the logs.
|
||||
db_truncate('node_counter');
|
||||
$this->client = \Drupal::httpClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies node hit counter logging and script placement.
|
||||
*/
|
||||
public function testLogging() {
|
||||
$path = 'node/' . $this->node->id();
|
||||
$module_path = drupal_get_path('module', 'statistics');
|
||||
$stats_path = base_path() . $module_path . '/statistics.php';
|
||||
$lib_path = base_path() . $module_path . '/statistics.js';
|
||||
$expected_library = '/<script src=".*?' . preg_quote($lib_path, '/.') . '.*?">/is';
|
||||
|
||||
// Verify that logging scripts are not found on a non-node page.
|
||||
$this->drupalGet('node');
|
||||
$settings = $this->getDrupalSettings();
|
||||
$this->assertNoPattern($expected_library, 'Statistics library JS not found on node page.');
|
||||
$this->assertFalse(isset($settings['statistics']), 'Statistics settings not found on node page.');
|
||||
|
||||
// Verify that logging scripts are not found on a non-existent node page.
|
||||
$this->drupalGet('node/9999');
|
||||
$settings = $this->getDrupalSettings();
|
||||
$this->assertNoPattern($expected_library, 'Statistics library JS not found on non-existent node page.');
|
||||
$this->assertFalse(isset($settings['statistics']), 'Statistics settings not found on node page.');
|
||||
|
||||
// Verify that logging scripts are found on a valid node page.
|
||||
$this->drupalGet($path);
|
||||
$settings = $this->getDrupalSettings();
|
||||
$this->assertPattern($expected_library, 'Found statistics library JS on node page.');
|
||||
$this->assertIdentical($this->node->id(), $settings['statistics']['data']['nid'], 'Found statistics settings on node page.');
|
||||
|
||||
// Verify the same when loading the site in a non-default language.
|
||||
$this->drupalGet($this->language['langcode'] . '/' . $path);
|
||||
$settings = $this->getDrupalSettings();
|
||||
$this->assertPattern($expected_library, 'Found statistics library JS on a valid node page in a non-default language.');
|
||||
$this->assertIdentical($this->node->id(), $settings['statistics']['data']['nid'], 'Found statistics settings on valid node page in a non-default language.');
|
||||
|
||||
// Manually call statistics.php to simulate ajax data collection behavior.
|
||||
global $base_root;
|
||||
$post = ['nid' => $this->node->id()];
|
||||
$this->client->post($base_root . $stats_path, ['form_params' => $post]);
|
||||
$node_counter = statistics_get($this->node->id());
|
||||
$this->assertIdentical($node_counter['totalcount'], '1');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics\Tests;
|
||||
|
||||
use Drupal\Core\Cache\Cache;
|
||||
use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
|
||||
|
||||
/**
|
||||
* Tests display of statistics report blocks.
|
||||
*
|
||||
* @group statistics
|
||||
*/
|
||||
class StatisticsReportsTest extends StatisticsTestBase {
|
||||
|
||||
use AssertPageCacheContextsAndTagsTrait;
|
||||
|
||||
/**
|
||||
* Tests the "popular content" block.
|
||||
*/
|
||||
public function testPopularContentBlock() {
|
||||
// Clear the block cache to load the Statistics module's block definitions.
|
||||
$this->container->get('plugin.manager.block')->clearCachedDefinitions();
|
||||
|
||||
// Visit a node to have something show up in the block.
|
||||
$node = $this->drupalCreateNode(['type' => 'page', 'uid' => $this->blockingUser->id()]);
|
||||
$this->drupalGet('node/' . $node->id());
|
||||
// Manually calling statistics.php, simulating ajax behavior.
|
||||
$nid = $node->id();
|
||||
$post = http_build_query(['nid' => $nid]);
|
||||
$headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
|
||||
global $base_url;
|
||||
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
|
||||
$client = \Drupal::httpClient();
|
||||
$client->post($stats_path, ['headers' => $headers, 'body' => $post]);
|
||||
|
||||
// Configure and save the block.
|
||||
$block = $this->drupalPlaceBlock('statistics_popular_block', [
|
||||
'label' => 'Popular content',
|
||||
'top_day_num' => 3,
|
||||
'top_all_num' => 3,
|
||||
'top_last_num' => 3,
|
||||
]);
|
||||
|
||||
// Get some page and check if the block is displayed.
|
||||
$this->drupalGet('user');
|
||||
$this->assertText('Popular content', 'Found the popular content block.');
|
||||
$this->assertText("Today's", "Found today's popular content.");
|
||||
$this->assertText('All time', 'Found the all time popular content.');
|
||||
$this->assertText('Last viewed', 'Found the last viewed popular content.');
|
||||
|
||||
$tags = Cache::mergeTags($node->getCacheTags(), $block->getCacheTags());
|
||||
$tags = Cache::mergeTags($tags, $this->blockingUser->getCacheTags());
|
||||
$tags = Cache::mergeTags($tags, ['block_view', 'config:block_list', 'node_list', 'rendered', 'user_view']);
|
||||
$this->assertCacheTags($tags);
|
||||
$contexts = Cache::mergeContexts($node->getCacheContexts(), $block->getCacheContexts());
|
||||
$contexts = Cache::mergeContexts($contexts, ['url.query_args:_wrapper_format']);
|
||||
$this->assertCacheContexts($contexts);
|
||||
|
||||
// Check if the node link is displayed.
|
||||
$this->assertRaw(\Drupal::l($node->label(), $node->urlInfo('canonical')), 'Found link to visited node.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Defines a base class for testing the Statistics module.
|
||||
*
|
||||
* @deprecated Scheduled for removal in Drupal 9.0.0.
|
||||
* Use \Drupal\Tests\statistics\Functional\StatisticsTestBase instead.
|
||||
*/
|
||||
abstract class StatisticsTestBase extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['node', 'block', 'ban', 'statistics'];
|
||||
|
||||
/**
|
||||
* User with permissions to ban IP's.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $blockingUser;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
// Create Basic page node type.
|
||||
if ($this->profile != 'standard') {
|
||||
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
|
||||
}
|
||||
|
||||
// Create user.
|
||||
$this->blockingUser = $this->drupalCreateUser([
|
||||
'access administration pages',
|
||||
'access site reports',
|
||||
'ban IP addresses',
|
||||
'administer blocks',
|
||||
'administer statistics',
|
||||
'administer users',
|
||||
]);
|
||||
$this->drupalLogin($this->blockingUser);
|
||||
|
||||
// Enable logging.
|
||||
$this->config('statistics.settings')
|
||||
->set('count_content_views', 1)
|
||||
->save();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\statistics\Tests\Views;
|
||||
|
||||
use Drupal\views\Tests\ViewTestBase;
|
||||
use Drupal\views\Tests\ViewTestData;
|
||||
|
||||
/**
|
||||
* Tests basic integration of views data from the statistics module.
|
||||
*
|
||||
* @group statistics
|
||||
* @see
|
||||
*/
|
||||
class IntegrationTest extends ViewTestBase {
|
||||
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['statistics', 'statistics_test_views', 'node'];
|
||||
|
||||
/**
|
||||
* Stores the user object that accesses the page.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $webUser;
|
||||
|
||||
/**
|
||||
* Stores the node object which is used by the test.
|
||||
*
|
||||
* @var \Drupal\node\Entity\Node
|
||||
*/
|
||||
protected $node;
|
||||
|
||||
/**
|
||||
* Views used by this test.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $testViews = ['test_statistics_integration'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
ViewTestData::createTestViews(get_class($this), ['statistics_test_views']);
|
||||
|
||||
// Create a new user for viewing nodes and statistics.
|
||||
$this->webUser = $this->drupalCreateUser(['access content', 'view post access counter']);
|
||||
|
||||
// Create a new user for viewing nodes only.
|
||||
$this->deniedUser = $this->drupalCreateUser(['access content']);
|
||||
|
||||
$this->drupalCreateContentType(['type' => 'page']);
|
||||
$this->node = $this->drupalCreateNode(['type' => 'page']);
|
||||
|
||||
// Enable counting of content views.
|
||||
$this->config('statistics.settings')
|
||||
->set('count_content_views', 1)
|
||||
->save();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the integration of the {node_counter} table in views.
|
||||
*/
|
||||
public function testNodeCounterIntegration() {
|
||||
$this->drupalLogin($this->webUser);
|
||||
|
||||
$this->drupalGet('node/' . $this->node->id());
|
||||
// Manually calling statistics.php, simulating ajax behavior.
|
||||
// @see \Drupal\statistics\Tests\StatisticsLoggingTest::testLogging().
|
||||
global $base_url;
|
||||
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
|
||||
$client = \Drupal::httpClient();
|
||||
$client->post($stats_path, ['form_params' => ['nid' => $this->node->id()]]);
|
||||
$this->drupalGet('test_statistics_integration');
|
||||
|
||||
$expected = statistics_get($this->node->id());
|
||||
// Convert the timestamp to year, to match the expected output of the date
|
||||
// handler.
|
||||
$expected['timestamp'] = date('Y', $expected['timestamp']);
|
||||
|
||||
foreach ($expected as $field => $value) {
|
||||
$xpath = "//div[contains(@class, views-field-$field)]/span[@class = 'field-content']";
|
||||
$this->assertFieldByXpath($xpath, $value, "The $field output matches the expected.");
|
||||
}
|
||||
|
||||
$this->drupalLogout();
|
||||
$this->drupalLogin($this->deniedUser);
|
||||
$this->drupalGet('test_statistics_integration');
|
||||
$this->assertResponse(200);
|
||||
|
||||
foreach ($expected as $field => $value) {
|
||||
$xpath = "//div[contains(@class, views-field-$field)]/span[@class = 'field-content']";
|
||||
$this->assertNoFieldByXpath($xpath, $value, "The $field output is not displayed.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user