Vigiar
1
0
Derivar
Você já tinha feito uma derivação do repositório wordpress-sms-center-plugin, anteriormente
0
wordpress-sms-center-plugin/interweb-ao-sms-center/includes/class-sms.php
2026-12-01 13:26:00 +02:00

162 linhas
7 KiB
PHP

<?php
if (!defined('ABSPATH')) {
exit;
}
/**
* Sending SMS: one message (POST /v1/sms/messages) or many (POST /v1/sms/messages/batch),
* with an Idempotency-Key so a retry never sends twice. Also reads the senders and the balance.
*/
class INTERWEB_AO_SMS_CENTER_Sms
{
const BATCH_SIZE = 500;
const MAX_RECIPIENTS = 5000;
/** Splits a list of numbers (lines, commas or semicolons) and keeps the ones that look like a phone number. */
public static function numbers($text)
{
$out = array();
foreach (preg_split('/[\r\n,;]+/', (string) $text) as $n) {
$n = trim(preg_replace('/[^\d+ ]/', '', $n));
$digits = preg_replace('/\D/', '', $n);
if (strlen($digits) >= 9 && strlen($digits) <= 15) {
$out[$digits] = $n;
}
}
return array_values($out);
}
/** Characters and parts of a text: 160 per SMS (153 when split), or 70 (67) with characters outside the GSM alphabet. */
public static function parts($text)
{
$text = (string) $text;
$gsm = "@£\$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà^{}\\[~]|€";
$len = function_exists('mb_strlen') ? mb_strlen($text, 'UTF-8') : strlen($text);
$unicode = false;
$count = 0;
for ($i = 0; $i < $len; $i++) {
$ch = function_exists('mb_substr') ? mb_substr($text, $i, 1, 'UTF-8') : $text[$i];
if (strpos($gsm, $ch) === false) {
$unicode = true;
break;
}
$count += (strpos('^{}\\[~]|€', $ch) !== false) ? 2 : 1;
}
if ($unicode) {
$count = $len;
$parts = $count <= 70 ? 1 : (int) ceil($count / 67);
} else {
$parts = $count <= 160 ? 1 : (int) ceil($count / 153);
}
return array('chars' => $count, 'parts' => max(1, $parts), 'unicode' => $unicode);
}
/** One SMS. @return array|WP_Error */
public static function send($number, $text, $idempotency_key = true, $lang = null, $sender = null)
{
$sender = $sender === null ? (string) INTERWEB_AO_SMS_CENTER_Settings::get('sms_sender') : (string) $sender;
return INTERWEB_AO_SMS_CENTER_Api::send_sms($number, $text, $sender, $idempotency_key, $lang);
}
/**
* Many SMS with the same text, in batches of 500. $key makes the call safe to repeat.
*
* @return array accepted, failed, simulated, errors (list of messages)
*/
public static function send_many(array $numbers, $text, $key, $sender = null)
{
$sender = $sender === null ? (string) INTERWEB_AO_SMS_CENTER_Settings::get('sms_sender') : (string) $sender;
$summary = array('accepted' => 0, 'failed' => 0, 'simulated' => false, 'errors' => array());
foreach (array_chunk(array_values($numbers), self::BATCH_SIZE) as $i => $chunk) {
$body = array('text' => (string) $text, 'messages' => array());
foreach ($chunk as $n) {
$body['messages'][] = array('number' => (string) $n);
}
if ($sender !== '') {
$body['sender'] = $sender;
}
$res = INTERWEB_AO_SMS_CENTER_Api::request('POST', '/v1/sms/messages/batch', $body, array('idempotency_key' => $key . '-' . $i, 'timeout' => 60));
if (is_wp_error($res)) {
$summary['failed'] += count($chunk);
$summary['errors'][] = $res->get_error_message();
continue;
}
$data = is_array($res['data']) ? $res['data'] : array();
if (!empty($data['simulated']) || (isset($data['mode']) && $data['mode'] === 'sandbox')) {
$summary['simulated'] = true;
}
$results = isset($data['results']) && is_array($data['results']) ? $data['results'] : array();
$bad_count = 0;
foreach ($results as $r) {
$bad = !empty($r['error']) || (isset($r['status']) && in_array($r['status'], array('failed', 'rejected'), true));
if (!$bad) {
continue;
}
$bad_count++;
if (count($summary['errors']) < 5) {
$idx = isset($r['index']) ? (int) $r['index'] : -1;
$who = isset($chunk[$idx]) ? INTERWEB_AO_SMS_CENTER_Log::mask_phone($chunk[$idx]) . ': ' : '';
$summary['errors'][] = $who . (!empty($r['error']) ? (string) $r['error'] : (string) $r['status']);
}
}
if (isset($data['accepted'])) {
$summary['accepted'] += (int) $data['accepted'];
$summary['failed'] += isset($data['rejected']) ? (int) $data['rejected'] : $bad_count;
} else {
$summary['accepted'] += count($chunk) - $bad_count;
$summary['failed'] += $bad_count;
}
}
return $summary;
}
/** Test from the settings page. @return array|WP_Error */
public static function test($number)
{
$lang = INTERWEB_AO_SMS_CENTER_I18n::lang();
$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
$text = sprintf(INTERWEB_AO_SMS_CENTER_I18n::in($lang, '%s: this is a test SMS. If it reached you, the site can send SMS.'), $site);
return self::send($number, $text, true, $lang);
}
/** Senders of the account, kept for 10 minutes. @return array|WP_Error|null */
public static function senders()
{
if (INTERWEB_AO_SMS_CENTER_Settings::api_key() === '') {
return null;
}
$hit = get_transient('interweb_ao_sms_center_senders');
if (is_array($hit)) {
return $hit;
}
$res = INTERWEB_AO_SMS_CENTER_Api::request('GET', '/v1/sms/senders', null, array('timeout' => 10));
if (is_wp_error($res)) {
return $res;
}
$list = is_array($res['data']) ? $res['data'] : array();
set_transient('interweb_ao_sms_center_senders', $list, 10 * MINUTE_IN_SECONDS);
return $list;
}
/** SMS balance (not kept: it changes with each send). @return array|WP_Error|null */
public static function balance()
{
if (INTERWEB_AO_SMS_CENTER_Settings::api_key() === '') {
return null;
}
$res = INTERWEB_AO_SMS_CENTER_Api::request('GET', '/v1/sms/balance', null, array('timeout' => 10));
return is_wp_error($res) ? $res : (is_array($res['data']) ? $res['data'] : array());
}
/** Mobile numbers of the WooCommerce customers (billing phone of the user accounts). */
public static function customer_numbers()
{
global $wpdb;
$rows = $wpdb->get_col($wpdb->prepare(
"SELECT meta_value FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value <> '' LIMIT %d",
'billing_phone',
self::MAX_RECIPIENTS
));
return self::numbers(implode("\n", (array) $rows));
}
}