<?php
/**
 * @copyright 2021 Double Bastion LLC <www.doublebastion.com>
 *
 * @author Double Bastion LLC
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

declare(strict_types=1);

namespace OCA\SMSRelentless\Controller;

use OCP\IRequest;
use OCP\AppFramework\Controller;
use OCA\SMSRelentless\Service\SmsrelentlessService;
use OCP\AppFramework\App;
use OC\Http\Client\Client;
use OCP\Files\SimpleFS\ISimpleFile;
use OCP\Files\SimpleFS\ISimpleFolder;
use OCP\IL10N;
use OCP\Files\Folder;
use OCP\IConfig;
use OC\Files\Filesystem;
use OC\Files\View;
use \ReflectionClass;
use \FilesystemIterator;
use \DateTime;
use \DateInterval;
use OCP\AppFramework\Http\DataResponse;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use Plivo\RestClient;
use OCP\IURLGenerator;
use OCP\Share\IManager;
use OCP\Constants;



class SmsrelentlessController extends Controller {

    private $service;
    private $config;
    private $userId;
    private $folder;
    private $filesystem;
    private $view;
    private $urlGenerator;
    private $shareManager;

    public function __construct($appName, IRequest $request, SmsrelentlessService $service, IConfig $config, $userId, Folder $folder, Filesystem $filesystem, View $view, IURLGenerator $urlGenerator, IManager $shareManager) {
        parent::__construct($appName, $request);
        $this->service = $service;
        $this->config = $config;
        $this->userId = $userId;
        $this->folder = $folder;
        $this->filesystem = $filesystem;
        $this->view = $view;
	$this->urlGenerator = $urlGenerator;
	$this->shareManager = $shareManager;
    }


    /**
     * @NoAdminRequired
     */
    public function object_to_array($obj) {
        if(is_object($obj)) $obj = (array)$this->dismount($obj);
        if(is_array($obj)) {
           $new = array();
           foreach($obj as $key => $val) {
               $new[$key] = $this->object_to_array($val);
           }
        }
        else $new = $obj;
        return $new;
    }


    /**
     * @NoAdminRequired
     */
    public function dismount($object) {
        $reflectionClass = new ReflectionClass(get_class($object));
        $array = array();
        foreach ($reflectionClass->getProperties() as $property) {
           $property->setAccessible(true);
           $array[$property->getName()] = $property->getValue($object);
           $property->setAccessible(false);
        }
        return $array;
    }


    /**
     * @NoAdminRequired
     */
    public function getbalancetel($userId) {

        $telsmsapicred = $this->service->getapicredentials($this->userId);

        $telapikey = $telsmsapicred[0];
        $ch = curl_init();
        $headerstel = array("Content-Type: application/json", "Accept: application/json", "Authorization: Bearer ".$telapikey);

        curl_setopt($ch, CURLOPT_URL, "https://api.telnyx.com/v2/balance");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerstel);
        $responsetel = curl_exec($ch);
        $recdatatel = json_decode($responsetel, TRUE);
        $telbalresponse = $recdatatel['data']['balance'];
        $currentbalancetel = round(floatval($telbalresponse), 3);
        curl_close($ch);

        return $currentbalancetel;
    }


    /**
     * @NoAdminRequired
     */
    public function getbalancenex($userId) {

        $smsapicred = $this->service->getapicredentials($this->userId);
        $smsapikey = $smsapicred[5];
        $smsapisecret = $smsapicred[6];

        if ($smsapikey == '' || $smsapisecret == '') {
            $currentbalancenex = "N/A";
        } else {
            $getmesdata = "https://".$smsapikey.":".$smsapisecret."@api.plivo.com/v1/Account/".$smsapikey."/";
            $mesdata = file_get_contents($getmesdata);
            $datainit = json_decode($mesdata);
            $balancenex = $datainit->cash_credits;
            $currentbalancenex = round(floatval($balancenex), 3);
        }
        return $currentbalancenex;
    }


    /**
     * @NoAdminRequired
     */
    public function getbalancetwil($userId) {

        $smsapicred = $this->service->getapicredentials($this->userId);
        $smsapisid = $smsapicred[15];
        $smsapitoken = $smsapicred[16];

        if ($smsapisid == '' || $smsapitoken == '') {
            $currentbalancetwil = "N/A";
        } else {

            $twilbalance = json_decode(file_get_contents("https://".$smsapisid.":".$smsapitoken."@api.twilio.com/2010-04-01/Accounts/".$smsapisid."/Balance.json"));
            $balancetwil = $twilbalance->balance;

            $currentbalancetwil = round(floatval($balancetwil), 3);
        }
        return $currentbalancetwil;
    }


    /**
     * @NoAdminRequired
     */
    public function getbalanceflow($userId) {

        $currentbalanceflow = 'n/a';

        return $currentbalanceflow;
    }


    /**
     * @NoAdminRequired
     */
    public function getsmsnumbers($userId) {

        $smsapicred = $this->service->getapicredentials($this->userId);

        $telnyxkey = $smsapicred[0];

        $nexapikey = $smsapicred[5];
        $nexapisecret = $smsapicred[6];

        $twilapikey = $smsapicred[15];
        $twilapisecret = $smsapicred[16];

        $flowapikey = $smsapicred[20];
        $flowapisecret = $smsapicred[21];

        $telsendernameinit = $smsapicred[9];
        $nexsendernameinit = $smsapicred[10];
        $twilsendernameinit = $smsapicred[19];

        $telsendername = "Tx: " . $telsendernameinit;
        $nexsendername = "Pl: " . $nexsendernameinit;
        $twilsendername = "Tw: " . $twilsendernameinit;

        // Get Telnyx phone numbers
        if ($telnyxkey != '') {

           \Telnyx\Telnyx::setApiKey($telnyxkey);
           $telnumbers = \Telnyx\MessagingPhoneNumber::All();

           $telnumbersarr = $this->object_to_array($telnumbers);
           $telnmbrs = [];

           foreach ($telnumbersarr['_originalValues'] as $nmbkey => $nmbvalue) {
              if (is_int($nmbkey)) {
                 foreach ($nmbvalue as $nkey => $nvalue) {
                    if ($nkey == 'phone_number') {
                       $telnmbrs[] = "Tx: " . $nvalue;
                    }
                 }
              }
           }

        } else { $telnmbrs = []; }

        // Get Plivo phone numbers
        if ($nexapikey != '' && $nexapisecret != '') {

           $getacdata = "https://".$nexapikey.":".$nexapisecret."@api.plivo.com/v1/Account/".$nexapikey."/Number/";
           $acdata = file_get_contents($getacdata);
           $datainit = json_decode($acdata, true);

           $findata = $this->object_to_array($datainit);

           $nexcurrentnmbrs = [];

           foreach ($findata['objects'] as $smskey => $smsvalue) {
                   if (is_array($smsvalue)) {
                         foreach ($smsvalue as $smskey2 => $smsvalue2) {
                               if ($smskey2 == 'number') {
                                   $nexcurrentnmbrs[] = "Pl: +" . $smsvalue2;
                               }
                         }
                   }
           }


        } else { $nexcurrentnmbrs = []; }

        // Get Twilio phone numbers
        if ($twilapikey != '' && $twilapisecret != '') {

            $twilnumbers = json_decode(file_get_contents("https://".$twilapikey.":".$twilapisecret."@api.twilio.com/2010-04-01/Accounts/".$twilapikey."/IncomingPhoneNumbers.json"), true);
            $twilactivenmbrs = $twilnumbers['incoming_phone_numbers'];

            $twilcurrentnmbrs = [];
            foreach ($twilactivenmbrs as $twnbkey => $twnbvalue) {
                 if (is_array($twnbvalue)) {
                     foreach ($twnbvalue as $twfkey => $twfvalue) {
                          if ($twfkey == 'phone_number') {
                              $twilcurrentnmbrs[] = "Tw: " . $twfvalue;
                          }
                     }
                 }
            }

        } else { $twilcurrentnmbrs = []; }

        // Get Flowroute phone numbers
        if ($flowapikey != '' && $flowapisecret != '') {

            $flnbrsresult = json_decode(file_get_contents("https://".$flowapikey.":".$flowapisecret."@api.flowroute.com/v2/numbers"));
            $flnbrsarr = $flnbrsresult->data;
            $flowcurrentnmbrs = [];
            foreach ($flnbrsarr as $flkey => $flitem) {
                     $flowcurrentnmbrs[] = "Fl: +" . $flitem->id;
            }

        } else { $flowcurrentnmbrs = []; }


        $telsenderarr = [0 => $telsendername];
        $nexsenderarr = [0 => $nexsendername];
        $twilsenderarr = [0 => $twilsendername];

        $currentnmbrs = array_merge($telnmbrs, $nexcurrentnmbrs, $twilcurrentnmbrs, $flowcurrentnmbrs, $telsenderarr, $nexsenderarr, $twilsenderarr);

        return $currentnmbrs;
    }


    /**
     * @NoAdminRequired
     */
    public function cleantempdir($userId) {

        // Create the temporary folder if it doesn't exist
        if ($this->folder->nodeExists('SMS_Relentless/temp_files') == false) {
            $this->folder->newFolder('SMS_Relentless/temp_files');
        }
        $datadir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/';
        $targetdir = $datadir . $this->userId . "/files/SMS_Relentless/temp_files";
        $fileSystemIterator = new FilesystemIterator($targetdir);

        $dirfiles = [];
        foreach ($fileSystemIterator as $fileInfo){
                 $dirfiles[] = $fileInfo->getFilename();
        }

        foreach ($dirfiles as $key => $indfile) {
                 $thisuserroot = $this->view->getRoot();
                 $tempfile = $thisuserroot . "/SMS_Relentless/temp_files/" . $indfile;
                 $removetmpfile = $this->filesystem->unlink($tempfile);
        }
     }


    /**
     * @NoAdminRequired
     */
    public function uploadNumbersFile($userId, $uploadfileforsms) {

        // Create the temporary folder if it doesn't exist
        if ($this->folder->nodeExists('SMS_Relentless/temp_files') == false) {
            $this->folder->newFolder('SMS_Relentless/temp_files');
        }

        // First delete any file that has been previously uploaded
        $datadir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/';
        $targetdir = $datadir . $this->userId . "/files/SMS_Relentless/temp_files";
        $fileSystemIterator = new FilesystemIterator($targetdir);

        $dirfiles = [];
        foreach ($fileSystemIterator as $fileInfo){
                 $dirfiles[] = $fileInfo->getFilename();
        }

        foreach ($dirfiles as $key => $indfile) {
                 $thisuserroot = $this->view->getRoot();
                 $tempfile = $thisuserroot . "/SMS_Relentless/temp_files/" . $indfile;
                 $removetmpfile = $this->filesystem->unlink($tempfile);
        }

        // Upload the new file
        $fileContent = file_get_contents($_FILES['uploadfileforsms']['tmp_name']);
        $fileName = $_FILES['uploadfileforsms']['name'];

        $userroot = $this->view->getRoot();
        $targetfile = $userroot . "/SMS_Relentless/temp_files/" . $fileName;

        $target = $this->folder->newFile($targetfile);
        $target->putContent($fileContent);

        // Extract the phone numbers from the file
        $numberarraysec = str_replace(array(";", "|", "\r\n", "\r", "\n", "\t"), ",", $fileContent);
        $numberarraytert = preg_replace("/[^0-9,]/", "", $numberarraysec);
        $numberarrayfourth = explode(",", $numberarraytert);
        $numberarrayfifth = array_filter(array_map('trim', $numberarrayfourth));
        $numberarray = array_unique($numberarrayfifth);

        return $numberarray;
    }


    /**
     * @NoAdminRequired
     */
    public function uploadfile($uploadfileformms) {

           $fileContent = file_get_contents($_FILES['uploadfileformms']['tmp_name']);
           $fileName = $_FILES['uploadfileformms']['name'];
           $fileSizeinit = $_FILES['uploadfileformms']['size'];
           $fileSize = $fileSizeinit / 1024;

           if ($this->folder->nodeExists('SMS_Relentless/temp_files') == false) {
               $this->folder->newFolder('SMS_Relentless/temp_files');
           }

           $userroot = $this->view->getRoot();
           $targetfile = $userroot . "/SMS_Relentless/temp_files/" . $fileName;

           $target = $this->folder->newFile($targetfile);
           $target->putContent($fileContent);

           // Get the cumulative files size of the uploaded files
           $datadir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/';
           $targetdir = $datadir . $this->userId . "/files/SMS_Relentless/temp_files";

           $fileSystemIterator = new FilesystemIterator($targetdir);

           $dirfiles = [];
           foreach ($fileSystemIterator as $fileInfo){
                    $dirfiles[] = $fileInfo->getFilename();
           }

           $totalflsizeinit = 0;
           foreach ($dirfiles as $key => $indfile) {
                    $fileSizeinit = $this->filesystem->filesize($userroot . "/SMS_Relentless/temp_files/" . $indfile);
                    $mbSize = round($fileSizeinit / 1024, 4);
                    $totalflsizeinit += $mbSize;
           }

           $totalflsize = round($totalflsizeinit, 4);

           return $totalflsize;
    }


    /**
     * @NoAdminRequired
     */
    public function pickfile($path) {

           if ($this->folder->nodeExists('SMS_Relentless/temp_files') == false) {
               $this->folder->newFolder('SMS_Relentless/temp_files');
           }

           $datadir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/';

           $fltgt = $datadir . $this->userId . "/files" . $path;

           $fileContent = file_get_contents($fltgt);

           $pkfilesize = round(filesize($fltgt) / 1024, 4);

           $patharr = explode("/", $path);

           $revarr = array_reverse($patharr);

           $relflpath = "/SMS_Relentless/temp_files/" . $revarr[0]; 

           $target = $this->folder->newFile($relflpath);

           $target->putContent($fileContent);

           // Get the cumulative files size of the uploaded files
           $targetdir = $datadir . $this->userId . "/files/SMS_Relentless/temp_files";

           $fileSystemIterator = new FilesystemIterator($targetdir);

           $dirfiles = [];
           foreach ($fileSystemIterator as $fileInfo) {
                    $dirfiles[] = $fileInfo->getFilename();
           }

           $totalflsizeinit = 0;

           foreach ($dirfiles as $key => $indfile) {

                    $fileSizeinit = $this->filesystem->filesize("/SMS_Relentless/temp_files/" . $indfile);
                    $mbSize = round($fileSizeinit / 1024, 4);
                    $totalflsizeinit += $mbSize;
           }

           $totalflsize = round($totalflsizeinit, 4);

           $pickresult = [$totalflsize, $pkfilesize];

           return $pickresult;
    }


    /**
     * @NoAdminRequired
     */
    public function removeupfile($removedfilename) {

           $tmpfl = "/" . $this->userId . "/files/SMS_Relentless/temp_files/" . $removedfilename;

           $removefile = $this->view->unlink($tmpfl);

           // Get the cumulative files size of the uploaded files
           $datadir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/';
           $targetdir = $datadir . $this->userId . "/files/SMS_Relentless/temp_files";
           $fileSystemIterator = new FilesystemIterator($targetdir);

           $dirfiles = [];
           foreach ($fileSystemIterator as $fileInfo){
                    $dirfiles[] = $fileInfo->getFilename();
           }

           $totalflsizeinit = 0;

           foreach ($dirfiles as $key => $indfile) {
                    $fileSizeinit = $this->filesystem->filesize("/SMS_Relentless/temp_files/" . $indfile);
                    $mbSize = round($fileSizeinit / 1024, 4);
                    $totalflsizeinit += $mbSize;
           }

           $totalflsize = round($totalflsizeinit, 4);

           return $totalflsize;
    }


    /**
     * @NoAdminRequired
     */
    public function sendsmstel($userId, $receiversPhoneNbs, $fromsender, $waitinterval, $sentsmstext, $ismms, $mmsfiles) {
         $telsmsapicred = $this->service->getapicredentials($this->userId);
         $telnyxkey = $telsmsapicred[0];
         $teldelrecurl = $telsmsapicred[3];
         $messagingprofid = $telsmsapicred[4];

         \Telnyx\Telnyx::setApiKey($telnyxkey);

         $microinterval = $waitinterval * 1000;

         foreach ($receiversPhoneNbs as $keytel => $tonumber) {

             usleep($microinterval);

             $messagedate = date("Y-m-d H:i:s");

             if ($ismms == 0) {

                 if (preg_match('/[A-Za-z]+/', $fromsender)) {
                     $message = \Telnyx\Message::Create(["from" => $fromsender, "to" => $tonumber, "text" => $sentsmstext, "webhook_url" => $teldelrecurl, "messaging_profile_id" => $messagingprofid]);
                 } else {
                     $message = \Telnyx\Message::Create(["from" => $fromsender, "to" => $tonumber, "text" => $sentsmstext, "webhook_url" => $teldelrecurl]);
                 }

                 $messagetexttel = $sentsmstext;

             } else {

                 $mediaURLarr = [];
                 $includedMediaFiles = '';

                 for ($p = 0; $p < count($mmsfiles); $p++ ) {

                      $userroot = $this->view->getRoot();
                      $filetoshare = $userroot . "/SMS_Relentless/temp_files/".$mmsfiles[$p]."";

                      $flsharetarget = $this->folder->newFile($filetoshare);

	              $share = $this->shareManager->newShare();
	              $share->setNode($flsharetarget);
	              $share->setPermissions(Constants::PERMISSION_READ);
	              $share->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK);
	              $share->setSharedBy($this->userId);
                      $expirydate = DateTime::createFromFormat('Y-m-d H:i:s', $messagedate);
                      $expirydate->add(new \DateInterval('P1D'));
                      $share->setExpirationDate($expirydate);
                      $shared = $this->shareManager->createShare($share);
                      $shareToken = $shared->getToken();

                      $mediaURLarr[] = "https://cloud.webpublicist.net/s/".$shareToken."/download/".$mmsfiles[$p]."";
                      $includedMediaFiles .= "https://cloud.webpublicist.net/s/".$shareToken."/download/".$mmsfiles[$p] . "<br><br>";
                 }

                 if (preg_match('/[A-Za-z]+/', $fromsender)) {
                     $message = \Telnyx\Message::Create(["from" => $fromsender, "to" => $tonumber, "text" => $sentsmstext, "webhook_url" => $teldelrecurl, "messaging_profile_id" => $messagingprofid, "subject" => "MMS", "media_urls" => $mediaURLarr]);
                 } else {
                     $message = \Telnyx\Message::Create(["from" => $fromsender, "to" => $tonumber, "text" => $sentsmstext, "webhook_url" => $teldelrecurl, "subject" => "MMS", "media_urls" => $mediaURLarr]);
                 }

                 $messagetexttel = $sentsmstext . "<br><br><br>--- File(s) included in MMS ---<br><br>" . $includedMediaFiles;
             }

             $messageid = $message['id'];
             $messagefrom = "Telnyx: " . $fromsender;
             $messageto = $tonumber;
             $messagenetwork = null;
             $messageprice = null;
             $messagestatus = $message['to'][0]['status'];
             $messagedelivery = null;

             $sentmessagearr = [$messageid, $messagedate, $messagefrom, $messageto, $messagenetwork, $messageprice, $messagestatus, $messagedelivery, $messagetexttel];

             $this->service->insertsentsms($this->userId, $sentmessagearr);

         }
    }


    /**
     * @NoAdminRequired
     */
    public function sendsmsnex($userId, $receiversPhoneNbs, $fromsender, $waitinterval, $sentsmstext, $ismms, $mmsfiles) {

         $smsapicred = $this->service->getapicredentials($this->userId);

         $smsapikey = $smsapicred[5];
         $smsapisecret = $smsapicred[6];
         $smsapideliveryrecurl = $smsapicred[8];

         $microinterval = $waitinterval * 1000;

         foreach ($receiversPhoneNbs as $keynex => $tonumber) {

             usleep($microinterval);

             $messagedatepl = date("Y-m-d H:i:s");

             if ($ismms == 0) {

                 $client = new RestClient($smsapikey, $smsapisecret);
                 $response = $client->messages->create($fromsender,[$tonumber],$sentsmstext,["url" => $smsapideliveryrecurl]);
                 $messagetextpl = $sentsmstext;
	         $messageidinit = $response->getmessageUuid(0);
                 $messageid = $messageidinit[0];

                 if (property_exists($response, 'error')) { 
                     $messagestatus = "Error: " . $response->error;
                 } else { $messagestatus = 'The message has been accepted for delivery.'; }

             } else {

                 $mediaURLarr = [];
                 $includedMediaFiles = '';

                 for ($p = 0; $p < count($mmsfiles); $p++ ) {

                      $userroot = $this->view->getRoot();
                      $filetoshare = $userroot . "/SMS_Relentless/temp_files/".$mmsfiles[$p]."";

                      $flsharetarget = $this->folder->newFile($filetoshare);

	              $share = $this->shareManager->newShare();
	              $share->setNode($flsharetarget);
	              $share->setPermissions(Constants::PERMISSION_READ);
	              $share->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK);
	              $share->setSharedBy($this->userId);
                      $expirydate = DateTime::createFromFormat('Y-m-d H:i:s', $messagedatepl);
                      $expirydate->add(new \DateInterval('P1D'));
                      $share->setExpirationDate($expirydate);
                      $shared = $this->shareManager->createShare($share);
                      $shareToken = $shared->getToken();

                      $mediaURLarr[] = "https://cloud.webpublicist.net/s/".$shareToken."/download/".$mmsfiles[$p]."";
                      $includedMediaFiles .= "https://cloud.webpublicist.net/s/".$shareToken."/download/".$mmsfiles[$p] . "<br><br>";
                 }

		 $datatosendpl = ["src" => $fromsender, "dst" => $tonumber, "text" => $sentsmstext, "url" => $smsapideliveryrecurl, "type" => "mms", "media_urls" => $mediaURLarr];
		 $postedparamspl = json_encode($datatosendpl);

		 $chpl = curl_init();
		 curl_setopt($chpl, CURLOPT_URL, 'https://'.$smsapikey.':'.$smsapisecret.'@api.plivo.com/v1/Account/'.$smsapikey.'/Message/');
		 curl_setopt($chpl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
		 curl_setopt($chpl, CURLOPT_TIMEOUT, 300);
		 curl_setopt($chpl, CURLOPT_RETURNTRANSFER, 1);
		 curl_setopt($chpl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		 curl_setopt($chpl, CURLOPT_POST, 1);
		 curl_setopt($chpl, CURLOPT_POSTFIELDS, $postedparamspl);
		 $resultpl = curl_exec ($chpl);
		 $statusCodepl = curl_getinfo($chpl, CURLINFO_HTTP_CODE);
		 curl_close ($chpl);

		 $decresultpl = json_decode($resultpl);

                 if (property_exists($decresultpl, 'message_uuid')) {
                     $messageidinit = $decresultpl->message_uuid;
                     $messageid = $messageidinit[0];
                 }

	         if (in_array($statusCodepl, [200, 201, 202, 203, 204, 205, 206])) {

                     if (property_exists($decresultpl, 'error')) {
                         $messagestatus = "Error: " . $decresultpl->error;
                     } else { $messagestatus = 'The message has been accepted for delivery.'; }

                 } else { $messagestatus = 'An error occurred while trying to send the message.'; }

                 $messagetextpl = $sentsmstext . "<br><br><br>--- File(s) included in MMS ---<br><br>" . $includedMediaFiles;
             }

             if (preg_match('/[A-Za-z]+/', $fromsender)) {
                 $messagefrom = "Plivo: " . $fromsender;
             } else { $messagefrom = "Plivo: +" . $fromsender; }

             $messageto = $tonumber;
             $messagenetwork = '';
             $messageprice = '';

             $messagedelivery = '';

             $sentmessagearr = [$messageid, $messagedatepl, $messagefrom, $messageto, $messagenetwork, $messageprice, $messagestatus, $messagedelivery, $messagetextpl];

             $this->service->insertsentsms($this->userId, $sentmessagearr);
         }
    }


    /**
     * @NoAdminRequired
     */
    public function sendsmstwil($userId, $receiversPhoneNbs, $fromsender, $waitinterval, $sentsmstext, $ismms, $mmsfiles) {

         $smsapicred = $this->service->getapicredentials($this->userId);

         $sid = $smsapicred[15];
         $token = $smsapicred[16];
         $smsapirecurltw = $smsapicred[18];

         $microinterval = $waitinterval * 1000;

         foreach ($receiversPhoneNbs as $keytwil => $tonumbertw) {

             usleep($microinterval);

             $messagedatetw = date("Y-m-d H:i:s");

             if ($ismms == 0) {

                  $datatoposttw = [["To" => $tonumbertw, "From" => $fromsender, "Body" => $sentsmstext, "StatusCallback" => $smsapirecurltw]];
                  $sentsmstextfintw = $sentsmstext;

             } else {

                 $mediaURLs = [];

                 for ($p = 0; $p < count($mmsfiles); $p++ ) {

                      $userroot = $this->view->getRoot();
                      $filetoshare = $userroot . "/SMS_Relentless/temp_files/".$mmsfiles[$p]."";

                      $flsharetarget = $this->folder->newFile($filetoshare);

	              $share = $this->shareManager->newShare();
	              $share->setNode($flsharetarget);
	              $share->setPermissions(Constants::PERMISSION_READ);
	              $share->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK);
	              $share->setSharedBy($this->userId);
                      $expirydate = DateTime::createFromFormat('Y-m-d H:i:s', $messagedatetw);
                      $expirydate->add(new \DateInterval('P1D'));
                      $share->setExpirationDate($expirydate);
                      $shared = $this->shareManager->createShare($share);
                      $shareToken = $shared->getToken();

                      $mediaURLs[] = "https://cloud.webpublicist.net/s/".$shareToken."/download/".$mmsfiles[$p]."";
                 }

                 $datatoposttw = [["To" => $tonumbertw, "From" => $fromsender, "Body" => $sentsmstext, "StatusCallback" => $smsapirecurltw]];
                 $includedMediaFiles = '';

                 for ($m = 0; $m < count($mediaURLs); $m++) {
                      array_push($datatoposttw, ["MediaUrl" => $mediaURLs[$m]]);
                      $includedMediaFiles .= $mediaURLs[$m] . "<br><br>";
                 }

                 $sentsmstextfintw = $sentsmstext . "<br><br><br>--- File(s) included in MMS ---<br><br>" . $includedMediaFiles;
             }

             $postedsendingfl = implode('&', array_map('http_build_query', $datatoposttw));

	     $chtw = curl_init();
	     curl_setopt($chtw, CURLOPT_URL, 'https://api.twilio.com/2010-04-01/Accounts/'.$sid.'/Messages.json');
	     curl_setopt($chtw, CURLOPT_TIMEOUT, 300);
	     curl_setopt($chtw, CURLOPT_RETURNTRANSFER, 1);
	     curl_setopt($chtw, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
             curl_setopt($chtw, CURLOPT_USERPWD, "$sid:$token");
	     curl_setopt($chtw, CURLOPT_POST, 1);
             curl_setopt($chtw, CURLOPT_POSTFIELDS, $postedsendingfl);

	     $resulttw = curl_exec ($chtw);
	     $statusCodetw = curl_getinfo($chtw, CURLINFO_HTTP_CODE);
	     curl_close ($chtw);

             $decresulttw = json_decode($resulttw);

             if ($resulttw) {
                 $messageidtw = $decresulttw->sid;
             } else { $messageidtw = ''; }

	     if (in_array($statusCodetw, [200, 201, 202, 203, 204, 205, 206])) {
                 $messagestatustw = 'The message has been accepted for delivery.';
             } else {
                 $messagestatustw = 'An error occurred while trying to send the message.';
             }

             if (preg_match('/[A-Za-z]+/', $fromsender)) {
                 $messagefromtw = "Twilio: " . $fromsender;
             } else { $messagefromtw = "Twilio: " . $fromsender; }

             $messagenetworktw = '';
             $messagepricetw = '';
             $messagedeliverytw = '';


             $sentmessagearr = [$messageidtw, $messagedatetw, $messagefromtw, $tonumbertw, $messagenetworktw, $messagepricetw, $messagestatustw, $messagedeliverytw, $sentsmstextfintw];

             $this->service->insertsentsms($this->userId, $sentmessagearr);
         }

    }


    /**
     * @NoAdminRequired
     */
    public function sendsmsflow($userId, $receiversPhoneNbs, $fromsender, $waitinterval, $sentsmstext, $ismms, $mmsfiles) {

         $smsapicredfl = $this->service->getapicredentials($this->userId);

         $flowapikey = $smsapicredfl[20];
         $flowapisecret = $smsapicredfl[21];
         $flowdelrecurl = $smsapicredfl[23];
         $sentsmstextproc = str_replace('"','\\"', $sentsmstext);

         $microinterval = $waitinterval * 1000;

         foreach ($receiversPhoneNbs as $keyflow => $tonumberfl) {

             usleep($microinterval);

             $messagedatefl = date("Y-m-d H:i:s");

             if ($ismms == 0) {

                 $messagetextfinfl = $sentsmstext;
                 $postedparamsfl = json_encode(["to" => $tonumberfl, "from" => $fromsender, "body" => $sentsmstextproc, "dlr_callback" => $flowdelrecurl]);

             } else {

		 $mediaurlsarr = [];

		 for ($p = 0; $p < count($mmsfiles); $p++ ) {

		      $userroot = $this->view->getRoot();
		      $filetoshare = $userroot . "/SMS_Relentless/temp_files/".$mmsfiles[$p]."";

		      $flsharetarget = $this->folder->newFile($filetoshare);

		      $share = $this->shareManager->newShare();
		      $share->setNode($flsharetarget);
		      $share->setPermissions(Constants::PERMISSION_READ);
		      $share->setShareType(\OC\Share\Constants::SHARE_TYPE_LINK);
		      $share->setSharedBy($this->userId);
                      $expirydate = DateTime::createFromFormat('Y-m-d H:i:s', $messagedatefl);
                      $expirydate->add(new \DateInterval('P1D'));
                      $share->setExpirationDate($expirydate);
		      $shared = $this->shareManager->createShare($share);
		      $shareToken = $shared->getToken();

		      $mediaurlsarr[] = "https://cloud.webpublicist.net/s/".$shareToken."/download/".$mmsfiles[$p]."";
		 }

		 $includedMediaFiles = '';

		 for ($m = 0; $m < count($mediaurlsarr); $m++) {
		      $includedMediaFiles .= $mediaurlsarr[$m] . "<br><br>";
		 }

                 $messagetextfinfl = $sentsmstext . "<br><br><br>--- File(s) included in MMS ---<br><br>" . $includedMediaFiles;

                 $postedparamsfl = json_encode(["to" => $tonumberfl, "from" => $fromsender, "body" => $sentsmstextproc, "dlr_callback" => $flowdelrecurl, "media_urls" => $mediaurlsarr]);
             }


	     $chfl = curl_init();
	     curl_setopt($chfl, CURLOPT_URL, 'https://'.$flowapikey.':'.$flowapisecret.'@api.flowroute.com/v2.1/messages');
	     curl_setopt($chfl, CURLOPT_HTTPHEADER, array("Content-Type: application/vnd.api+json"));
	     curl_setopt($chfl, CURLOPT_TIMEOUT, 300);
	     curl_setopt($chfl, CURLOPT_RETURNTRANSFER, 1);
	     curl_setopt($chfl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	     curl_setopt($chfl, CURLOPT_POST, 1);
             curl_setopt($chfl, CURLOPT_POSTFIELDS, $postedparamsfl);
	     $resultfl = curl_exec ($chfl);
	     $statusCode = curl_getinfo($chfl, CURLINFO_HTTP_CODE);
	     curl_close ($chfl);

             $decresultfl = json_decode($resultfl);

             if ($resultfl) {
                 $messageidfl = $decresultfl->data->id;
             } else { $messageidfl = ''; }

	     if (in_array($statusCode, [200, 201, 202, 203, 204, 205, 206])) {
                 $messagestatusfl = 'The message has been accepted for delivery.'; 
             } else { 
                 $messagestatusfl = 'An error occurred while trying to send the message.'; 
             }

             if (preg_match('/[A-Za-z]+/', $fromsender)) {
                 $messagefromfl = "Flowroute: " . $fromsender;
             } else { $messagefromfl = "Flowroute: " . $fromsender; }

             $messagetofl = $tonumberfl;
             $messagenetworkfl = '';
             $messagepricefl = '';
             $messagedeliveryfl = '';

             $sentmessagearr = [$messageidfl, $messagedatefl, $messagefromfl, $messagetofl, $messagenetworkfl, $messagepricefl, $messagestatusfl, $messagedeliveryfl, $messagetextfinfl];

             $this->service->insertsentsms($this->userId, $sentmessagearr);
         }

    }


    /**
     * @NoAdminRequired
     */
    public function saveoldrecrows($userId, $oldrecRows) {

           // Create the folder for removed messages if it doesn't exist
           if ($this->folder->nodeExists('SMS_Relentless/removed_received_messages') == false) {
               $this->folder->newFolder('SMS_Relentless/removed_received_messages');
           }
           $savecheck = 0;

           if (count($oldrecRows) > 1) {
               $msfileContent = implode("", $oldrecRows);

               $delrowsdate = date("Y-m-d_H-i-s");
               $msfileName = "Received_Messages_Deleted_On_" . $delrowsdate . ".csv";

               $userroot = $this->view->getRoot();
               $targetfile = $userroot . "/SMS_Relentless/removed_received_messages/" . $msfileName;

               $target = $this->folder->newFile($targetfile);
               $target->putContent($msfileContent);

               if ($this->filesystem->file_get_contents($targetfile) != '') {
                   $savecheck = 1;
               }
           }

           return $savecheck;
    }


    /**
     * @NoAdminRequired
     */
    public function saveoldsentrows($userId, $oldsentRows) {

           // Create the folder for removed messages if it doesn't exist
           if ($this->folder->nodeExists('SMS_Relentless/removed_sent_messages') == false) {
               $this->folder->newFolder('SMS_Relentless/removed_sent_messages');
           }
           $savesentcheck = 0;

           if (count($oldsentRows) > 1) {
               $sntfileContent = implode("", $oldsentRows);

               $delsentrowsdate = date("Y-m-d_H-i-s");
               $sntfileName = "Sent_Messages_Deleted_On_" . $delsentrowsdate . ".csv";

               $userroot = $this->view->getRoot();
               $snttargetfile = $userroot . "/SMS_Relentless/removed_sent_messages/" . $sntfileName;

               $snttarget = $this->folder->newFile($snttargetfile);
               $snttarget->putContent($sntfileContent);

               if ($this->filesystem->file_get_contents($snttargetfile) != '') {
                   $savesentcheck = 1;
               }
           }

           return $savesentcheck;
    }


    /**
     * @NoAdminRequired
     */
    public function getreceivedtable($userId) {
           return $this->service->getreceivedtable($this->userId);
    }

    /**
     * @NoAdminRequired
     */
    public function getreceivedtablefordel($userId) {
           return $this->service->getreceivedtablefordel($this->userId);
    }

    /**
     * @NoAdminRequired
     */
    public function removerecrows($userId, $recmessagedbIDs) {
           return $this->service->removerecrows($this->userId, $recmessagedbIDs);
    }

    /**
     * @NoAdminRequired
     */
    public function getsenttable($userId) {
           return $this->service->getsenttable($this->userId);
    }

    /**
     * @NoAdminRequired
     */
    public function getsenttablefordel($userId) {
           return $this->service->getsenttablefordel($this->userId);
    }

    /**
     * @NoAdminRequired
     */
    public function removesentrows($userId, $sentmessagedbIDs) {
           return $this->service->removesentrows($this->userId, $sentmessagedbIDs);
    }

    /**
     * @NoAdminRequired
     */
    public function getmessagesperpage($userId) {
           return $this->service->getmessagesperpage($this->userId);
    }

    /**
     * @NoAdminRequired
     */
    public function getdelrecsettings($userId) {
           return $this->service->getdelrecsettings($this->userId);
    }

    /**
     * @NoAdminRequired
     */
    public function getsettings($userId) {
           return $this->service->getsettings($this->userId);
    }

    /**
     * @NoAdminRequired
     */
    public function updatesettings($userId, $telapiKey, $telPubKey, $telapiUrlRec, $telapiUrl, $messagingProfileId, $nexapiKey, $nexapiSecret, $nexapiUrlRec, $nexapiUrl, $telSenderName, $nexSenderName, $messagesperpage, $getNotify, $notificationEmail, $getsmsinemail, $twilapiKey, $twilapiSecret, $twilapiUrlRec, $twilapiUrl, $twilSenderName, $flowapiKey, $flowapiSecret, $flowapiUrlRec, $flowapiUrl) {
           return $this->service->updatesettings($this->userId, $telapiKey, $telPubKey, $telapiUrlRec, $telapiUrl, $messagingProfileId, $nexapiKey, $nexapiSecret, $nexapiUrlRec, $nexapiUrl, $telSenderName, $nexSenderName, $messagesperpage, $getNotify, $notificationEmail, $getsmsinemail, $twilapiKey, $twilapiSecret, $twilapiUrlRec, $twilapiUrl, $twilSenderName, $flowapiKey, $flowapiSecret, $flowapiUrlRec, $flowapiUrl);
    }

}
