mocean_sms_broadcast-1.x-dev/src/Form/SmsBroadcastPageForm.php
src/Form/SmsBroadcastPageForm.php
<?php
namespace Drupal\mocean_sms_broadcast\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\mocean_sms_broadcast\Utility;
use Drupal\user\Entity\User;
use Drupal\user\Entity;
use Drupal\Core\Database\Database;
use Drupal\Core\Link;
use Drupal\Core\Url;
class SmsBroadcastPageForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'mocean_sms_broadcast_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$jsonResponse1 = (new Utility)->smsBroadcastGetCredit();
$jsonResponse2 = (new Utility)->smsBroadcastGetPricing();
if ($jsonResponse1['status'] == 0 && $jsonResponse2['status'] == 0)
$str = $jsonResponse2['destinations'][0]['currency'].' '.$jsonResponse1['value'];
else {
if ($jsonResponse1['status'] != 0)
$str = $jsonResponse1['err_msg'];
else if ($jsonResponse2['status'] != 0)
$str = $jsonResponse2['err_msg'];
}
$form['help'] = [
'#type' => 'markup',
'#markup' => '<p align="right">Credit Balance: '.$str.' </p>',
'#weight' => -3,
];
$form['recipient'] = [
'#type' => 'select',
'#title' => $this->t('To:'),
'#options' => [
'all' => $this->t('All users'),
'specific_user' => $this->t('Specific users'),
'specific_phone' => $this->t('Specific phone numbers'),
],
'#required' => TRUE,
'#attributes' => [
'number' => 'field_enter_number',
'user' => 'field_select_user',
],
'#weight' => -2,
];
$form['specific_phone_numbers'] = [
'#type' => 'textarea',
'#cols' => 60,
'#rows' => 5,
'#placeholder' => 'Enter specific phone numbers with comma or space as separator. Country code is required.',
'#states' => [
'visible' => [
':input[number="field_enter_number"]' => ['value' => 'specific_phone'],
],
],
'#weight' => -1,
];
$ids = \Drupal::entityQuery('user')
->condition('status', 1)
->execute();
$users = User::loadMultiple($ids);
$userlist = [];
foreach ($users as $count => $us){
$userlist[$count] = $us->get('name')->value;;
}
$form['specific_users'] = [
'#type' => 'select',
'#options' => $userlist,
'#multiple' => TRUE,
'#attributes' => [
'id' => 'specific_users',
],
'#states' => [
'visible' => [
':input[user="field_select_user"]' => ['value' => 'specific_user'],
],
],
'#weight' => -1,
'#attributes' => [
'style' => 'width: 20em;'
],
];
$form['message'] = [
'#type' => 'textarea',
'#title' => $this->t('Message:'),
'#cols' => 60,
'#rows' => 5,
'#weight' => 1,
'#required' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Send'),
'#weight' => 2,
];
$form['#attached']['library'][] = 'mocean_sms_broadcast/mocean_sms_broadcast';
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$sms_broadcast_settings = \Drupal::config('mocean_sms_broadcast.settings');
if($sms_broadcast_settings->get('api_key') == '' || $sms_broadcast_settings->get('api_key') == '') {
$this->messenger()->addError($this->t('API key or API secret not configured.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$sms_broadcast_settings = \Drupal::config('mocean_sms_broadcast.settings');
$user = User::load(\Drupal::currentUser()->id());
$timezone = $user->getTimeZone();
date_default_timezone_set($timezone);
$conn = Database::getConnection();
$recipient = $form_state->getValue('recipient');
if($recipient == 'specific_user') {
$specific_user = $form_state->getValue('specific_users');
foreach($specific_user as $spe) {
$user = \Drupal\user\Entity\User::load($spe);
$phone = $user->get((new Utility)->getFieldName())->value;
$recipients = array();
if($phone != '') {
$recipients[] = $phone;
}
}
}
else if($recipient == 'specific_phone') {
$recipients = array();
$recipients = preg_split('~[^0-9]~i', $form_state->getValue(['specific_phone_numbers']), -1, PREG_SPLIT_NO_EMPTY);
}
else {
$ids = \Drupal::entityQuery('user')
->condition('status', 1)
->execute();
$recipient = User::loadMultiple($ids);
$recipients = array();
foreach($recipient as $rec) {
$phone = $rec->get((new Utility)->getFieldName())->value;
if($phone != '') {
$recipients[] = $phone;
}
}
}
if (empty($recipients)) {
$recipients[] = '';
}
foreach ($recipients as $rec) {
$final = (new Utility)->smsBroadcastSendMessage($rec, $form_state->getValue('message'));
if (count($final) == count($final, COUNT_RECURSIVE)) {
$errMsg = $final['err_msg'];
$status = $final['status'];
}
else {
$errMsg = $final['messages'][0]['err_msg'];
$status = $final['messages'][0]['status'];
}
$allSent = true;
if ($status == 0) {
$conn->insert('mocean_sms_history')->fields(
array(
'sender' => $sms_broadcast_settings->get('message_from'),
'datetime' => date("Y/m/d").' '.date("H:i:s"),
'message' => $form_state->getValue('message'),
'recipient' => $rec,
'response' => 'Message sent',
'status' => 'Success',
)
)->execute();
}
else {
$conn->insert('mocean_sms_history')->fields(
array(
'sender' => $sms_broadcast_settings->get('message_from'),
'datetime' => date("Y/m/d").' '.date("H:i:s"),
'message' => $form_state->getValue('message'),
'recipient' => $rec,
'response' => $errMsg,
'status' => 'Fail',
)
)->execute();
$allSent = false;
}
}
if ($allSent) {
$this->messenger()->addStatus($this->t('Messages sent.'));
}
else {
$this->messenger()->addError($this->t('Error encountered when sending message, check MoceanSMS History for more details.'));
}
}
}
