#!/usr/bin/php -q
<?php
// Debug Mode for IDE runtime debugger
define("SCRIPTDEBUG", 0);
define("DEFAULTVALUES", 0);
// is config->debug set
$GLOBALS['IS_DEBUG'] = 0;

// change to web server root to load scripts
chdir("/var/www");
require_once "public/config.inc.php";
// access to config file
require_once "src/foundation/class.siteconfig.php";
// db access; uses config file
require_once "src/foundation/class.common.php";
// access global conig
require_once "src/class/class.globalconfig.php";
// communicate with a comport with the serial_comm binary
require_once "src/class/class.serialcomm.php";
// wvdialer
require_once "src/class/class.services.php";

$GLOBALS['SERIAL_BINPATH'] = "/usr/local/recordum/dataproc/";
$GLOBALS['SERIAL_TYPE'] = 1;
$GLOBALS['USE_WVDIAL'] = 1;
$GLOBALS['USE_ROUTER'] = 0;

function init()
{
    $oConf = new GlobalConfig('en');
    $settings = $oConf->GetParams(array(179, 305, 1827, 1893, 2588));

    // connected via USB or UART
    $modem_dev = isset($settings[1827]) ? $settings[1827]['int_val'] : 0;
    $GLOBALS['SERIAL_BINPATH'] .= ($modem_dev == 1) ? "serial_comm_usb" : "serial_comm";
    // convert from Windows port numbering (1 .. n) to Linux device numbers (0 .. n-1)
    $com = isset($settings[305]) ? intval($settings[305]['str_val']) - 1 : 0;
    if ($com < 0)
    {
        $com = 0;
    }
    $GLOBALS['SERIAL_PORT'] = $com;
    // supported modem types are
    //      1: UMTS (PH8)
    //      2: GPRS (MC66)
    //      3: LTE (PLS8)
    $type = isset($settings[1893]) ? $settings[1893]['int_val'] : 1;
    $GLOBALS['SERIAL_TYPE'] = $type;
    // Cinterion PLS8
    if ($type == 3)
    {
        // has its own command channel
        $GLOBALS['SERIAL_PORT'] = $com + 1;
        // thus we can send SMs without interrupting the internet connection
        $GLOBALS['USE_WVDIAL'] = 0;
    }
    $GLOBALS['USE_ROUTER'] = isset($settings[2588]) ? intval($settings[2588]['str_val']) : 0;
    // also apply the system debug flag
    $GLOBALS['IS_DEBUG'] = isset($settings[179]) ? intval($settings[179]['str_val']) : 0;

    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        $config = array();
        $config["binary"] = $GLOBALS['SERIAL_BINPATH'];
        switch ($type)
        {
            case 1:
                { // UMTS (PH8)
                    $type_name = "UMTS (PH8)";
                }
            break;
            case 2:
                { // GPRS (MC66)
                    $type_name = "GPRS (MC66)";
                }
            break;
            case 3:
                { // LTE (PLS8)
                    $type_name = "LTE (PLS8)";
                }
            break;
            default:
            {
                $type_name = $type;
            }
        }
        $config["type"] = $type_name;
        $config["device"] = ($modem_dev == 1) ?
            "/dev/ttyACM" . $GLOBALS['SERIAL_PORT'] :
            "/dev/ttyS" . $GLOBALS['SERIAL_PORT'];
        var_dump($config);
    }
}

function writeError($id, $msg)
{
    fwrite($GLOBALS['stderr'], "ERROR: (" . $id . ") " . $msg . "\n");
}

function writeFeedback($msg)
{
    fwrite($GLOBALS['stdout'], $msg . "\n");
}

function writeUsage()
{
    fwrite($GLOBALS['stdout'], "Usage: " . $GLOBALS['argv'][0] . " action_id message\n\t123\n\timportant message\n");
}

/** @noinspection DuplicatedCode */
function send($id, $message)
{
    $nl = "\n";
    /** @var SqlDb2 $oSql */
    $oSql = DBAccess::getSqlObj();
    // here fetch sms settings
    $sql = "SELECT";
    $sql .= " * FROM ra_actions WHERE actions_id = " . $id;
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        echo $nl . "Lookup command: " . $sql . $nl;
    }

    $access = $oSql->query($sql);
    if (!$access)
    {
        writeError(3, "Error table lookup: " . $oSql->lastError());
        exit(3);
    }

    $settings = array();
    while (($row = $oSql->fetchRowFields($access)))
    {
        $settings = $row;
    }
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        var_dump($settings);
    }
    $count = count($settings);
    // no tables found silent exit
    if ($count == 0)
    {
        exit(4);
    }

    $sWvdial = new ServiceWvdial();
    $oComm = new SerialComm();

    $oComm->InitFiles($GLOBALS['SERIAL_BINPATH'], '/tmp/PLUGIN_sms.out', '/tmp/PLUGIN_sms.err');
    $oComm->InitDevice($GLOBALS['SERIAL_PORT'], 115200);
    $oComm->EnableRootExec($GLOBALS['rootExecPath'] . $GLOBALS['rootExec']);

    // only send a message when we have someone to send it to
    $to = explode(';', $settings["phone_nr"]);
    $c = count($to);
    if ($c)
    {
        try
        {
            if ($GLOBALS['USE_ROUTER'])
            {
                $ip = trim($settings["url"]);
                if (filter_var(trim($ip), FILTER_VALIDATE_IP))
                {
                    if (SCRIPTDEBUG)
                    {
                        writeFeedback('Connect to: ' . $ip);
                    }
                    $ch = curl_init();
                    if ($ch)
                    {
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
                        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                        // cgi-bin/sms_send?username=user1&password=user_pass&number=0037060000001&text=testmessage
                        $parts = array();
                        $parts["username"] = $settings["login_name"];
                        $parts["password"] = $settings["login_pwd"];
                        $parts["text"] = substr($message, 0, 158);

                        $isNumber = '/^([0+])+([0-9])+$/';
                        $rc = 0;
                        foreach ($to as $value)
                        {
                            // telecommunication providers  seem to prefer +xx format for SMs sending
                            $internationalNumber = preg_replace('/^00/', '+', $value);
                            $parts["number"] = $internationalNumber;
                            $allow = preg_match($isNumber, $internationalNumber);
                            if ($allow !== 1)
                            {
                                writeError(5, "No valid number: [" . $internationalNumber . "]");
                                continue;
                            }

                            $getData = '';
                            foreach ($parts as $k => $v)
                            {
                                $getData .= $k . '=' . urlencode($v) . '&';
                            }
                            $getData = rtrim($getData, '&');
                            $url = 'http://' . $ip . '/cgi-bin/sms_send?' . $getData;
                            if (SCRIPTDEBUG)
                            {
                                writeFeedback('Calling: ' . $url);
                            }
                            curl_setopt($ch, CURLOPT_URL, $url);
                            $cgi_answer = curl_exec($ch);
                            if ($cgi_answer === false)
                            {
                                $cgi_answer = curl_error($ch);
                            }
                            $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            if ($code == 200)
                            {
                                $target = "Message successfully send to: " . $internationalNumber . $nl;
                                echo $target;
                                $rc = 1;
                            }
                            if ($cgi_answer && SCRIPTDEBUG)
                            {
                                writeFeedback('Response: ' . $cgi_answer);
                            }

                            sleep(1);
                        }
                        curl_close($ch);
                        if ($rc == 0)
                        {
                            writeError(6, "No recipient received the message.");
                            exit(6);
                        }
                    }
                } else
                {
                    writeError(7, "No valid IPv4 Address: [" . $ip . "]");
                }
            } else
            {
                if ($GLOBALS['USE_WVDIAL'] == 1)
                {
                    // Stop wvdial service
                    $rc = $sWvdial->execAction('stop');
                    if ($rc)
                    {
                        writeError(5, "Could not stop service wvdial. (" . $sWvdial->GetRemainingOutputP(true) . ")");
                        $oComm->CleanUp();
                        exit(5);
                    }
                    // loop for the stop to finish
                    $loops = 0;
                    while ($sWvdial->queryStatus() == DAEMON_RUNNING && $loops < 15)
                    {
                        sleep(1);
                        $loops++;
                    }
                    sleep(3);
                }

                // Send SMS in 3 steps
                $err = array();
                $rc = 0;
                for ($i = 0; $i < count($to); $i++)
                {
                    // ATZ loads a via AT&W saved user defined profile
                    // if no profile is stored it behaves like AT&F (command factory default settings)
                    $oComm->SetData("ATZ\r");
                    $oComm->StartComm();
                    $r0 = $oComm->ReadReply();
                    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                    {
                        echo $r0;
                    }
                    $oComm->SetData("AT+CMGF=1\r");
                    $oComm->StartComm();
                    $r1 = $oComm->ReadReply();
                    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                    {
                        echo $r1;
                    }
                    // ask provider to be verbose about errors
                    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                    {
                        $oComm->SetData("AT+CMEE=1\r");
                        $oComm->StartComm();
                        $r1 = $oComm->ReadReply();
                        if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                        {
                            echo $r1;
                        }
                    }
                    if ($GLOBALS['SERIAL_TYPE'] == 2)
                    { // GPRS (MC66)
                        $oComm->SetData("AT+CMGS=" . $to[$i] . "\r");
                    } else
                    { // UMTS (PH8), LTE (PLS8)
                        $oComm->SetData("AT+CMGS=\"" . $to[$i] . "\"\r");
                    }
                    $oComm->StartComm();
                    $r2 = $oComm->ReadReply();
                    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                    {
                        echo $r2;
                    }
                    $oComm->SetData(substr($message, 0, 158) . chr(26)); // 26 - EOF
                    $oComm->StartComm();
                    $r3 = $oComm->ReadReply();
                    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                    {
                        echo $r3;
                    }
                    if (strpos($r1, "OK") === false || strpos($r2, ">") === false || strpos($r3, "ERROR") !== false)
                    {
                        $err[] = htmlentities("SMS-Error (0: " . $r0 . ", 1: " . $r1 . ", 2: " . $r2 . ", 3: " . $r3 . ")");
                    } else
                    {
                        $target = "Message successfully send to: " . $to[$i] . " (" . $r3 . ")\n";
                        echo $target;
                        $rc = 1;
                    }
                    sleep(1);
                }

                if ($GLOBALS['USE_WVDIAL'] == 1)
                {
                    // Start wvdial again
                    if ($sWvdial->isActive())
                    {
                        sleep(1);
                        $sWvdial->execAction('start');
                    }
                }

                if ($rc == 0)
                {
                    $oComm->CleanUp();
                    writeError(6, "No recipient received the message." . $nl . "SMS errors: " . implode(';', $err));
                    exit(6);
                }
            }
        } catch (Exception $e)
        {
            if ($GLOBALS['USE_WVDIAL'] == 1)
            {
                // Start wvdial again
                if ($sWvdial->isActive())
                {
                    sleep(1);
                    $sWvdial->execAction('start');
                }
            }

            if (!$GLOBALS['USE_ROUTER'])
            {
                $oComm->CleanUp();
            }
            writeError(1, "Error sending: " . $e->getMessage());
            exit(1);
        }
    }
    if (!$GLOBALS['USE_ROUTER'])
    {
        $oComm->CleanUp();
    }
}

function main($argc, $argv)
{
    if (SCRIPTDEBUG && DEFAULTVALUES)
    {
        send(2, "hello world");
        exit(0);
    } else
    {
        if ($argc < 3)
        {
            writeUsage();
            writeError(2, "Wrong or missing command line parameters");
            exit(2);
        }
        send($argv[1], $argv[2]);
        exit(0);
    }
}

// supported STDIN/OUT/ERR syntax for php version 4.3 till 5.3
$stderr = fopen('php://stderr', 'w');
$stdout = fopen('php://stdout', 'w');
// fetch modem bin path, port and debug flag
init();
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
