<?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\AppFramework\ApiController;
use OCP\IRequest;
use OCA\SMSRelentless\Service\SmsrelentlessService;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\IUserSession;
use OCP\IConfig;
use \DateTime;
use OCP\AppFramework\Controller;
use OCP\Files\IAppData;
use OCP\AppFramework\App;
use OCP\Files\NotPermittedException;
use \ReflectionClass;
use OCP\Notification;
use OCP\Notification\INotification;
use OCP\Notification\IManager;
use OCP\Notification\IAction;
use Plivo\RestClient;
use Plivo\Util\signatureValidation;


class AuthorApiController extends ApiController {

    private $service;
    private $userId;
    private $config;

    public function __construct($appName, IRequest $request, SmsrelentlessService $service, $userId, IConfig $config) {
        parent::__construct(
            $appName,
            $request,
            'PUT, POST, GET, DELETE, PATCH',
            'Authorization, Content-Type, Accept',
            1728000);

        $this->service = $service;
        $this->userId = $userId;
        $this->config = $config;
    }


    /**
     * @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 verifyHeader($receiveddata, $signature_header, $timestamp, $public_key = '', $tolerance = null ) {
        // Typecast timestamp to int for comparisons
        $timestamp = (int)$timestamp;

        // Check if timestamp is within tolerance
        if (($tolerance > 0) && (\abs(\time() - $timestamp) > $tolerance)) {
             return false;
        } else {

            // Convert base64 string to bytes for sodium crypto functions
            $public_key_bytes = base64_decode($public_key);
            $signature_header_bytes = base64_decode($signature_header);

            // Construct a message to test against the signature header using the timestamp and payload
            $constructed_string = $timestamp . '|' . $receiveddata;

            if (!\sodium_crypto_sign_verify_detached($signature_header_bytes, $constructed_string, $public_key_bytes)) {
                return false;
            } else {
                return true;
            }
        }
    }


    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     * @PublicPage
     */
    public function recdeliveryreptel() {

       $request = file_get_contents("php://input");
       $recdata = json_decode($request, TRUE);

       $delsmswebhookurl = $recdata["data"]["payload"]["webhook_url"];
       $ncuserfortelnyxdel = $this->service->getuserbyteldelrwhurl($delsmswebhookurl);

       if ($ncuserfortelnyxdel != '' && $ncuserfortelnyxdel != null && $ncuserfortelnyxdel != 'undefined') {

	       $messageid = $recdata["data"]["payload"]["id"];

	       $network = $recdata["data"]["payload"]["to"][0]["carrier"];
	       $messageprice = $recdata["data"]["payload"]["cost"]["amount"];
	       $deliverystatus = $recdata["data"]["payload"]["to"][0]["status"];

	       $goterrorinit = $recdata["data"]["payload"]["errors"];

	       if (!empty($goterrorinit)) {
		   $retrievedtitle = $recdata["data"]["payload"]["errors"][0]["title"];
		   $retrievedcode = $recdata["data"]["payload"]["errors"][0]["code"];
		   $messagestatus = "(Error " . $retrievedcode . ") " . $retrievedtitle;
	       } else {
		   $messagestatus = "Success ! The message has been successfully accepted for delivery.";
	       }

	       return $this->service->updatedeliverystatustel($ncuserfortelnyxdel, $messageid, $network, $messageprice, $messagestatus, $deliverystatus); 

       } else { return "access denied"; }

    }


    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     * @PublicPage
     */
    public function recdeliveryrepnex() {

       $plivodrurl = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

       $ncuserforplivodel = $this->service->getuserbyplivodelrwhurl($plivodrurl);

       if ($ncuserforplivodel != '' && $ncuserforplivodel != null && $ncuserforplivodel != 'undefined') {

	       $networkcode = "";
	       $mStatus = ""; 

	       if (isset($_REQUEST["MessageUUID"])) { $messageid = $_REQUEST["MessageUUID"]; } else { $messageid = ''; }
	       if (isset($_REQUEST["MCC"]) && isset($_REQUEST["MNC"])) { $networkcode = $_REQUEST["MCC"] . " " . $_REQUEST["MNC"]; } else { $networkcode = ''; }
	       if (isset($_REQUEST["TotalAmount"])) { $messageprice = $_REQUEST["TotalAmount"]; } else { $messageprice = ''; }
	       if (isset($_REQUEST["ErrorCode"]) && $_REQUEST["ErrorCode"] == "") {
                   $mStatus = "Success ! The message has been successfully accepted for delivery.";
               } elseif (isset($_REQUEST["ErrorCode"]) && $_REQUEST["ErrorCode"] != "") {
                   $mStatus = "Error " . $_REQUEST["ErrorCode"]; 
               } else { $mStatus = ''; }

	       if (isset($_REQUEST["Status"])) { $deliverystatus = $_REQUEST["Status"]; }

	       return $this->service->updatedeliverystatusnex($ncuserforplivodel, $messageid, $networkcode, $messageprice, $mStatus, $deliverystatus);

       } else { return "access denied"; }

    }


    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     * @PublicPage
     */
    public function recdeliveryreptwil() {

       $twildrurl = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

       $ncuserfortwildel = $this->service->getuserbytwildelrwhurl($twildrurl);

       if ($ncuserfortwildel != '' && $ncuserfortwildel != null && $ncuserfortwildel != 'undefined') {

           $messageid = $_REQUEST["SmsSid"];

           if ($messageid != null) {

               $credentialstw = $this->service->getapicredentials($ncuserfortwildel);
               $sidtw = $credentialstw[15];
               $tokentw = $credentialstw[16];
               $msdetails = json_decode(file_get_contents("https://".$sidtw.":".$tokentw."@api.twilio.com/2010-04-01/Accounts/".$sidtw."/Messages/".$messageid.".json"));
               $errorMessage = $msdetails->error_message;
               $errorCode = $msdetails->error_code;
               $deliverystatus = $msdetails->status;

               if ($errorCode == null) { 
                   $mStatus = 'Success ! The message has been successfully accepted for delivery.'; 
               } else { $mStatus = 'Error ' . $errorCode . '. '. ($errorMessage != '') ? 'Message: '. $errorMessage : ''; }

               $messagepricepre = $msdetails->price;
               $messageprice = str_replace("-", "", $messagepricepre);
               $networkcode = '';

	       return $this->service->updatedeliverystatustwil($ncuserfortwildel, $messageid, $networkcode, $messageprice, $mStatus, $deliverystatus);

           } else { exit(); }

       } else { exit(); }

    }


    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     * @PublicPage
     */
    public function recdeliveryrepflow() {

       $flowdrurl = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

       $ncuserforflowdel = $this->service->getuserbyflowdelrwhurl($flowdrurl);

       if ($ncuserforflowdel != '' && $ncuserforflowdel != null && $ncuserforflowdel != 'undefined') {

           $receivereq = file_get_contents('php://input');
           $recmdec = json_decode($receivereq, true);
           $recmsid = $recmdec['data']['id'];

           $smsapicredfl = $this->service->getapicredentials($ncuserforflowdel);
           $flowapikey = $smsapicredfl[20];
           $flowapisecret = $smsapicredfl[21];

           $getmsdetails = json_decode(file_get_contents("https://".$flowapikey.":".$flowapisecret."@api.flowroute.com/v2.1/messages/".$recmsid.""), true);
           $messagepriceflinit = $getmsdetails['data']['attributes']['amount_display'];
           $messagepricefl = str_replace("$", "", $messagepriceflinit);

           $mdeliveryflinit = $getmsdetails['data']['attributes']['delivery_receipts'][0]['status'];

           if ($mdeliveryflinit != 'message buffered') {
               if ($mdeliveryflinit == 'Ok') {
                   $messagedeliveryfl = "Issues";
               } else { $messagedeliveryfl = $mdeliveryflinit; }
           } else { $messagedeliveryfl = 'delivered'; }

           $messagestatuscode = $getmsdetails['data']['attributes']['delivery_receipts'][0]['status_code'];
           $messagestatusdescr = $getmsdetails['data']['attributes']['delivery_receipts'][0]['status_code_description'];

           if ($messagestatuscode != '') { 
               $messagestatusfl = (($messagestatusdescr != '') ? $messagestatusdescr . ". " : "") . "Status code: " . $messagestatuscode; 
           } else { $messagestatusfl = "There were issues with message delivery."; }

           $networkcodefl = '';

           return $this->service->updatedeliverystatusflow($ncuserforflowdel, $recmsid, $networkcodefl, $messagepricefl,  $messagestatusfl, $messagedeliveryfl);

       } else { return "access denied"; }

    }


    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     * @PublicPage
     */
    public function receivesmstel() {

       $signature = $_SERVER['HTTP_TELNYX_SIGNATURE_ED25519'];
       $timestamp = $_SERVER['HTTP_TELNYX_TIMESTAMP'];

       $receivereq = file_get_contents('php://input');

       $recmesdata = json_decode($receivereq, TRUE);

       $recsmswebhookurl = $recmesdata["data"]["payload"]["webhook_url"];

       $ncuserfortelnyx = $this->service->getuserbytelrecwhurl($recsmswebhookurl);

       $credentials = $this->service->getapicredentials($ncuserfortelnyx);

       $telpubkey = $credentials[1];

       // Verify message signature
       $signatureverify = $this->verifyHeader($receivereq, $signature, $timestamp, $telpubkey, $tolerance = 30);

       if ($signatureverify) {

          if ($ncuserfortelnyx != '' && $ncuserfortelnyx != null && $ncuserfortelnyx != 'undefined') {

	       $messageid = $recmesdata["data"]["payload"]["id"];

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

	       $messagefrom = $recmesdata["data"]["payload"]["from"]["phone_number"];

	       $messageto = "Telnyx: " . $recmesdata["data"]["payload"]["to"][0]["phone_number"];

               // Check if the message is a MMS
               if ($recmesdata["data"]["payload"]['type'] == 'MMS') {

                   $includedFiles = '';

                   foreach ($recmesdata["data"]["payload"]['media'] as $telkey => $telvalue) {
                        if (is_array($telvalue)) {
                            foreach ($telvalue as $telkeysec => $telvaluesec) {
                                if ($telkeysec == "url") {
                                    $includedFiles .= $telvaluesec . "<br><br>";
                                }
                            }
                        }
                   }

                   $messagetexttel = $recmesdata["data"]["payload"]["text"] . "<br><br><br>--- The file(s) included in the MMS follow. Download them only if you trust the sender and the domain of the URLs ---<br><br>" . $includedFiles;
                   $ismmstel = 1;
               } else {
                   $messagetexttel = $recmesdata["data"]["payload"]["text"];
                   $ismmstel = 0;
               }

	       $recmessagearr = [$messageid, $messagedate, $messagefrom, $messageto, $messagetexttel];

	       $this->service->insertrecsms($ncuserfortelnyx, $recmessagearr);

	       // Send notifications
	       $nameofhost = exec("hostname");

	       $telsmsapicred = $this->service->getapicredentials($ncuserfortelnyx);
	       $telnotify = $telsmsapicred[12];
	       $emailaddress = $telsmsapicred[13];
	       $includemessageinemail = $telsmsapicred[14];

               if ($ismmstel == 0) { $smsormmstel = "SMS"; } else { $smsormmstel = "MMS"; }

	       if ($telnotify != 0 ) {

		   $notifytel = exec("php ./occ notification:generate ".$ncuserfortelnyx." 'SMS Relentless has received a new ". $smsormmstel ." message !' -l 'You can read the new message by going to SMS Relentless and clicking on the Received SMS Messages button.'");

	       }

	       if ($emailaddress != '') {

		   $gmtind = "UTC " . date('P');
		   $smsdateinit = date("Y-m-d  H:i:s");
		   $smsdate = $smsdateinit . " " . $gmtind;

		   $subject = "New ". $smsormmstel ." message received";

                   $messagetextnltel = str_replace("\n", "<br>", $messagetexttel);

		   if ($includemessageinemail == 0) {
		       $message = "Hello, <br><br> You have received a new message on ".$smsdate." .<br> You can check the new message by going to 'SMS Relentless' > 'Received SMS Messages'. <br><br> Yours, <br> SMS Relentless <br> An SMS application for Nextcloud <br> Host: '".$nameofhost."' <br>";
		   } else {
		       $message = "Hello, <br><br> You have received a new message on ".$smsdate." :<br><br><br> Message ID: ".$messageid." <br> Message Date: ".$messagedate." <br> From: ".$messagefrom." <br> To: ".$messageto."<br> Message Text: <br><br><b>".$messagetextnltel."</b><br><br>____________<br><br> Yours, <br> SMS Relentless <br> An SMS application for Nextcloud <br> Host: '".$nameofhost."' <br>";
		   }

                   $messagefin = chunk_split(base64_encode($message));

		   $headers = "MIME-Version: 1.0" . "\r\n";
		   $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
                   $headers .= "Content-Transfer-Encoding: base64" . "\r\n";

		   // Set the email sender
		   $headers .= "From: " . $emailaddress . "\r\n";
		   $headers .= "Reply-To: " . $emailaddress . "\r\n";

		   mail($emailaddress, $subject, $messagefin, $headers);
	       }

	       return http_response_code(200);

          } else { return "access denied"; }

       } else { return "access denied"; }
    }


    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     * @PublicPage
     */
    public function receivesmsnex() {

       $plivosignature = $_SERVER['HTTP_X_PLIVO_SIGNATURE_V2'];
       $plivononce = $_SERVER["HTTP_X_PLIVO_SIGNATURE_V2_NONCE"];

       $plivorecurl = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

       $ncuserforplivo = $this->service->getuserbyplivorecwhurl($plivorecurl);

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

       $plivoauthtoken = $smsapicred[6];

       $baseplivourlinit = explode("?", $plivorecurl);  
       $baseplivoURI = $baseplivourlinit[0];

       // Verify message signature
       $SigValidation = new signatureValidation();
       $signverify = $SigValidation->validateSignature($baseplivoURI, $plivononce, $plivosignature, $plivoauthtoken);

       if ($signverify) {

              if ($ncuserforplivo != '' && $ncuserforplivo != null && $ncuserforplivo != 'undefined') {

	          $messageid = $_REQUEST["MessageUUID"];

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

	          $messagefrom = "+" . $_REQUEST['From'];
	          $messageto = "Plivo: +" . $_REQUEST['To'];

                  // Check if the message is a MMS
                  if ($_REQUEST['Type'] == 'mms') {

                      $includedFiles = '';
                      foreach ($_REQUEST as $plkey => $plvalue) {

			   if (strpos($plkey, "Media") !== false && $plkey != "MediaCount") {
                               $includedFiles .= $plvalue . "<br><br>";
			   }
                      }

                      $messagetextpl = $_REQUEST['Body'] . "<br><br><br>--- The file(s) included in the MMS follow. Download them only if you trust the sender and the domain of the URLs ---<br><br>" . $includedFiles;
                      $ismmspl = 1;
                  } else {
                      $messagetextpl = $_REQUEST['Text'];
                      $ismmspl = 0;
                  }

	          $recmessagearr = [$messageid, $messagedate, $messagefrom, $messageto, $messagetextpl];

                  $this->service->insertrecsms($ncuserforplivo, $recmessagearr);

	          // Send notifications
	          $nameofhost = exec("hostname");

	          $nextnotify = $smsapicred[12];
	          $emailaddress = $smsapicred[13];
	          $includemessageinemail = $smsapicred[14];

                  if ($ismmspl == 0) { $smsormmspl = "SMS"; } else { $smsormmspl = "MMS"; }

	          if ($nextnotify != 0 ) {
		      $notifynext = exec("php ./occ notification:generate ".$ncuserforplivo." 'SMS Relentless has received a new ". $smsormmspl ." message !' -l 'You can read the new message by going to SMS Relentless and clicking on the Received SMS Messages button.'");
	          }

	          if ($emailaddress != '') {

		      $gmtind = "UTC " . date('P');
		      $smsdateinit = date("Y-m-d  H:i:s");
		      $smsdate = $smsdateinit . " " . $gmtind;

		      $subject = "New ". $smsormmspl ." message received";

                      $messagetextnlpl = str_replace("\n", "<br>", $messagetextpl);

		      if ($includemessageinemail == 0) {
		          $message = "Hello, <br><br> You have received a new message on ".$smsdate." .<br> You can check the new message by going to 'SMS Relentless' > 'Received SMS Messages'. <br><br> Yours, <br> SMS Relentless <br> An SMS application for Nextcloud <br> Host: '".$nameofhost."' <br>";
		      } else {
		          $message = "Hello, <br><br> You have received a new message on ".$smsdate." :<br><br><br> Message ID: ".$messageid." <br> Message Date: ".$messagedate." <br> From: ".$messagefrom." <br> To: ".$messageto."<br> Message Text: <br><br><b>".$messagetextnlpl."</b><br><br>____________<br><br> Yours, <br> SMS Relentless <br> An SMS application for Nextcloud <br> Host: '".$nameofhost."' <br>";
		      }

                      $messagefin = chunk_split(base64_encode($message));

		      $headers = "MIME-Version: 1.0" . "\r\n";
		      $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
                      $headers .= "Content-Transfer-Encoding: base64" . "\r\n";

		      // Set the email sender
		      $headers .= "From: " . $emailaddress . "\r\n";
		      $headers .= "Reply-To: " . $emailaddress . "\r\n";

		      mail($emailaddress, $subject, $messagefin, $headers);
	          }

	          return http_response_code(200);

              } else { return "access denied"; }

       } else { return "access denied"; }
    }


    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     * @PublicPage
     */
    public function receivesmstwil() {

       $twilsig = $_SERVER['HTTP_X_TWILIO_SIGNATURE'];

       $basepath = $this->config->getSystemValue('overwrite.cli.url');
       $twilrecprm = $_GET["twilrecparam"];
       $twilrecurl = $basepath . "/apps/sms_relentless/api/recsmstwil?twilrecparam=" . $twilrecprm;

       $ncuserfortwil = $this->service->getuserbytwilrecwhurl($twilrecurl);

       $smsapicred = $this->service->getapicredentials($ncuserfortwil);
       $authTokenTw = $smsapicred[16];

       $postVars = $_POST;
       ksort($postVars);

       $compurlpart = '';

       foreach ($postVars as $twilkey => $twilvalue) {
                $compurlpart .= $twilkey . $twilvalue;
       }

       $compURL1 = $basepath . "/apps/sms_relentless/api/recsmstwil?twilrecparam=" . $twilrecprm . $compurlpart;
       $compURL2 = $basepath . "/apps/sms_relentless/api/recsmstwil?twilrecparam=" . $twilrecprm . "&twilrecparam=" . $twilrecprm . $compurlpart;
       $computedsig1 = base64_encode(hash_hmac('sha1', $compURL1, $authTokenTw, true));
       $computedsig2 = base64_encode(hash_hmac('sha1', $compURL2, $authTokenTw, true));

       // Verify message signature
       if (strcmp($computedsig1, $twilsig) == 0 || strcmp($computedsig2, $twilsig) == 0) {

           if ($ncuserfortwil) {

	       $messageid = $_POST['MessageSid'];

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

	       $messagefrom = $_POST['From'];

	       $messageto = "Twilio: " . $_POST['To'];

               // Check if the new message is a MMS
               if ($_POST['NumMedia'] != 0) {

                   $includedFiles = '';
                   foreach ($_POST as $twkey => $twvalue) {

			if (strpos($twkey, "MediaUrl") !== false) {
                            $includedFiles .= $twvalue . "<br><br>";
			}
                   }
                   $messagetexttw = $_POST['Body'] . "<br><br><br>--- The file(s) included in the MMS follow. Download them only if you trust the sender and the domain of the URLs. ---<br><br>" . $includedFiles;
                   $ismmstw = 1;
               } else {
                   $messagetexttw = $_POST['Body'];
                   $ismmstw = 0;
               }

	       $recmessagearr = [$messageid, $messagedate, $messagefrom, $messageto, $messagetexttw];

	       $this->service->insertrecsms($ncuserfortwil, $recmessagearr);

	       // Send notifications
	       $nameofhost = exec("hostname");

	       $twilnotify = $smsapicred[12];
	       $emailaddress = $smsapicred[13];
	       $includemessageinemail = $smsapicred[14];

               if ($ismmstw == 0) { $smsormmstw = "SMS"; } else { $smsormmstw = "MMS"; }

	       if ($twilnotify != 0 ) {
		   $notifynext = exec("php ./occ notification:generate ".$ncuserfortwil." 'SMS Relentless has received a new ". $smsormmstw ." message !' -l 'You can read the new message by going to SMS Relentless and clicking on the Received SMS Messages button.'");
	       }

	       if ($emailaddress != '') {

		   $gmtind = "UTC " . date('P');
		   $smsdateinit = date("Y-m-d  H:i:s");
		   $smsdate = $smsdateinit . " " . $gmtind;

		   $subject = "New ". $smsormmstw ." message received";

                   $messagetextnltw = str_replace("\n", "<br>", $messagetexttw);

		   if ($includemessageinemail == 0) {
		       $message = "Hello, <br><br> You have received a new message on ".$smsdate." .<br> You can check the new message by going to 'SMS Relentless' > 'Received SMS Messages'. <br><br> Yours, <br> SMS Relentless <br> An SMS application for Nextcloud <br> Host: '".$nameofhost."' <br>";
		   } else {
		       $message = "Hello, <br><br> You have received a new message on ".$smsdate." :<br><br><br> Message ID: ".$messageid." <br> Message Date: ".$messagedate." <br> From: ".$messagefrom." <br> To: ".$messageto."<br> Message Text: <br><br><b>".$messagetextnltw."</b><br><br>____________<br><br> Yours, <br> SMS Relentless <br> An SMS application for Nextcloud <br> Host: '".$nameofhost."' <br>";
		   }

                   $messagefin = chunk_split(base64_encode($message));

		   $headers = "MIME-Version: 1.0" . "\r\n";
		   $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
                   $headers .= "Content-Transfer-Encoding: base64" . "\r\n";

		   // Set the email sender
		   $headers .= "From: " . $emailaddress . "\r\n";
		   $headers .= "Reply-To: " . $emailaddress . "\r\n";

		   mail($emailaddress, $subject, $messagefin, $headers);
	       }

               exit();

           } else { exit(); }

       } else { exit(); }

    }


    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     * @PublicPage
     */
    public function receivesmsflow() {

       $flowdrurl = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

       $receivesms = file_get_contents('php://input');
       $recsmsarr = json_decode($receivesms, true);

       $ncuserforflowrec = $this->service->getuserbyflowrecwhurl($flowdrurl);

       if ($ncuserforflowrec != '' && $ncuserforflowrec != null && $ncuserforflowrec != 'undefined') {

           $messageidfl = $recsmsarr['data']['id'];

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

           $messagefromflpre = $recsmsarr['data']['attributes']['from'];
           if (substr($messagefromflpre, 0, 1) == '+') { $messagefromfl = $messagefromflpre; } else { $messagefromfl = '+' . $messagefromflpre; }

           $messagetofl = "Flowroute: +" . $recsmsarr['data']['attributes']['to'];

           // Check if the message is a MMS
           if ($recsmsarr['data']['attributes']['is_mms'] == true) {

               $includedFiles = '';
               for ($k = 0; $k < count($recsmsarr['included']); $k++) {
                    $includedFiles .= $recsmsarr['included'][$k]['attributes']['url'] . "<br><br>";
               }
               $messagetextfl = $recsmsarr['data']['attributes']['body'] . "<br><br><br>--- The file(s) included in the MMS follow. Download them only if you trust the sender and the domain of the URLs. ---<br><br>" . $includedFiles;
               $ismmsfl = 1;
           } else {
               $messagetextfl = $recsmsarr['data']['attributes']['body'];
               $ismmsfl = 0;
           }

           $recmessagearr = [$messageidfl, $messagedatefl, $messagefromfl, $messagetofl, $messagetextfl];

           $this->service->insertrecsms($ncuserforflowrec, $recmessagearr);

	   // Send notifications
	   $nameofhost = exec("hostname");

           $smsapicred = $this->service->getapicredentials($ncuserforflowrec);
	   $flownotify = $smsapicred[12];
	   $emailaddress = $smsapicred[13];
	   $includemessageinemail = $smsapicred[14];

           if ($ismmsfl == 0) { $smsormmsfl = "SMS"; } else { $smsormmsfl = "MMS"; }

	   if ($flownotify != 0 ) {
	       $notifyflow = exec("php ./occ notification:generate ".$ncuserforflowrec." 'SMS Relentless has received a new ". $smsormmsfl ." message !' -l 'You can read the new message by going to SMS Relentless and clicking on the Received SMS Messages button.'");
	   }

	   if ($emailaddress != '') {

	       $gmtind = "UTC " . date('P');
	       $smsdateinit = date("Y-m-d  H:i:s");
	       $smsdate = $smsdateinit . " " . $gmtind;

	       $subject = "New ". $smsormmsfl ." message received";

               $messagetextnlfl = str_replace("\n", "<br>", $messagetextfl);

	       if ($includemessageinemail == 0) {
	           $message = "Hello, <br><br> You have received a new message on ".$smsdate." .<br> You can check the new message by going to 'SMS Relentless' > 'Received SMS Messages'. <br><br> Yours, <br> SMS Relentless <br> An SMS application for Nextcloud <br> Host: '".$nameofhost."' <br>";
	       } else {
	           $message = "Hello, <br><br> You have received a new message on ".$smsdate." :<br><br><br> Message ID: ".$messageidfl." <br> Message Date: ".$messagedatefl." <br> From: ".$messagefromfl." <br> To: ".$messagetofl."<br> Message Text: <br><br><b>".$messagetextnlfl."</b><br><br>____________<br><br> Yours, <br> SMS Relentless <br> An SMS application for Nextcloud <br> Host: '".$nameofhost."' <br>";
	       }

               $messagefin = chunk_split(base64_encode($message));

	       $headers = "MIME-Version: 1.0" . "\r\n";
	       $headers .= "Content-type: text/html; charset=UTF-8" . "\r\n";
               $headers .= "Content-Transfer-Encoding: base64" . "\r\n";

	       // Set the email sender
	       $headers .= "From: " . $emailaddress . "\r\n";
	       $headers .= "Reply-To: " . $emailaddress . "\r\n";

	       mail($emailaddress, $subject, $messagefin, $headers);
	   }

           return http_response_code(200);

       } else { return "access denied"; }

    }
}
