You are here

class PoptinController in Website Popups, Email Popup, Exit-Intent Popup, and Contact Forms – Poptin 8

Provides route responses for the Poptin module.

Hierarchy

Expanded class hierarchy of PoptinController

File

src/Controller/PoptinController.php, line 15

Namespace

Drupal\poptin\Controller
View source
class PoptinController extends ControllerBase {

  /**
   * Returns a simple page.
   *
   * @return array
   *   A simple renderable array.
   */

  /**
   * Use variable.
   *
   * @var baseUrlT
   */
  protected $baseUrlT;

  /**
   * Use variable.
   *
   * @var tokenGenerator
   */
  protected $tokenGenerator;

  /**
   * Implements __construct().
   */
  public function __construct(CsrfTokenGenerator $csrf_token) {
    global $base_url;
    $this->baseUrlT = $base_url;
    $this->tokenGenerator = $csrf_token;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('csrf_token'));
  }

  /**
   * Implements check().
   */
  public function check() {
    if (!$this
      ->poptinIsUser()) {
      $regclass = "yes";
    }
    else {
      $regclass = 'no';
    }
    $csrftoken = $this
      ->poptinGetToken();
    $module_img_dir = $this->baseUrlT . '/' . drupal_get_path('module', 'poptin') . '/images/';
    $generateloginlink = $this->baseUrlT . '/admin/config/poptin/poptinGeneratePoptinLink?csrftoken=' . $csrftoken;
    $poptin_deactivate = $this->baseUrlT . '/admin/config/poptin/poptinDeactivate';
    return [
      '#theme' => 'main_template',
      '#test_var' => $regclass,
      '#csrftoken' => $csrftoken,
      '#module_img_dir' => $module_img_dir,
      '#base_url' => $this->baseUrlT,
      '#generateloginlink' => $generateloginlink,
      '#deactivate_url' => $poptin_deactivate,
    ];
  }

  /**
   * Implements poptinDeactivate().
   */
  public function poptinDeactivate(Request $request) {
    $token = $request->request
      ->get('csrftoken');
    if (!$this
      ->poptinCheckToken($token)) {
      $tmp_arr = [
        'mssg' => "Invalid CSRF TOKEN",
        'status' => 0,
        'token' => $this
          ->poptinGetToken(),
      ];
      die(Json::encode($tmp_arr));
    }
    \Drupal::database()
      ->truncate('poptin')
      ->execute();
    $tmp_arr = [
      'mssg' => "done",
      'status' => 1,
      'token' => $this
        ->poptinGetToken(),
    ];
    die(Json::encode($tmp_arr));
  }

  /**
   * Implements poptinGeneratePoptinLink().
   */
  public function poptinGeneratePoptinLink(Request $request) {
    $token = $request->query
      ->get('csrftoken');
    if (!$this
      ->poptinCheckToken($token)) {
      $tmp_arr = [
        'mssg' => "Invalid csrf token",
        'status' => 0,
        'token' => $this
          ->poptinGetToken(),
      ];
      die(Json::encode($tmp_arr));
    }
    $api_url = "https://app.popt.in/api/marketplace/";
    $row_details = $this
      ->poptinFetchRow();
    if (!is_array($row_details)) {
      exit(FALSE);
    }
    else {
      if (isset($row_details['token']) && $row_details['token'] == '') {
        return new TrustedRedirectResponse("https://app.popt.in/login");
      }
    }
    $url = $api_url . "auth";
    $dataurl = "token=" . $row_details['token'] . "&user_id=" . $row_details['userid'];
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $dataurl,
      CURLOPT_HTTPHEADER => [
        "cache-control: no-cache",
        "content-type: application/x-www-form-urlencoded",
        "postman-token: 16ba048a-499c-06c8-517c-cea2abb11945",
      ],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    if ($err) {
      echo "cURL Error #:" . $err;
    }
    else {
      $res = json_decode($response);
      if (!isset($res->login_url)) {
        return new TrustedRedirectResponse("https://app.popt.in/login");
      }
      if ($request->query
        ->get('utm_source')) {
        return new TrustedRedirectResponse($res->login_url . "&utm_source=drupal8");
      }
      else {
        return new TrustedRedirectResponse($res->login_url);
      }
    }
  }

  /**
   * Implements poptinSignup().
   */
  public function poptinSignup(Request $request) {
    $token = $request->request
      ->get('csrftoken');
    if (!$this
      ->poptinCheckToken($token)) {
      $tmp_arr = [
        'mssg' => "Invalid csrf token",
        'status' => 0,
        'token' => $this
          ->poptinGetToken(),
      ];
      die(Json::encode($tmp_arr));
    }
    $email_id = $request->request
      ->get('email');
    $api_url = "https://app.popt.in/api/marketplace/";
    $url = $api_url . "register";
    $dataurl = "email=" . $email_id . "&marketplace=drupal8";
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $dataurl,
      CURLOPT_HTTPHEADER => [
        "cache-control: no-cache",
        "content-type: application/x-www-form-urlencoded",
        "postman-token: 16ba048a-499c-06c8-517c-cea2abb11945",
      ],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    if ($err) {
      echo "cURL Error #:" . $err;
    }
    else {
      $result = json_decode($response);
      if (!empty($result) && $result->success == 1) {
        $tmp_arr = [
          'user_id' => $result->user_id,
          'client_id' => $result->client_id,
          'token' => $result->token,
        ];
        \Drupal::database()
          ->insert('poptin')
          ->fields($tmp_arr)
          ->execute();
        $return_mssg = [
          'mssg' => "User Registered successfully",
          'status' => 1,
          'token' => $this
            ->poptinGetToken(),
        ];
      }
      else {
        $return_mssg = [
          'mssg' => $result->message,
          'status' => 0,
          'token' => $this
            ->poptinGetToken(),
        ];
      }
    }
    echo Json::encode($return_mssg);
    die;
  }

  /**
   * Implements poptinLogin().
   */
  public function poptinLogin(Request $request) {
    $userid = $request->request
      ->get('userid');
    \Drupal::database()
      ->insert('poptin')
      ->fields([
      'client_id' => $userid,
    ])
      ->execute();
    $return_mssg = [
      'mssg' => "User id Registered successfully",
      'status' => 1,
      'token' => $this
        ->poptinGetToken(),
    ];
    die(Json::encode($return_mssg));
  }

  /**
   * Implements poptinFetchRow().
   */
  public function poptinFetchRow() {
    $results = \Drupal::database()
      ->select('poptin', 'p')
      ->fields('p')
      ->execute();
    $results->allowRowCount = TRUE;
    $num_of_results = $results
      ->rowCount();
    if ($num_of_results > 0) {
      foreach ($results as $result) {
        return [
          'userid' => $result->user_id,
          'client_id' => $result->client_id,
          'token' => $result->token,
        ];
      }
    }
    else {
      return FALSE;
    }
  }

  /**
   * Implements poptinIsUser().
   */
  public function poptinIsUser() {
    $result = \Drupal::database()
      ->select('poptin', 'p')
      ->fields('p')
      ->execute();
    $result->allowRowCount = TRUE;
    $num_of_results = $result
      ->rowCount();
    if ($num_of_results > 0) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }

  /**
   * Implements poptin_check_csrf_token().
   */
  private function poptinCheckToken($token) {
    if (!empty($token)) {
      $testtoken = $this->tokenGenerator
        ->validate($token);
      if ($testtoken) {
        return TRUE;
      }
      return FALSE;
    }
    return FALSE;
  }

  /**
   * Implements poptin_check_csrf_token().
   */
  private function poptinGetToken() {
    $token = $this->tokenGenerator
      ->get();
    return $token;
  }

}

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::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.
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.
PoptinController::$baseUrlT protected property Use variable.
PoptinController::$tokenGenerator protected property Use variable.
PoptinController::check public function Implements check().
PoptinController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
PoptinController::poptinCheckToken private function Implements poptin_check_csrf_token().
PoptinController::poptinDeactivate public function Implements poptinDeactivate().
PoptinController::poptinFetchRow public function Implements poptinFetchRow().
PoptinController::poptinGeneratePoptinLink public function Implements poptinGeneratePoptinLink().
PoptinController::poptinGetToken private function Implements poptin_check_csrf_token().
PoptinController::poptinIsUser public function Implements poptinIsUser().
PoptinController::poptinLogin public function Implements poptinLogin().
PoptinController::poptinSignup public function Implements poptinSignup().
PoptinController::__construct public function Implements __construct().
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.