updated core and modules

This commit is contained in:
Bachir Soussi Chiadmi
2017-09-09 16:27:51 +02:00
parent 027aa99b32
commit 41863f872c
7810 changed files with 318922 additions and 83631 deletions
@@ -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');
}
}
@@ -4,8 +4,14 @@ 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.
@@ -15,17 +21,82 @@ use Drupal\Core\Session\AccountInterface;
* admin_label = @Translation("Popular content")
* )
*/
class StatisticsPopularBlock extends BlockBase {
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 array(
return [
'top_day_num' => 0,
'top_all_num' => 0,
'top_last_num' => 0
);
];
}
/**
@@ -40,29 +111,29 @@ class StatisticsPopularBlock extends BlockBase {
*/
public function blockForm($form, FormStateInterface $form_state) {
// Popular content block settings.
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40);
$numbers = array('0' => $this->t('Disabled')) + array_combine($numbers, $numbers);
$form['statistics_block_top_day_num'] = array(
$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'] = array(
];
$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'] = array(
];
$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;
}
@@ -79,31 +150,67 @@ class StatisticsPopularBlock extends BlockBase {
* {@inheritdoc}
*/
public function build() {
$content = array();
$content = [];
if ($this->configuration['top_day_num'] > 0) {
$result = statistics_title_list('daycount', $this->configuration['top_day_num']);
if ($result) {
$content['top_day'] = node_title_list($result, $this->t("Today's:"));
$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) {
$result = statistics_title_list('totalcount', $this->configuration['top_all_num']);
if ($result) {
$content['top_all'] = node_title_list($result, $this->t('All time:'));
$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) {
$result = statistics_title_list('timestamp', $this->configuration['top_last_num']);
$content['top_last'] = node_title_list($result, $this->t('Last viewed:'));
$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(),
],
];
}
}
@@ -21,7 +21,7 @@ class StatisticsSettingsForm extends ConfigFormBase {
protected $moduleHandler;
/**
* Constructs a \Drupal\user\StatisticsSettingsForm object.
* Constructs a \Drupal\statistics\StatisticsSettingsForm object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The factory for configuration objects.
@@ -65,17 +65,17 @@ class StatisticsSettingsForm extends ConfigFormBase {
$config = $this->config('statistics.settings');
// Content counter settings.
$form['content'] = array(
$form['content'] = [
'#type' => 'details',
'#title' => t('Content viewing counter settings'),
'#open' => TRUE,
);
$form['content']['statistics_count_content_views'] = array(
];
$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);
}
@@ -0,0 +1,90 @@
<?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 \Drupal\statistics\StatisticsViewsResult[]
* An array of value objects representing the number of times each entity
* has been viewed. The array is keyed by entity ID. If an ID does not
* exist, it will not be present in the array.
*/
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|false
* If the entity exists, a value object representing the number of times if
* has been viewed. If it does not exist, FALSE is returned.
*/
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;
}
}
@@ -6,6 +6,9 @@ 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 {
@@ -14,7 +17,7 @@ abstract class StatisticsTestBase extends WebTestBase {
*
* @var array
*/
public static $modules = array('node', 'block', 'ban', 'statistics');
public static $modules = ['node', 'block', 'ban', 'statistics'];
/**
* User with permissions to ban IP's.
@@ -28,18 +31,18 @@ abstract class StatisticsTestBase extends WebTestBase {
// Create Basic page node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
}
// Create user.
$this->blockingUser = $this->drupalCreateUser(array(
$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.
@@ -19,7 +19,7 @@ class IntegrationTest extends ViewTestBase {
*
* @var array
*/
public static $modules = array('statistics', 'statistics_test_views', 'node');
public static $modules = ['statistics', 'statistics_test_views', 'node'];
/**
* Stores the user object that accesses the page.
@@ -40,25 +40,24 @@ class IntegrationTest extends ViewTestBase {
*
* @var array
*/
public static $testViews = array('test_statistics_integration');
public static $testViews = ['test_statistics_integration'];
protected function setUp() {
parent::setUp();
ViewTestData::createTestViews(get_class($this), array('statistics_test_views'));
ViewTestData::createTestViews(get_class($this), ['statistics_test_views']);
// Create a new user for viewing nodes and statistics.
$this->webUser = $this->drupalCreateUser(array('access content', 'view post access counter'));
$this->webUser = $this->drupalCreateUser(['access content', 'view post access counter']);
// Create a new user for viewing nodes only.
$this->deniedUser = $this->drupalCreateUser(array('access content'));
$this->deniedUser = $this->drupalCreateUser(['access content']);
$this->drupalCreateContentType(array('type' => 'page'));
$this->node = $this->drupalCreateNode(array('type' => 'page'));
$this->drupalCreateContentType(['type' => 'page']);
$this->node = $this->drupalCreateNode(['type' => 'page']);
// Enable access logging.
// Enable counting of content views.
$this->config('statistics.settings')
->set('access_log.enabled', 1)
->set('count_content_views', 1)
->save();
@@ -75,8 +74,8 @@ class IntegrationTest extends ViewTestBase {
// @see \Drupal\statistics\Tests\StatisticsLoggingTest::testLogging().
global $base_url;
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$client = \Drupal::service('http_client_factory')->fromOptions(['config/curl', array(CURLOPT_TIMEOUT => 10)]);
$client->post($stats_path, array('form_params' => array('nid' => $this->node->id())));
$client = \Drupal::httpClient();
$client->post($stats_path, ['form_params' => ['nid' => $this->node->id()]]);
$this->drupalGet('test_statistics_integration');
$expected = statistics_get($this->node->id());