You are here

class SimpleGateway in SMS simple gateway 8

This plugin handles sending SMSes through most GET & POST based SMS Gateways.

Plugin annotation


@SmsGateway(
  id = "simplegateway",
  label = @Translation("Simple Gateway"),
  outgoing_message_max_recipients = 1,
  incoming = TRUE,
  incoming_route = TRUE,
)

Hierarchy

Expanded class hierarchy of SimpleGateway

File

src/Plugin/SmsGateway/SimpleGateway.php, line 33

Namespace

Drupal\sms_simplegateway\Plugin\SmsGateway
View source
class SimpleGateway extends SmsGatewayPluginBase implements ContainerFactoryPluginInterface {

  /**
   * Creates an instance of the plugin.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The container to pull out services used in the plugin.
   * @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.
   *
   * @return static
   *   Returns an instance of this plugin.
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  function defaultConfiguration() {
    parent::defaultConfiguration();
    $default_config = \Drupal::config('sms_simplegateway.settings');
    return [
      'method' => $default_config
        ->get('method'),
      'authorization' => $default_config
        ->get('authorization'),
      'content_type' => $default_config
        ->get('content_type'),
      'base_url' => $default_config
        ->get('base_url'),
      'user_field' => $default_config
        ->get('user_field'),
      'user_value' => $default_config
        ->get('user_value'),
      'pass_field' => $default_config
        ->get('pass_field'),
      'pass_value' => $default_config
        ->get('pass_value'),
      'sender_field' => $default_config
        ->get('sender_field'),
      'sender_value' => $default_config
        ->get('sender_value'),
      'number_field' => $default_config
        ->get('number_field'),
      'number_prefix' => $default_config
        ->get('number_prefix'),
      'message_field' => $default_config
        ->get('message_field'),
      'extra_params' => $default_config
        ->get('extra_params'),
      'receive_number_field' => $default_config
        ->get('receive_number_field'),
      'receive_message_field' => $default_config
        ->get('receive_message_field'),
      'receive_gwnumber_field' => $default_config
        ->get('receive_gwnumber_field'),
    ];
  }

  /**
   * Builds the configuration form.
   *
   * @param array $form
   *   The configuration form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The updated form.
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['send'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Outgoing Messages'),
      '#tree' => TRUE,
      '#open' => TRUE,
    ];
    $form['send']['method'] = [
      '#type' => 'radios',
      '#required' => TRUE,
      '#title' => $this
        ->t('HTTP method'),
      '#default_value' => $this->configuration['method'],
      '#options' => [
        'get' => 'GET',
        'post' => 'POST',
      ],
    ];
    $form['send']['authorization'] = [
      '#type' => 'radios',
      '#required' => TRUE,
      '#title' => $this
        ->t('Authorization'),
      '#description' => $this
        ->t('For POST Requests Only. use "Username field value" & "Password field value" to specify credentials'),
      '#default_value' => $this->configuration['authorization'],
      '#options' => [
        'none' => 'NONE',
        'basic' => 'BASIC',
        'digest' => 'DIGEST',
        'ntlm' => 'NTLM',
      ],
    ];
    $form['send']['content_type'] = [
      '#type' => 'radios',
      '#required' => TRUE,
      '#title' => $this
        ->t('Content Encoding'),
      '#description' => $this
        ->t('For POST Requests Only.'),
      '#default_value' => $this->configuration['content_type'],
      '#options' => [
        'plain' => 'Plain',
        'json' => 'Json',
      ],
    ];
    $form['send']['base_url'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => $this
        ->t('Base URL for sending messages'),
      '#description' => $this
        ->t('Eg: http://simplegateway.example.com:13031/sendsms'),
      '#default_value' => $this->configuration['base_url'],
    ];
    $form['send']['user_field'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => $this
        ->t('Username field name'),
      '#description' => $this
        ->t('The argument/field name for the field that holds the username. Eg: user, username, authid.'),
      '#default_value' => $this->configuration['user_field'],
    ];
    $form['send']['user_value'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => $this
        ->t('Username field value'),
      '#description' => $this
        ->t('Your username for this gateway account.'),
      '#default_value' => $this->configuration['user_value'],
    ];
    $form['send']['pass_field'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Password field name'),
      '#description' => $this
        ->t('Optional. The argument/field name for the field that holds the password. Eg: pass, password, passwd.'),
      '#default_value' => $this->configuration['pass_field'],
    ];
    $form['send']['pass_value'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Password field value'),
      '#description' => $this
        ->t('Optional. Your password for this gateway account.'),
      '#default_value' => $this->configuration['pass_value'],
    ];
    $form['send']['sender_field'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Sender (from) field name'),
      '#description' => $this
        ->t('The argument/field name for the field that holds the sender number data. Eg: from, sender'),
      '#default_value' => $this->configuration['sender_field'],
    ];
    $form['send']['sender_value'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Sender (from) field value'),
      '#description' => $this
        ->t('The FROM number/name the sms should go out having'),
      '#default_value' => $this->configuration['sender_value'],
    ];
    $form['send']['number_field'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => $this
        ->t('Number (to) field name'),
      '#description' => $this
        ->t('The argument/field name for the field that holds the number data. Eg: number, to, no'),
      '#default_value' => $this->configuration['number_field'],
    ];
    $form['send']['number_prefix'] = [
      '#type' => 'textfield',
      '#title' => t('Number (to) prefix value'),
      '#description' => t('The value to be prefixed to the sender. Eg: country code'),
      '#default_value' => $this->configuration['number_prefix'],
    ];
    $form['send']['message_field'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => $this
        ->t('Message field name'),
      '#description' => $this
        ->t('The argument/field name for the field that holds the message text. Eg: message, text, content'),
      '#default_value' => $this->configuration['message_field'],
    ];
    $form['send']['extra_params'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Extra parameters'),
      '#description' => $this
        ->t('Any additional parameters that the gateway may need. Eg: route=4&country=0'),
      '#default_value' => $this->configuration['extra_params'],
    ];
    $form['receive']['receive_number_field'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Sender (from) field name'),
      '#description' => $this
        ->t('The argument/field name for the field that holds the sender number. Eg: sender, from.'),
      '#default_value' => $this->configuration['receive_number_field'],
      '#group' => 'incoming_messages',
    ];
    $form['receive']['receive_message_field'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Message field name'),
      '#description' => $this
        ->t('The argument/field name for the field that holds the message. Eg: message, text, content.'),
      '#default_value' => $this->configuration['receive_message_field'],
      '#group' => 'incoming_messages',
    ];
    $form['receive']['receive_gwnumber_field'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Receiver (to) field name'),
      '#description' => $this
        ->t('Optional. The argument/field name for the field that holds the gateway receiver number. Eg: to, inNumber, receiver.'),
      '#default_value' => $this->configuration['receive_gwnumber_field'],
      '#group' => 'incoming_messages',
    ];
    return $form;
  }

  /**
   * Saves the configuration values.
   *
   * @param array $form
   *   The configuration form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['method'] = trim($form_state
      ->getValue([
      'send',
      'method',
    ]));
    $this->configuration['authorization'] = trim($form_state
      ->getValue([
      'send',
      'authorization',
    ]));
    $this->configuration['content_type'] = trim($form_state
      ->getValue([
      'send',
      'content_type',
    ]));
    $this->configuration['base_url'] = trim($form_state
      ->getValue([
      'send',
      'base_url',
    ]));
    $this->configuration['user_field'] = trim($form_state
      ->getValue([
      'send',
      'user_field',
    ]));
    $this->configuration['user_value'] = trim($form_state
      ->getValue([
      'send',
      'user_value',
    ]));
    $this->configuration['pass_field'] = trim($form_state
      ->getValue([
      'send',
      'pass_field',
    ]));
    $this->configuration['pass_value'] = trim($form_state
      ->getValue([
      'send',
      'pass_value',
    ]));
    $this->configuration['sender_field'] = trim($form_state
      ->getValue([
      'send',
      'sender_field',
    ]));
    $this->configuration['sender_value'] = trim($form_state
      ->getValue([
      'send',
      'sender_value',
    ]));
    $this->configuration['number_field'] = trim($form_state
      ->getValue([
      'send',
      'number_field',
    ]));
    $this->configuration['number_prefix'] = trim($form_state
      ->getValue([
      'send',
      'number_prefix',
    ]));
    $this->configuration['message_field'] = trim($form_state
      ->getValue([
      'send',
      'message_field',
    ]));
    $this->configuration['extra_params'] = trim($form_state
      ->getValue([
      'send',
      'extra_params',
    ]));
    $this->configuration['receive_number_field'] = trim($form_state
      ->getValue('receive_number_field'));
    $this->configuration['receive_message_field'] = trim($form_state
      ->getValue('receive_message_field'));
    $this->configuration['receive_gwnumber_field'] = trim($form_state
      ->getValue('receive_gwnumber_field'));
  }

  /**
   * Sends out the sms by hitting the gateway.
   *
   * @param \Drupal\sms\Message\SmsMessageInterface $sms
   *   The sms to be sent out to the user.
   *
   * @return \Drupal\sms\Message\SmsMessageResultInterface
   *   A response object indicating whether the sms was sent or not.
   */
  public function send(SmsMessageInterface $sms) {
    $client = \Drupal::httpClient();
    $result = new SmsMessageResult();
    $report = new SmsDeliveryReport();
    $parameters = array_filter([
      $this->configuration['user_field'] => $this->configuration['user_value'],
      $this->configuration['pass_field'] => $this->configuration['pass_value'],
      $this->configuration['sender_field'] => $this->configuration['sender_value'],
      $this->configuration['number_field'] => $this->configuration['number_prefix'] . $sms
        ->getRecipients()[0],
      $this->configuration['message_field'] => $sms
        ->getMessage(),
    ]);
    $url = NULL;
    $options = [];
    switch ($this->configuration['method']) {
      case 'get':
        $url = $this->configuration['base_url'] . '?' . http_build_query($parameters) . '&' . $this->configuration['extra_params'];
        break;
      case 'post':
        $url = $this->configuration['base_url'];
        switch ($this->configuration['authorization']) {
          case 'basic':
            $options['auth'] = [
              $this->configuration['user_value'],
              $this->configuration['pass_value'],
            ];
            break;
          case 'digest':
            $options['auth'] = [
              $this->configuration['user_value'],
              $this->configuration['pass_value'],
              'digest',
            ];
            break;
          case 'ntlm':
            $options['auth'] = [
              $this->configuration['user_value'],
              $this->configuration['pass_value'],
              'ntlm',
            ];
            break;
        }
        switch ($this->configuration['content_type']) {
          case 'plain':
            $options['headers'] = [
              'Content-Type' => 'application/x-www-form-urlencoded',
            ];
            $options['body'] = http_build_query($parameters) . '&' . $this->configuration['extra_params'];
            break;
          case 'json':
            $options['headers'] = [
              'Content-Type' => 'application/json',
            ];
            $options['body'] = json_encode($parameters);
            break;
            break;
        }
    }
    try {
      $response = $client
        ->request($this->configuration['method'], $url, $options);
      if ($response
        ->getStatusCode() >= 200 and $response
        ->getStatusCode() <= 299) {
        return $result
          ->addReport($report
          ->setRecipient($sms
          ->getRecipients()[0])
          ->setStatus(SmsMessageReportStatus::QUEUED));
      }
      else {
        return $result
          ->addReport($report
          ->setRecipient($sms
          ->getRecipients()[0])
          ->setStatus(SmsMessageResultStatus::ERROR))
          ->setErrorMessage($response
          ->getBody());
      }
    } catch (HttpException $e) {
      return $result
        ->setError(SmsMessageResultStatus::ERROR)
        ->setErrorMessage($e
        ->getMessage());
    }
  }

  /**
   * Process an incoming message POST request.
   *
   * This callback expects a 'messages' POST value containing JSON.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   * @param \Drupal\sms\Entity\SmsGatewayInterface $sms_gateway
   *   The gateway instance.
   *
   * @return \Drupal\sms\SmsProcessingResponse
   *   A SMS processing response task.
   */
  public function processIncoming(Request $request, SmsGatewayInterface $sms_gateway) {
    $number = $request
      ->get($this->configuration['receive_number_field']);
    $text = $request
      ->get($this->configuration['receive_message_field']);
    $gwnumber = $request
      ->get($this->configuration['receive_gwnumber_field']);
    $report = (new SmsDeliveryReport())
      ->setRecipient($gwnumber)
      ->setTimeDelivered(\Drupal::time()
      ->getRequestTime());
    $result = (new SmsMessageResult())
      ->setReports([
      $report,
    ]);
    $message = (new SmsMessage())
      ->addRecipient($gwnumber)
      ->setMessage($text)
      ->setSender($number)
      ->setResult($result)
      ->setGateway($sms_gateway)
      ->setDirection(Direction::INCOMING);
    $response = new Response('', 200);
    $task = (new SmsProcessingResponse())
      ->setResponse($response)
      ->setMessages([
      $message,
    ]);
    return $task;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
SimpleGateway::buildConfigurationForm public function Builds the configuration form. Overrides SmsGatewayPluginBase::buildConfigurationForm
SimpleGateway::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
SimpleGateway::defaultConfiguration function Gets default configuration for this plugin. Overrides SmsGatewayPluginBase::defaultConfiguration
SimpleGateway::processIncoming public function Process an incoming message POST request.
SimpleGateway::send public function Sends out the sms by hitting the gateway. Overrides SmsGatewayPluginInterface::send
SimpleGateway::submitConfigurationForm public function Saves the configuration values. Overrides SmsGatewayPluginBase::submitConfigurationForm
SmsGatewayPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
SmsGatewayPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurablePluginInterface::getConfiguration
SmsGatewayPluginBase::getCreditsBalance public function Returns the credit balance available on this gateway. Overrides SmsGatewayPluginInterface::getCreditsBalance 1
SmsGatewayPluginBase::getDeliveryReports public function Gets delivery reports from the gateway. Overrides SmsGatewayPluginInterface::getDeliveryReports 1
SmsGatewayPluginBase::parseDeliveryReports public function Parses incoming delivery reports and returns the created delivery reports. Overrides SmsGatewayPluginInterface::parseDeliveryReports 1
SmsGatewayPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurablePluginInterface::setConfiguration
SmsGatewayPluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
SmsGatewayPluginBase::__construct public function Constructs a new SmsGateway plugin. Overrides PluginBase::__construct 1
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.