You are here

class ImageHotspotsController in Image Hotspots 8

Class ImageHotspotsController.

@package Drupal\image_hotspots\Controller

Hierarchy

Expanded class hierarchy of ImageHotspotsController

File

src/Controller/ImageHotspotsController.php, line 17

Namespace

Drupal\image_hotspots\Controller
View source
class ImageHotspotsController extends ControllerBase {

  /**
   * Deletes hotspot with $hid.
   *
   * @param string $hid
   *   Hotspot id.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   AjaxResponse
   */
  public function deleteAction($hid) {
    if (!$this
      ->accessCallback()) {
      $code = 403;
      $data = $this
        ->t('You did a lot actions with hotspots and can not delete this hotspot right now. Wait some seconds before you can do it again.');
    }
    else {
      try {

        /** @var \Drupal\image_hotspots\Entity\ImageHotspot $hotspot */
        $hotspot = ImageHotspot::load($hid);
        $target = $hotspot
          ->getTarget();
        $hotspot
          ->delete();
        $this
          ->disableCache($target);
        $code = 200;
        $data = $this
          ->t('Hotspot was successfully deleted');
      } catch (EntityStorageException $e) {
        $code = 500;
        $data = $e
          ->getMessage();
      }
    }
    return new AjaxResponse($data, $code);
  }

  /**
   * Creates hotspot with values from request data.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   Request from user to change hotspot.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   AjaxResponse
   */
  public function createAction(Request $request) {
    if (!$this
      ->accessCallback()) {
      $code = 403;
      $parameters['error'] = $this
        ->t('You did a lot actions with hotspots and can not create hotspot right now. Wait some seconds before you can do it again.');
    }
    else {
      $parameters = $request->request
        ->all();
      $parameters['title'] = preg_replace('/(javascript)+(\\s)*:+/', '', Xss::filter($parameters['title']));
      $parameters['description'] = preg_replace('/(javascript)+(\\s)*:+/', '', Xss::filter($parameters['description']));
      $parameters['link'] = preg_replace('/(javascript)+(\\s)*:+/', '', Xss::filter($parameters['link']));
      $parameters['target'] = preg_replace('/(javascript)+(\\s)*:+/', '', Xss::filter($parameters['target']));
      $parameters['uid'] = $this
        ->currentUser()
        ->id();
      try {
        $hotspot = ImageHotspot::create($parameters);
        $hotspot
          ->save();
        $this
          ->disableCache($hotspot
          ->getTarget());
        $code = 200;
        $parameters['hid'] = $hotspot
          ->id();
      } catch (EntityStorageException $e) {
        $code = 500;
        $parameters['error'] = $e
          ->getMessage();
      }
    }
    return new AjaxResponse($parameters, $code);
  }

  /**
   * Update hotspot with $hid.
   *
   * @param string $hid
   *   Hotspot id.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   Request from user to change hotspot.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   AjaxResponse
   */
  public function updateAction($hid, Request $request) {
    if (!$this
      ->accessCallback()) {
      $code = 403;
      $parameters['error'] = $this
        ->t('You did a lot actions with hotspots and can not update this hotspot right now. Wait some seconds before you can do it again.');
    }
    else {

      /** @var \Drupal\image_hotspots\Entity\ImageHotspot $hotspot */
      $hotspot = ImageHotspot::load($hid);
      if (is_null($hotspot)) {
        $code = 404;
        $parameters['error'] = $this
          ->t('Can not find hotspot with hid @hid', [
          '@hid' => $hid,
        ]);
      }
      else {
        $parameters = $request->request
          ->all();
        $parameters['title'] = preg_replace('/(javascript)+(\\s)*:+/', "", Xss::filter($parameters['title']));
        $parameters['description'] = preg_replace('/(javascript)+(\\s)*:+/', "", Xss::filter($parameters['description']));
        $parameters['link'] = preg_replace('/(javascript)+(\\s)*:+/', "", Xss::filter($parameters['link']));
        $parameters['target'] = preg_replace('/(javascript)+(\\s)*:+/', "", Xss::filter($parameters['target']));
        $hotspot
          ->setTitle($parameters['title']);
        $hotspot
          ->setDescription($parameters['description']);
        $hotspot
          ->setLink($parameters['link']);
        $hotspot
          ->setTargetLink($parameters['target']);
        $hotspot
          ->setCoordinates([
          'x' => $parameters['x'],
          'y' => $parameters['y'],
          'x2' => $parameters['x2'],
          'y2' => $parameters['y2'],
        ]);
        try {
          $hotspot
            ->save();
          $this
            ->disableCache($hotspot
            ->getTarget());
          $code = 200;
          $parameters['hid'] = $hotspot
            ->id();
        } catch (EntityStorageException $e) {
          $code = 500;
          $parameters['error'] = $e
            ->getMessage();
        }
      }
    }
    return new AjaxResponse($parameters, $code);
  }

  /**
   * Translate hotspot with $hid.
   *
   * @param $hid
   *   Hotspot id.
   * @param $langcode
   *   Language ID.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   */
  public function translateAction($hid, $langcode, Request $request) {
    if (!$this
      ->accessCallback()) {
      $code = 403;
      $parameters['error'] = $this
        ->t('You did a lot actions with hotspots and can not update this hotspot right now. Wait some seconds before you can do it again.');
    }
    else {

      /** @var ImageHotspotInterface $hotspot */
      $hotspot = ImageHotspot::load($hid);
      if (is_null($hotspot)) {
        $code = 404;
        $parameters['error'] = $this
          ->t('Can not find hotspot with hid ') + $hid;
      }
      else {
        if ($hotspot
          ->hasTranslation($langcode)) {
          $hotspot = $hotspot
            ->getTranslation($langcode);
        }
        else {
          $hotspot = $hotspot
            ->addTranslation($langcode);
        }
        $parameters = $request->request
          ->all();
        $parameters['title'] = preg_replace('/(javascript)+(\\s)*:+/', "", Xss::filter($parameters['title']));
        $parameters['description'] = preg_replace('/(javascript)+(\\s)*:+/', "", Xss::filter($parameters['description']));
        $parameters['link'] = preg_replace('/(javascript)+(\\s)*:+/', "", Xss::filter($parameters['link']));
        $hotspot
          ->setTitle($parameters['title']);
        $hotspot
          ->setDescription($parameters['description']);
        $hotspot
          ->setLink($parameters['link']);
        try {
          $hotspot
            ->save();
          $this
            ->disableCache($hotspot
            ->getTarget());
          $code = 200;
          $parameters['hid'] = $hotspot
            ->id();
        } catch (EntityStorageException $e) {
          $code = 500;
          $parameters['error'] = $e
            ->getMessage();
        }
      }
    }
    return new AjaxResponse($parameters, $code);
  }

  /**
   * Check if user allowed to do actions with hotspots right now.
   *
   * @return bool
   *   Returns true of false when access is requested.
   */
  protected function accessCallback() {
    $flood = \Drupal::flood();
    $name = 'image_hotspots.action';
    $ip = \Drupal::request()
      ->getClientIp();

    // Anonymous can work with hotspots every 20 seconds.
    if ($this
      ->currentUser()
      ->isAnonymous()) {
      $count = 1;
      $window = 20;
      if ($flood
        ->isAllowed($name, $count, $window, $ip)) {
        $flood
          ->register($name, $window, $ip);
        return TRUE;
      }
      else {
        return FALSE;
      }
    }
    else {
      $count = 5;
      $window = 10;
      if ($flood
        ->isAllowed($name, $count, $window, $ip)) {
        $flood
          ->register($name, $window, $ip);
        return TRUE;
      }
      else {
        return FALSE;
      }
    }
  }

  /**
   * Invalidated cache items with current hotspot tag.
   *
   * If user edit hotspots in one place it will displayed in other.
   *
   * @param array $target
   *   Hotspot target.
   */
  protected function disableCache(array $target) {
    $tag = 'hotspots:' . $target['field_name'] . ':' . $target['fid'] . ':' . $target['image_style'];
    \Drupal::service('cache_tags.invalidator')
      ->invalidateTags([
      $tag,
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
ImageHotspotsController::accessCallback protected function Check if user allowed to do actions with hotspots right now.
ImageHotspotsController::createAction public function Creates hotspot with values from request data.
ImageHotspotsController::deleteAction public function Deletes hotspot with $hid.
ImageHotspotsController::disableCache protected function Invalidated cache items with current hotspot tag.
ImageHotspotsController::translateAction public function Translate hotspot with $hid.
ImageHotspotsController::updateAction public function Update hotspot with $hid.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.