View source
<?php
namespace Drupal\mailing_list\Entity;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\mailing_list\SubscriptionInterface;
use Drupal\user\UserInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Url;
class Subscription extends ContentEntityBase implements SubscriptionInterface {
use EntityChangedTrait;
public function getList() {
return $this
->entityTypeManager()
->getStorage('mailing_list')
->load($this
->getListId());
}
public function getListId() {
return $this
->bundle();
}
public function getTitle() {
return $this
->get('title')->value;
}
public function setTitle($title) {
$this
->set('title', $title);
return $this;
}
public function getCreatedTime() {
return $this
->get('created')->value;
}
public function setCreatedTime($timestamp) {
$this
->set('created', $timestamp);
return $this;
}
public function getOwner() {
return $this
->get('uid')->entity;
}
public function setOwner(UserInterface $account) {
$this
->set('uid', $account
->id());
return $this;
}
public function getOwnerId() {
return $this
->get('uid')->target_id;
}
public function setOwnerId($uid) {
$this
->set('uid', $uid);
return $this;
}
public function isActive() {
return (bool) $this
->getEntityKey('status');
}
public function setStatus($status) {
$this
->set('status', $status ? SubscriptionInterface::ACTIVE : SubscriptionInterface::INACTIVE);
return $this;
}
public function getEmail($obfuscate = FALSE) {
$email = $this
->get('email')->value;
if ($obfuscate) {
$parts = explode('@', $email);
$u = $parts[0];
$d = $parts[1];
$dp = strpos($d, '.');
$email = $u[0] . str_repeat('*', strlen($u) - 1) . '@' . $d[0] . str_repeat('*', $dp - 1) . substr($d, $dp);
}
return $email;
}
public function setEmail($email) {
$this
->set('email', $email);
return $this;
}
public function getAccessHash() {
$data = $this
->uuid() . $this
->getChangedTime() . $this
->getOwnerId();
return Crypt::hmacBase64($data, \Drupal::service('private_key')
->get());
}
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), [
'session',
]);
}
public function toUrl($rel = 'canonical', array $options = []) {
if ($rel == 'form-destination') {
$url = NULL;
if ($dst = $this
->getList()
->getFormDestination()) {
$url = parent::toUrl($dst, $options);
}
if (!$url || !$url
->access()) {
if ($this
->access('view')) {
$url = parent::toUrl('canonical', $options);
}
else {
$url = parent::toUrl('manage', $options);
if (!$url
->access()) {
$url = Url::fromRoute('<front>');
}
}
}
return $url;
}
return parent::toUrl($rel, $options);
}
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields['sid']
->setLabel(t('Subscription ID'))
->setDescription(t('The ID of the subscription.'));
$fields['mailing_list']
->setDescription(t('The mailing list to which this subscription belongs.'));
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Authored by'))
->setRequired(TRUE)
->setDescription(t('The user ID of the subscriber.'))
->setRevisionable(TRUE)
->setSetting('target_type', 'user')
->setSetting('handler', 'default')
->setDefaultValueCallback('Drupal\\mailing_list\\Entity\\Subscription::getCurrentUserId')
->setTranslatable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'author',
'weight' => 0,
])
->setDisplayConfigurable('view', TRUE)
->setDisplayOptions('form', [
'type' => 'entity_reference_autocomplete',
'weight' => 5,
'settings' => [
'match_operator' => 'CONTAINS',
'size' => '60',
'autocomplete_type' => 'tags',
'placeholder' => '',
],
])
->setDisplayConfigurable('form', TRUE);
$fields['title'] = BaseFieldDefinition::create('string')
->setLabel(t('Title'))
->setRequired(TRUE)
->setTranslatable(TRUE)
->setRevisionable(TRUE)
->setSetting('max_length', 255)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'string',
'weight' => -5,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => -5,
])
->setDisplayConfigurable('form', TRUE);
$fields['email'] = BaseFieldDefinition::create('email')
->setLabel(t('Email'))
->setDescription(t('The email address of this subscription.'))
->setRequired(TRUE)
->setRevisionable(TRUE)
->setSetting('max_length', 255)
->setDisplayOptions('view', [
'type' => 'string',
'weight' => 0,
])
->setDisplayConfigurable('view', TRUE)
->setDisplayOptions('form', [
'type' => 'email_default',
'weight' => 0,
])
->setDisplayConfigurable('form', TRUE);
$fields['status'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Active'))
->setDescription(t('Indicates whether the subscription is active.'))
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setDefaultValue(SubscriptionInterface::ACTIVE)
->setDisplayOptions('form', [
'type' => 'boolean_checkbox',
'title' => t('Subscription status'),
'label' => 'above',
'weight' => 5,
])
->setDisplayConfigurable('form', TRUE);
$fields['created'] = BaseFieldDefinition::create('created')
->setLabel(t('Added on'))
->setDescription(t('The time that the subscription was created.'))
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'timestamp',
'weight' => 0,
])
->setDisplayConfigurable('view', TRUE)
->setDisplayOptions('form', [
'type' => 'datetime_timestamp',
'weight' => 10,
])
->setDisplayConfigurable('form', TRUE);
$fields['changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Changed'))
->setDescription(t('The time that the subscription was last updated.'))
->setRevisionable(TRUE)
->setTranslatable(TRUE);
return $fields;
}
public static function getCurrentUserId() {
return [
\Drupal::currentUser()
->id(),
];
}
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
if ($this
->isNew() && $this
->isActive() || $this
->isActive() && isset($this->original) && !$this->original
->isActive()) {
$list = $this
->getList();
$max_reached = FALSE;
if ($max_per_email = intval($list
->getLimitByEmail())) {
$query = \Drupal::entityQuery('mailing_list_subscription')
->condition('status', SubscriptionInterface::ACTIVE)
->condition('email', $this
->getEmail())
->count();
if ($this
->id()) {
$query
->condition('sid', $this
->id(), '<>');
}
$max_reached = $query
->execute() >= $max_per_email;
}
if (!$max_reached && ($max_per_user = intval($list
->getLimitByUser()))) {
$query = \Drupal::entityQuery('mailing_list_subscription')
->condition('status', SubscriptionInterface::ACTIVE)
->condition('uid', \Drupal::currentUser()
->id())
->count();
if ($this
->id()) {
$query
->condition('sid', $this
->id(), '<>');
}
$max_reached = $query
->execute() >= $max_per_user;
}
if ($max_reached) {
$this
->setStatus(SubscriptionInterface::INACTIVE);
\Drupal::service('plugin.manager.mail')
->mail('mailing_list', 'subscription_limit_reached', $this
->getEmail(), $this
->language(), [
'subscription' => $this,
]);
}
}
}
public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
parent::preCreate($storage_controller, $values);
if (!isset($values['uid'])) {
$values['uid'] = \Drupal::currentUser()
->id();
}
}
public function postCreate(EntityStorageInterface $storage) {
parent::postCreate($storage);
if ($this
->getOwner()
->isAnonymous() && \Drupal::currentUser()
->isAnonymous()) {
\Drupal::service('mailing_list.manager')
->grantSessionAccess($this);
}
}
}