Your IP : 216.73.216.224


Current Path : /var/www/html/plugins/membershipprosms/textlocal/src/Extension/
Upload File :
Current File : /var/www/html/plugins/membershipprosms/textlocal/src/Extension/Textlocal.php

<?php
/**
 * @package        Joomla
 * @subpackage     Membership Pro
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2012 - 2026 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

namespace JoomDonation\MembershipPro\Plugin\SMS\Textlocal\Extension;

use Joomla\CMS\Http\HttpFactory;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\Event\DispatcherInterface;
use Joomla\Event\Event;
use Joomla\Event\SubscriberInterface;

defined('_JEXEC') or die;

class Textlocal extends CMSPlugin implements SubscriberInterface
{
	public static function getSubscribedEvents(): array
	{
		return [
			'onMembershipProSendingSMSReminder' => 'onMembershipProSendingSMSReminder',
		];
	}

	/**
	 * Constructor.
	 *
	 * @param   DispatcherInterface  $dispatcher  The dispatcher
	 * @param   array                $config      An optional associative array of configuration settings
	 */
	public function __construct(DispatcherInterface $dispatcher, array $config)
	{
		parent::__construct($dispatcher, $config);
	}

	public function onMembershipProSendingSMSReminder(Event $event)
	{
		[$rows] = array_values($event->getArguments());

		if (!$this->params->get('api_key'))
		{
			return false;
		}

		foreach ($rows as $row)
		{
			$this->sendSMS([$this->sanitize($row->phone)], $row->sms_message);
		}

		// Return true to tell the system that SMS were successfully sent so that it could update sms sending status for registrants
		return true;
	}

	/**
	 * Method to send SMS messages
	 *
	 * @param   array   $phones
	 * @param   string  $smsMessage
	 */
	private function sendSMS($phones, $smsMessage)
	{
		$http = HttpFactory::getHttp();
		$data = [
			'apikey'  => $this->params->get('api_key'),
			'numbers' => implode(',', $phones),
			'sender'  => $this->params->get('sender', 'TXTLCL'),
			'message' => $smsMessage,
		];

		try
		{
			$response = $http->post('https://api.txtlocal.com/send/', $data);
			// \OSMembershipHelper::logData(JPATH_PLUGINS . '/membershipprosms/textlocal/textlocal.txt', ['code' => $response->code, 'body' => $response->body]);
		}
		catch (\Exception $e)
		{
			\OSMembershipHelper::logData(JPATH_PLUGINS . '/membershipprosms/textlocal/textlocal.txt', $data, $e->getMessage());
		}
	}

	/**
	 * Helper method used to sanitize phone numbers.
	 *
	 * @param   string  $phone  The phone number to sanitize.
	 *
	 * @return    string    The cleansed number.
	 */
	protected function sanitize($phone)
	{
		$phone = trim(str_replace(' ', '', $phone));

		if (substr($phone, 0, 1) != '+')
		{
			if (substr($phone, 0, 2) == '00')
			{
				$phone = '+' . substr($phone, 2);
			}
			else
			{
				$phone = $this->params->get('prefix') . $phone;
			}
		}

		return $phone;
	}
}