whmcs-sms-center-module/modules/addons/mozout_sms_center/mozout_sms_center.php
2026-11-28 15:28:08 +02:00

473 lines
28 KiB
PHP

<?php
/**
* SMS Center Notify: WHMCS addon that sends SMS notices to your clients and to your team
* through the SMS Center API (POST /v1/sms/messages). Install in modules/addons/mozout_sms_center/.
*
* Compatible with PHP 7.4 and 8.x.
*/
use MozoutSmsCenter\Core;
use WHMCS\Database\Capsule;
if (!defined('WHMCS')) {
die('This file cannot be accessed directly');
}
require_once __DIR__ . '/lib/Core.php';
function mozout_sms_center_config()
{
return [
'name' => 'SMS Center Notify',
'description' => Core::t(mozout_smsc_lang(), 'SMS notices to your clients and your team through the SMS Center API: orders, invoices, services, domains and tickets.'),
'version' => Core::VERSION,
'author' => 'SMS Center',
'language' => 'english',
'fields' => [],
];
}
function mozout_sms_center_activate()
{
try {
Core::install();
return ['status' => 'success', 'description' => Core::t(mozout_smsc_lang(), 'SMS Center Notify activated. Open Addons > SMS Center Notify to save the API key.')];
} catch (\Throwable $e) {
return ['status' => 'error', 'description' => Core::t(mozout_smsc_lang(), 'Could not create the tables: %s', $e->getMessage())];
}
}
/** The data (log, templates, settings) is kept, so a reactivation loses nothing. See the README to remove it. */
function mozout_sms_center_deactivate()
{
return ['status' => 'success', 'description' => Core::t(mozout_smsc_lang(), 'SMS Center Notify deactivated. Settings, templates and the log were kept.')];
}
function mozout_sms_center_upgrade($vars)
{
Core::install();
}
/* ---------------------------------------------------------------------- */
/* Admin page */
/* ---------------------------------------------------------------------- */
/**
* The admin's language: $_SESSION['adminlang'], then the admin profile, then the default language
* of the addon. Returns 'pt' or 'en' (any «portuguese*» WHMCS language is 'pt').
*/
function mozout_smsc_lang()
{
$l = isset($_SESSION['adminlang']) ? (string) $_SESSION['adminlang'] : '';
if ($l === '') {
try {
$a = (new \WHMCS\Authentication\CurrentUser())->admin();
$l = $a ? (string) $a->language : '';
} catch (\Throwable $e) {
}
}
if ($l === '') {
try {
$l = Core::get('default_lang', '');
} catch (\Throwable $e) {
}
}
if ($l === '') {
$l = (string) \WHMCS\Config\Setting::getValue('Language');
}
return Core::langFile($l) === 'portuguese' ? 'pt' : 'en';
}
function mozout_smsc_pt()
{
return mozout_smsc_lang() === 'pt';
}
function mozout_smsc_h($s)
{
return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
}
function mozout_sms_center_output($vars)
{
Core::install();
$pt = mozout_smsc_pt();
$T = function ($en, ...$args) use ($pt) {
return Core::t($pt ? 'pt' : 'en', $en, ...$args);
};
$base = $vars['modulelink'];
$tab = isset($_GET['tab']) ? preg_replace('~[^a-z]~', '', $_GET['tab']) : 'overview';
$notice = '';
$noticeType = 'success';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
check_token('WHMCS.admin.default');
$do = (string) ($_POST['do'] ?? '');
if ($do === 'settings') {
$brand = (string) ($_POST['brand'] ?? 'mozout');
if (!Core::brand() && ($brand === 'custom' || isset(Core::brands()[$brand]))) {
Core::set('brand', $brand);
}
$url = rtrim(trim((string) ($_POST['api_url'] ?? '')), '/');
if (Core::brand()) {
// Fixed brand (brand.php): the API address comes from the file, nothing to save.
} elseif ($brand === 'custom' && !preg_match('~^https://[a-z0-9.-]+(:[0-9]+)?$~i', $url)) {
$notice = $T('The API address must start with https:// and have no path.');
$noticeType = 'danger';
} else {
Core::set('api_url', $url);
}
$key = trim((string) ($_POST['api_key'] ?? ''));
if ($key !== '') {
if (preg_match('~^(sandbox|prod)_[A-Za-z0-9_-]{20,}$~', $key)) {
Core::setApiKey($key);
} else {
$notice = $T('The API key starts with sandbox_ or prod_.');
$noticeType = 'danger';
}
}
Core::set('admin_numbers', mb_substr(trim((string) ($_POST['admin_numbers'] ?? '')), 0, 500));
Core::set('default_lang', ($_POST['default_lang'] ?? 'pt') === 'en' ? 'en' : 'pt');
Core::set('strip_accents', !empty($_POST['strip_accents']) ? '1' : '0');
$src = (string) ($_POST['phone_source'] ?? 'phonenumber');
Core::set('phone_source', preg_match('~^(phonenumber|cf:\d+)$~', $src) ? $src : 'phonenumber');
$days = implode(',', array_unique(array_filter(array_map('intval', explode(',', (string) ($_POST['expiry_days'] ?? ''))), function ($d) {
return $d > 0 && $d <= 365;
})));
Core::set('expiry_days', $days !== '' ? $days : '30,7,1');
if (isset($_POST['sender'])) {
Core::set('sender', mb_substr(preg_replace('~[^A-Za-z0-9 ._-]~', '', (string) $_POST['sender']), 0, 11));
}
if ($notice === '') {
$notice = $T('Settings saved.');
}
$tab = 'settings';
} elseif ($do === 'events') {
foreach (array_keys(Core::events()) as $e) {
Capsule::table(Core::T_EVENTS)->updateOrInsert(['event' => $e], ['enabled' => !empty($_POST['on'][$e]) ? 1 : 0]);
foreach (['pt', 'en'] as $l) {
if (isset($_POST['tpl'][$e][$l])) {
$body = trim((string) $_POST['tpl'][$e][$l]);
if ($body === '') {
$body = Core::defaultTemplates()[$e][$l];
}
Capsule::table(Core::T_TEMPLATES)->updateOrInsert(['event' => $e, 'lang' => $l], ['body' => mb_substr($body, 0, 1600)]);
}
}
}
$notice = $T('Events and templates saved.');
$tab = 'events';
} elseif ($do === 'reset_tpl') {
$e = (string) ($_POST['event'] ?? '');
if (isset(Core::defaultTemplates()[$e])) {
foreach (Core::defaultTemplates()[$e] as $l => $b) {
Capsule::table(Core::T_TEMPLATES)->updateOrInsert(['event' => $e, 'lang' => $l], ['body' => $b]);
}
$notice = $T('Template restored.');
}
$tab = 'events';
} elseif ($do === 'test') {
$num = trim((string) ($_POST['number'] ?? ''));
$txt = trim((string) ($_POST['text'] ?? ''));
if ($num === '' || $txt === '') {
$notice = $T('Enter the number and the text.');
$noticeType = 'danger';
} else {
$r = Core::send('test', $num, $txt, 0, 0, null);
$st = (string) ($r['status'] ?? '');
if (in_array($st, ['sent', 'queued', 'scheduled', 'simulated'], true)) {
$notice = $st === 'simulated'
? $T('Test SMS accepted in Sandbox: simulated, not really sent, no credits used.')
: $T('Test SMS sent. Status: %s.', $st);
} else {
$notice = $T('The test SMS was not sent: %s', (string) ($r['error'] ?? $st));
$noticeType = 'danger';
}
}
$tab = 'test';
} elseif ($do === 'optout_add') {
$num = trim((string) ($_POST['number'] ?? ''));
$r = Core::api('POST', '/v1/sms/opt-outs', ['number' => $num], Core::uuid());
if ($r['status'] === 201 || $r['status'] === 200) {
$notice = $T('Number added to the do-not-send list.')
. (!empty($r['json']['data']['simulated']) ? ' ' . $T('(Sandbox: simulated)') : '');
} else {
$notice = Core::errorText($r);
$noticeType = 'danger';
}
$tab = 'optout';
}
}
$tabs = [
'overview' => $T('Overview'),
'settings' => $T('Settings'),
'events' => $T('Events and templates'),
'test' => $T('Test'),
'log' => $T('Sending log'),
'optout' => $T('Opt-outs'),
];
echo '<style>
.mozout_smsc .nav-tabs{margin-bottom:18px}
.mozout_smsc .mozout_smsc-card{border:1px solid #e3e6ea;border-radius:6px;padding:16px 18px;margin-bottom:16px;background:#fff}
.mozout_smsc .mozout_smsc-kpi{display:inline-block;min-width:160px;margin:0 18px 10px 0}
.mozout_smsc .mozout_smsc-kpi b{display:block;font-size:20px}
.mozout_smsc .mozout_smsc-muted{color:#6c757d;font-size:12px}
.mozout_smsc textarea{font-family:inherit}
.mozout_smsc .mozout_smsc-ev{border-top:1px solid #eef0f2;padding:14px 0}
.mozout_smsc .mozout_smsc-ev:first-child{border-top:0}
.mozout_smsc .mozout_smsc-count{font-size:11px;color:#6c757d}
.mozout_smsc .label{font-weight:600}
</style>';
echo '<div class="mozout_smsc">';
echo '<ul class="nav nav-tabs">';
foreach ($tabs as $k => $label) {
echo '<li class="' . ($tab === $k ? 'active' : '') . '"><a href="' . mozout_smsc_h($base . '&tab=' . $k) . '">' . mozout_smsc_h($label) . '</a></li>';
}
echo '</ul>';
if ($notice !== '') {
echo '<div class="alert alert-' . $noticeType . '">' . mozout_smsc_h($notice) . '</div>';
}
$token = function_exists('generate_token') ? generate_token('plain') : '';
$hidden = function ($do) use ($token) {
return '<input type="hidden" name="token" value="' . mozout_smsc_h($token) . '"><input type="hidden" name="do" value="' . mozout_smsc_h($do) . '">';
};
if ($tab === 'overview') {
mozout_smsc_tab_overview($T);
} elseif ($tab === 'settings') {
mozout_smsc_tab_settings($T, $base, $hidden);
} elseif ($tab === 'events') {
mozout_smsc_tab_events($T, $base, $hidden, $pt);
} elseif ($tab === 'test') {
mozout_smsc_tab_test($T, $base, $hidden);
} elseif ($tab === 'log') {
mozout_smsc_tab_log($T, $base, $pt);
} elseif ($tab === 'optout') {
mozout_smsc_tab_optout($T, $base, $hidden);
}
echo '<p class="mozout_smsc-muted">SMS Center Notify ' . mozout_smsc_h(Core::VERSION) . '</p></div>';
}
function mozout_smsc_tab_overview($T)
{
if (Core::apiKey() === '' || Core::endpoint() === '') {
echo '<div class="alert alert-info">' . mozout_smsc_h(Core::brand()
? $T('Start with Settings: save the API key (with sms:read and sms:write).')
: $T('Start with Settings: choose the provider and save the API key (with sms:read and sms:write).')) . '</div>';
return;
}
$token = Core::api('GET', '/v1/token');
$bal = Core::api('GET', '/v1/sms/balance');
echo '<div class="mozout_smsc-card">';
if ($token['status'] !== 200) {
echo '<div class="alert alert-danger">' . mozout_smsc_h(Core::errorText($token)) . '</div>';
} else {
$d = $token['json']['data'];
$perms = (array) ($d['permissions'] ?? []);
$mode = (string) ($d['mode'] ?? '');
echo '<div class="mozout_smsc-kpi"><span class="mozout_smsc-muted">' . mozout_smsc_h($T('Key mode')) . '</span><b>' . mozout_smsc_h($mode === 'sandbox' ? 'Sandbox' : $T('Production')) . '</b></div>';
if ($bal['status'] === 200) {
$b = $bal['json']['data'];
echo '<div class="mozout_smsc-kpi"><span class="mozout_smsc-muted">' . mozout_smsc_h($T('SMS balance')) . '</span><b>' . mozout_smsc_h(rtrim(rtrim(number_format((float) $b['balance'], 2, ',', '.'), '0'), ',')) . ' ' . mozout_smsc_h($T('credits')) . '</b></div>';
echo '<div class="mozout_smsc-kpi"><span class="mozout_smsc-muted">' . mozout_smsc_h($T('Sent today')) . '</span><b>' . (int) ($b['sent_today'] ?? 0) . ' / ' . (int) ($b['daily_limit'] ?? 0) . '</b></div>';
} else {
echo '<div class="alert alert-warning">' . mozout_smsc_h(Core::errorText($bal)) . '</div>';
}
$sender = Core::get('sender');
echo '<div class="mozout_smsc-kpi"><span class="mozout_smsc-muted">Sender ID</span><b>' . mozout_smsc_h($sender !== '' ? $sender : 'NETMSG') . '</b></div>';
if (!in_array('sms:write', $perms, true)) {
echo '<div class="alert alert-warning">' . mozout_smsc_h($T('The key does not have the sms:write permission: SMS will not go out.')) . '</div>';
}
if ($mode === 'sandbox') {
echo '<div class="alert alert-info">' . mozout_smsc_h($T('With a Sandbox key, SMS are simulated: they are not really sent and use no credits.')) . '</div>';
}
}
echo '</div>';
$since = date('Y-m-d H:i:s', strtotime('-30 days'));
$rows = Capsule::table(Core::T_LOG)->where('created_at', '>=', $since)->selectRaw('status, COUNT(*) n')->groupBy('status')->pluck('n', 'status');
echo '<div class="mozout_smsc-card"><b>' . mozout_smsc_h($T('Last 30 days')) . '</b><br><br>';
foreach (['sent' => $T('Sent'), 'simulated' => $T('Simulated'), 'failed' => $T('Failed'), 'skipped' => $T('Skipped')] as $k => $label) {
echo '<div class="mozout_smsc-kpi"><span class="mozout_smsc-muted">' . mozout_smsc_h($label) . '</span><b>' . (int) ($rows[$k] ?? 0) . '</b></div>';
}
echo '</div>';
}
function mozout_smsc_tab_settings($T, $base, $hidden)
{
$brand = Core::get('brand', 'mozout');
$fixed = Core::brand();
$hasKey = Core::apiKey() !== '';
echo '<form method="post" action="' . mozout_smsc_h($base . '&tab=settings') . '" class="mozout_smsc-card">' . $hidden('settings');
if (!$fixed) {
// Neutral module: choose the provider or type another address. With brand.php both are fixed.
echo '<div class="form-group"><label>' . mozout_smsc_h($T('Provider')) . '</label><select name="brand" class="form-control" style="max-width:360px">';
foreach (Core::brands() as $k => $b) {
echo '<option value="' . mozout_smsc_h($k) . '"' . ($brand === $k ? ' selected' : '') . '>' . mozout_smsc_h($T($b[0])) . '</option>';
}
echo '<option value="custom"' . ($brand === 'custom' ? ' selected' : '') . '>' . mozout_smsc_h($T('Other address')) . '</option></select></div>';
echo '<div class="form-group"><label>' . mozout_smsc_h($T('API address (only for «Other address»)')) . '</label><input name="api_url" class="form-control" style="max-width:360px" placeholder="https://api.example.com" value="' . mozout_smsc_h(Core::get('api_url')) . '"></div>';
}
echo '<div class="form-group"><label>' . mozout_smsc_h($T('API key')) . '</label><input name="api_key" type="password" autocomplete="new-password" class="form-control" style="max-width:480px" placeholder="' . mozout_smsc_h($hasKey ? $T('Saved. Type only to replace it.') : $T('sandbox_... or prod_...')) . '">';
echo '<p class="mozout_smsc-muted">' . mozout_smsc_h($fixed
? $T('Create it in %s (%s) > API, with sms:read and sms:write. It is kept encrypted in the WHMCS database.', $fixed['panel_name'], $fixed['panel'])
: $T('Create it on the API page of your account, with sms:read and sms:write. It is kept encrypted in the WHMCS database.')) . '</p></div>';
$senders = [];
if ($hasKey) {
$r = Core::api('GET', '/v1/sms/senders');
if ($r['status'] === 200) {
foreach ((array) $r['json']['data'] as $s) {
if (($s['status'] ?? '') === 'approved') {
$senders[] = (string) $s['sender'];
}
}
}
}
$cur = Core::get('sender');
echo '<div class="form-group"><label>Sender ID</label>';
if ($senders) {
echo '<select name="sender" class="form-control" style="max-width:240px">';
foreach ($senders as $s) {
$val = strtoupper($s) === 'NETMSG' ? '' : $s;
echo '<option value="' . mozout_smsc_h($val) . '"' . ($cur === $val ? ' selected' : '') . '>' . mozout_smsc_h($s) . '</option>';
}
echo '</select><p class="mozout_smsc-muted">' . mozout_smsc_h($T('The approved senders of your account. NETMSG is free.')) . '</p>';
} else {
echo '<input name="sender" class="form-control" style="max-width:240px" maxlength="11" value="' . mozout_smsc_h($cur) . '" placeholder="NETMSG"><p class="mozout_smsc-muted">' . mozout_smsc_h($T('Empty: NETMSG, the free sender.')) . '</p>';
}
echo '</div>';
echo '<div class="form-group"><label>' . mozout_smsc_h($T('Team numbers (new order and new ticket notices)')) . '</label><input name="admin_numbers" class="form-control" style="max-width:480px" placeholder="+14155550123" value="' . mozout_smsc_h(Core::get('admin_numbers')) . '"><p class="mozout_smsc-muted">' . mozout_smsc_h($T('Comma separated.')) . '</p></div>';
$src = Core::get('phone_source', 'phonenumber');
echo '<div class="form-group"><label>' . mozout_smsc_h($T('Client mobile')) . '</label><select name="phone_source" class="form-control" style="max-width:360px"><option value="phonenumber">' . mozout_smsc_h($T('Profile phone number')) . '</option>';
foreach (Capsule::table('tblcustomfields')->where('type', 'client')->where('fieldtype', 'text')->orderBy('sortorder')->get(['id', 'fieldname']) as $f) {
$v = 'cf:' . $f->id;
$name = strpos($f->fieldname, '|') !== false ? substr($f->fieldname, strpos($f->fieldname, '|') + 1) : $f->fieldname;
echo '<option value="' . $v . '"' . ($src === $v ? ' selected' : '') . '>' . mozout_smsc_h($T('Field: %s', $name)) . '</option>';
}
echo '</select></div>';
$lang = Core::get('default_lang', 'pt');
echo '<div class="form-group"><label>' . mozout_smsc_h($T('Default language')) . '</label><select name="default_lang" class="form-control" style="max-width:200px"><option value="pt"' . ($lang === 'pt' ? ' selected' : '') . '>Português</option><option value="en"' . ($lang === 'en' ? ' selected' : '') . '>English</option></select><p class="mozout_smsc-muted">' . mozout_smsc_h($T('For clients with no language set and for team notices.')) . '</p></div>';
echo '<div class="form-group"><label>' . mozout_smsc_h($T('Domain expiring: notify how many days before')) . '</label><input name="expiry_days" class="form-control" style="max-width:200px" value="' . mozout_smsc_h(Core::get('expiry_days', '30,7,1')) . '"></div>';
echo '<div class="checkbox"><label><input type="checkbox" name="strip_accents" value="1"' . (Core::get('strip_accents', '1') === '1' ? ' checked' : '') . '> ' . mozout_smsc_h($T('Remove accents before sending (with accents, each SMS holds 70 characters instead of 160)')) . '</label></div>';
$fid = (int) Core::get('optout_field');
if ($fid) {
echo '<p class="mozout_smsc-muted">' . mozout_smsc_h($T('Clients who tick «I do not want SMS notices» in their account details stop receiving them (field #%s).', $fid)) . '</p>';
}
echo '<button class="btn btn-primary">' . mozout_smsc_h($T('Save')) . '</button></form>';
}
function mozout_smsc_tab_events($T, $base, $hidden, $pt)
{
$on = Capsule::table(Core::T_EVENTS)->pluck('enabled', 'event');
$tpls = [];
foreach (Capsule::table(Core::T_TEMPLATES)->get() as $r) {
$tpls[$r->event][$r->lang] = $r->body;
}
echo '<form method="post" action="' . mozout_smsc_h($base . '&tab=events') . '" class="mozout_smsc-card">' . $hidden('events');
echo '<p class="mozout_smsc-muted">' . mozout_smsc_h($T('Each client gets the notice in the language of their account (Portuguese or English). Team notices use the default language.')) . '</p>';
foreach (Core::events() as $e => $def) {
$vars = implode(' ', array_map(function ($v) {
return '{$' . $v . '}';
}, $def[2]));
echo '<div class="mozout_smsc-ev"><div class="checkbox" style="margin-top:0"><label><input type="checkbox" name="on[' . $e . ']" value="1"' . (!empty($on[$e]) ? ' checked' : '') . '> <b>' . mozout_smsc_h(Core::eventLabel($e, $pt)) . '</b> <span class="label label-' . ($def[0] === 'admin' ? 'warning' : 'info') . '">' . mozout_smsc_h($def[0] === 'admin' ? $T('team') : $T('client')) . '</span></label></div>';
echo '<div class="row">';
foreach (['pt' => 'Português', 'en' => 'English'] as $l => $ln) {
$body = $tpls[$e][$l] ?? Core::defaultTemplates()[$e][$l];
echo '<div class="col-md-6"><label class="mozout_smsc-muted">' . $ln . '</label><textarea class="form-control mozout_smsc-tpl" rows="3" maxlength="1600" name="tpl[' . $e . '][' . $l . ']">' . mozout_smsc_h($body) . '</textarea><span class="mozout_smsc-count"></span></div>';
}
echo '</div><p class="mozout_smsc-muted" style="margin-top:6px">' . mozout_smsc_h($T('Variables: %s', $vars)) . '</p></div>';
}
echo '<button class="btn btn-primary">' . mozout_smsc_h($T('Save')) . '</button></form>';
$strip = Core::get('strip_accents', '1') === '1' ? 'true' : 'false';
$lblParts = json_encode($T('parts'));
$lblChars = json_encode($T('characters'));
echo '<script>(function(){var strip=' . $strip . ';var gsm="@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà",ext="^{}\\\\[~]|€";
function un(s){return s.normalize?s.normalize("NFD").replace(/[̀-ͯ]/g,""):s;}
function count(t){t=t.replace(/\{\$[a-z_]+\}/g,"xxxxxxxxxx");if(strip)t=un(t);var n=0,g=true;for(var c of t){if(gsm.indexOf(c)>=0)n++;else if(ext.indexOf(c)>=0)n+=2;else{g=false;break;}}if(!g){n=Array.from(t).length;return [n,n<=70?1:Math.ceil(n/67),"UCS-2"];}return [n,n<=160?1:Math.ceil(n/153),"GSM"];}
document.querySelectorAll(".mozout_smsc-tpl").forEach(function(a){var s=a.nextElementSibling;function u(){var r=count(a.value);s.textContent="~"+r[0]+" "+' . $lblChars . '+", "+r[1]+" "+' . $lblParts . '+" ("+r[2]+")";}a.addEventListener("input",u);u();});})();</script>';
}
function mozout_smsc_tab_test($T, $base, $hidden)
{
echo '<form method="post" action="' . mozout_smsc_h($base . '&tab=test') . '" class="mozout_smsc-card">' . $hidden('test');
echo '<div class="form-group"><label>' . mozout_smsc_h($T('Number')) . '</label><input name="number" class="form-control" style="max-width:280px" placeholder="+14155550123"></div>';
echo '<div class="form-group"><label>' . mozout_smsc_h($T('Text')) . '</label><textarea name="text" class="form-control" rows="3" maxlength="1600" style="max-width:520px">' . mozout_smsc_h(Core::companyName() . ': ' . $T('SMS notices test.')) . '</textarea></div>';
echo '<p class="mozout_smsc-muted">' . mozout_smsc_h($T('With a Sandbox key, the SMS is simulated: it is not really sent.')) . '</p>';
echo '<button class="btn btn-primary">' . mozout_smsc_h($T('Send test')) . '</button></form>';
}
function mozout_smsc_tab_log($T, $base, $pt)
{
$per = (int) ($_GET['per'] ?? 25);
if (!in_array($per, [10, 25, 50, 100], true)) {
$per = 25;
}
$page = max(1, (int) ($_GET['p'] ?? 1));
$status = preg_replace('~[^a-z]~', '', (string) ($_GET['status'] ?? ''));
$q = Capsule::table(Core::T_LOG);
if ($status !== '') {
$q->where('status', $status);
}
$total = (clone $q)->count();
$rows = $q->orderBy('id', 'desc')->offset(($page - 1) * $per)->limit($per)->get();
$statuses = ['' => $T('All'), 'sent' => $T('Sent'), 'simulated' => $T('Simulated'), 'queued' => $T('Queued'), 'failed' => $T('Failed'), 'skipped' => $T('Skipped')];
echo '<form method="get" class="form-inline" style="margin-bottom:12px"><input type="hidden" name="module" value="mozout_sms_center"><input type="hidden" name="tab" value="log">';
echo '<select name="status" class="form-control input-sm">';
foreach ($statuses as $k => $l) {
echo '<option value="' . $k . '"' . ($status === $k ? ' selected' : '') . '>' . mozout_smsc_h($l) . '</option>';
}
echo '</select> <select name="per" class="form-control input-sm">';
foreach ([10, 25, 50, 100] as $n) {
echo '<option' . ($per === $n ? ' selected' : '') . '>' . $n . '</option>';
}
echo '</select> <button class="btn btn-default btn-sm">' . mozout_smsc_h($T('Filter')) . '</button></form>';
echo '<div class="table-responsive"><table class="table table-condensed table-striped"><thead><tr><th>' . mozout_smsc_h($T('Date')) . '</th><th>' . mozout_smsc_h($T('Event')) . '</th><th>' . mozout_smsc_h($T('Client')) . '</th><th>' . mozout_smsc_h($T('Number')) . '</th><th>' . mozout_smsc_h($T('Text')) . '</th><th>' . mozout_smsc_h($T('Status')) . '</th></tr></thead><tbody>';
$colors = ['sent' => 'success', 'queued' => 'info', 'scheduled' => 'info', 'simulated' => 'default', 'failed' => 'danger', 'skipped' => 'warning'];
foreach ($rows as $r) {
$client = $r->client_id ? '<a href="clientssummary.php?userid=' . (int) $r->client_id . '">#' . (int) $r->client_id . '</a>' : '';
echo '<tr><td style="white-space:nowrap">' . mozout_smsc_h($r->created_at) . '</td><td>' . mozout_smsc_h(Core::eventLabel($r->event, $pt)) . '</td><td>' . $client . '</td><td>' . mozout_smsc_h($r->number) . '</td><td style="max-width:420px">' . mozout_smsc_h($r->text);
if ($r->error !== '') {
echo '<br><span class="text-danger mozout_smsc-muted">' . mozout_smsc_h($r->error) . '</span>';
}
echo '</td><td><span class="label label-' . ($colors[$r->status] ?? 'default') . '">' . mozout_smsc_h($statuses[$r->status] ?? $r->status) . '</span>' . ((float) $r->credits > 0 ? '<br><span class="mozout_smsc-muted">' . mozout_smsc_h((float) $r->credits . ' ' . $T('cr.')) . '</span>' : '') . '</td></tr>';
}
if (!count($rows)) {
echo '<tr><td colspan="6" class="text-center mozout_smsc-muted">' . mozout_smsc_h($T('No messages yet.')) . '</td></tr>';
}
echo '</tbody></table></div>';
$pages = max(1, (int) ceil($total / $per));
if ($pages > 1) {
echo '<ul class="pagination pagination-sm">';
for ($i = max(1, $page - 4); $i <= min($pages, $page + 4); $i++) {
echo '<li class="' . ($i === $page ? 'active' : '') . '"><a href="' . mozout_smsc_h($base . '&tab=log&per=' . $per . '&status=' . $status . '&p=' . $i) . '">' . $i . '</a></li>';
}
echo '</ul>';
}
echo '<p class="mozout_smsc-muted">' . (int) $total . ' ' . mozout_smsc_h($T('messages')) . '</p>';
}
function mozout_smsc_tab_optout($T, $base, $hidden)
{
$fid = (int) Core::get('optout_field');
$n = $fid ? Capsule::table('tblcustomfieldsvalues')->where('fieldid', $fid)->where('value', 'on')->count() : 0;
echo '<div class="mozout_smsc-card"><p>' . mozout_smsc_h($T('Clients who asked not to receive SMS (field in their account details): ')) . '<b>' . (int) $n . '</b></p>';
echo '<p class="mozout_smsc-muted">' . mozout_smsc_h($T('For a number that is not a client, add it to your SMS Center account list. From then on the API refuses to send to it.')) . '</p>';
echo '<form method="post" action="' . mozout_smsc_h($base . '&tab=optout') . '" class="form-inline">' . $hidden('optout_add') . '<input name="number" class="form-control" placeholder="+14155550123"> <button class="btn btn-default">' . mozout_smsc_h($T('Add to the list')) . '</button></form></div>';
$r = Core::api('GET', '/v1/sms/opt-outs?per_page=25');
if ($r['status'] === 200) {
echo '<div class="mozout_smsc-card"><b>' . mozout_smsc_h($T('SMS Center account list')) . '</b><table class="table table-condensed"><tbody>';
foreach ((array) $r['json']['data'] as $o) {
echo '<tr><td>' . mozout_smsc_h($o['number'] ?? '') . '</td><td class="mozout_smsc-muted">' . mozout_smsc_h($o['created_at'] ?? '') . '</td></tr>';
}
if (empty($r['json']['data'])) {
echo '<tr><td class="mozout_smsc-muted">' . mozout_smsc_h($T('The list is empty.')) . '</td></tr>';
}
echo '</tbody></table></div>';
}
}