User Tools

Site Tools


br-222-wsdevice


WebService para Dispositivos Móveis


<?php

# ========================================================================================
#
#   FOLLOWZUP PROJECT
#   WEBSERVICE FOR DEVICE REQUESTS
#
# ========================================================================================
#
#   Copyright (C) 2016 Followzup.com
#
#   This program is free software: you can redistribute it and/or modify it under
#   the terms of the GNU General Public 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 General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>
#
# ========================================================================================

    $wid       = "";
    $wkey1     = "";
    $wframe1   = "";
    $wretcode  = "0";
    $wretframe = "";
    $wresponse = "";
    $wdecrypt  = "";
    $wretmd5   = "";

    $wnow = gmdate("Y-m-d H:i:s");

#   Extract and sanitize POST parameters

    if ( isset($_POST["id"]) )    $wid     = sanitizeID($_POST["id"]);
    if ( isset($_POST["key"]) )   $wkey1   = sanitizeText($_POST["key"]);
    if ( isset($_POST["frame"]) ) $wframe1 = sanitizeText($_POST["frame"]);

#   Verify identification

    $wprefix = substr($wid,0,1);

    if ( !validateID($wid) or ( $wprefix != "d" and $wprefix != "i" ) ) $wretcode = "7104";

# ========================================================================================
#
#   DEVICE REGISTER (ID prefix = "i")
#
#      Param:  FZUP_STAMP <stp> = stamp
#              FZUP_EMAIL <eml> = e-mail
#              FZUP_PASS  <pwd> = password
#
#      Return: <uid>User-ID</uid>
#              <did>Device-ID</did>
#              <pub>pub-key</pub>
#              <mod>mod-key</mod>
#              <pux>pux-key</pux>
#
# ========================================================================================

    elseif ( $wprefix == "i" )
    {

#       Retrieve valid Interface attributes

        $wquery = "select stamp
                     from interfaces
                    where idinterface = '$wid' and regstatus != 'd'";

        $wres    = mysql_query($wquery);
        $wnumreg = mysql_num_rows($wres);

#       verify the Interface is ok

        if ( $wnumreg == 0 ) $wretcode = "7104";

        else
        {

#           Retrieve attributes (Interface stamp)

            $wvetor     = mysql_fetch_row($wres);
            $istamp     = $wvetor[0];

#           Retrieve Interface Private RSA key

            $wquery  = "select pkpri from pkeys where idkey = 'keydev'";
            $wres    = mysql_query($wquery);
            $wnumreg = mysql_num_rows($wres);

#           Decode Private RSA Key

            if ( $wnumreg == 0 ) $wpri = "";

            else
            {
                $wvetor = mysql_fetch_row($wres);
                $wpri64 = $wvetor[0];
                $wpri   = base64_decode($wpri64);
            }

#           Decode and decrypt POST parameters using Private RSA key

            $wkey2   = base64_decode($wkey1);
            $wframe2 = base64_decode($wframe1);
            $wseq    = 0;

            openssl_private_decrypt($wkey2,$wkey3,$wpri);
            $wdecrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $wkey3, $wframe2, MCRYPT_MODE_CBC, str_repeat(chr(0),16));
            $wxml = @simplexml_load_string("$wdecrypt");

#           Verify decrypt

            if ( $wdecrypt == "" or $wkey3 == "" or $wpri == "" or !isset($wxml->stp) or !isset($wxml->eml) or !isset($wxml->pwd) ) $wretcode = "7102";

            else
            {

#               Extract parameters from XML request

                $wstamp   = preg_replace("/[^a-z0-9]/","","$wxml->stp");
                $wemail   = sanitizeEmail("$wxml->eml");
                $wtrypass = sanitizeText("$wxml->pwd");

#               Verify request stamp

                if ( $wstamp != $istamp ) $wretcode = "7105";

# ========================================================================================
#
#   Device register for ANUNYMOUS USERS
#
# ========================================================================================

                elseif ( $wemail == "anonymous" and $wtrypass == "anonymous" )
                {

#                   Register new Anonymous User-ID

                    $widuser  = idgenerator("usr");

                    $wquery2  = "insert into users (iduser, email, dateincl, name, regstatus)
                                            values ('$widuser', '$widuser', '$wnow', 'Anonymous User', 'a')";

                    while ( !mysql_query($wquery2) )
                    {

                        $widuser = idgenerator("usr");

                        $wquery2  = "insert into users (iduser, email, dateincl, name, regstatus)
                                                values ('$widuser', '$widuser', '$wnow', 'Anonymous User', 'a')";

                    }

#                   Generate Device RSA keys

                    $wdev    = keygenerator(2048);
                    $wdevpri = $wdev["pri"];
                    $wdevpub = $wdev["pub"];
                    $wdevmod = $wdev["mod"];
                    $wdevpux = $wdev["pux"];
                    $wdevprx = $wdev["prx"];
                    $wdevpr1 = $wdev["pr1"];
                    $wdevpr2 = $wdev["pr2"];
                    $wdevdmp = $wdev["dmp"];
                    $wdevdmq = $wdev["dmq"];
                    $wdeviqm = $wdev["iqm"];

#                   Register new Device-ID

                    $widdevice  = idgenerator("dev");

                    $wquery2    = "insert into devices (iddevice, iduser, devicetag, dateincl, lastact, idinterface, regstatus, pkpub, pkpri, pkmod, pkpux, pkprx, pkpr1, pkpr2, pkdmp, pkdmq, pkiqm)
                                                values ('$widdevice', '$widuser', 'Anonymous', '$wnow', '$wnow', '$wid', 'a',
                                                        '$wdevpub', '$wdevpri', '$wdevmod', '$wdevpux', '$wdevprx', '$wdevpr1', '$wdevpr2', '$wdevdmp', '$wdevdmq', '$wdeviqm')";

                    while ( !mysql_query($wquery2) )
                    {

                        $widdevice  = idgenerator("dev");

                        $wquery2    = "insert into devices (iddevice, iduser, devicetag, dateincl, lastact, idinterface, regstatus, pkpub, pkpri, pkmod, pkpux, pkprx, pkpr1, pkpr2, pkdmp, pkdmq, pkiqm)
                                                    values ('$widdevice', '$widuser', 'Anonymous', '$wnow', '$wnow', '$wid', 'a',
                                                            '$wdevpub', '$wdevpri', '$wdevmod', '$wdevpux', '$wdevprx', '$wdevpr1', '$wdevpr2', '$wdevdmp', '$wdevdmq', '$wdeviqm')";
                    }

#                   Generate random Subscription Code for Followzup Channel subscription

                    $wsubscode = rand(10000000,99999999);

                    $wquery = "insert into subscriptions (iduser, idchannel, dateincl, subscode, regstatus) values ('$widuser', 'c00000000000', '$wnow', '$wsubscode', 'a')";
                    $wres   = mysql_query($wquery);

#                   Build response

                    $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup>";
                    $wresponse = $wresponse . "<uid>$widuser</uid>";
                    $wresponse = $wresponse . "<did>$widdevice</did>";
                    $wresponse = $wresponse . "<pub>$wdevpub</pub>";
                    $wresponse = $wresponse . "<mod>$wdevmod</mod>";
                    $wresponse = $wresponse . "<pux>$wdevpux</pux>";
                    $wresponse = $wresponse . "</followzup>";

                    $wretframe1 = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $wkey3, $wresponse, MCRYPT_MODE_CBC, str_repeat(chr(0),16));
                    $wretframe  = base64_encode($wretframe1);

                }

#               Verify valid e-mail

                elseif ( !validateEmail($wemail) or $wemail == "" ) $wretcode = "7107";

# ========================================================================================
#
#   Device register for REGISTERED USERS
#
# ========================================================================================

                else
                {

#                   Retrieve valid User attributes

                    $wquery = "select iduser, pass, datetry
                                 from users
                                where email = '$wemail' and regstatus = 'a'";

                    $wres    = mysql_query($wquery);
                    $wnumreg = mysql_num_rows($wres);

#                   verify the User is ok

                    if ( $wnumreg == 0 ) $wretcode = "7107";

                    else
                    {

#                       Retrieve attributes

                        $wvetor   = mysql_fetch_row($wres);
                        $widuser  = $wvetor[0];
                        $wpass    = $wvetor[1];
                        $wdatetry = $wvetor[2];

#                       Make sure current time is greater than next time to try (avoid bot actions)

                        if ( $wnow < $wdatetry ) $wretcode = "7108";

#                       Password not ok

                        elseif ( $wpass == "" or $wpass != md5($wtrypass) )
                        {

                            $wretcode = "7108";

#                           Uptade next time to try (current time plus 2 seconds to avoid bot actions)

                            $wdatetry = gmdate("Y-m-d H:i:s", strtotime("+2 seconds"));

                            $wquery = "update users set datetry = '$wdatetry' where iduser = '$widuser'";
                            $wres   = mysql_query($wquery);

                        }

#                       Password is ok

                        else
                        {

#                           Find next default Device tag for the user (Device-N)

                            $wnext = 0;

                            do
                            {

                                $wnext   = $wnext + 1;
                                $wtag    = "Device-" . $wnext;
                                $wquery  = "select iddevice from devices where iduser = '$widuser' and devicetag = '$wtag'";
                                $wres    = mysql_query($wquery);
                                $wnumreg = mysql_num_rows($wres);

                            } while ( $wnumreg > 0 );

#                           Generate Device RSA keys

                            $wdev    = keygenerator(2048);
                            $wdevpri = $wdev["pri"];
                            $wdevpub = $wdev["pub"];
                            $wdevmod = $wdev["mod"];
                            $wdevpux = $wdev["pux"];
                            $wdevprx = $wdev["prx"];
                            $wdevpr1 = $wdev["pr1"];
                            $wdevpr2 = $wdev["pr2"];
                            $wdevdmp = $wdev["dmp"];
                            $wdevdmq = $wdev["dmq"];
                            $wdeviqm = $wdev["iqm"];

#                           Register new Device-ID

                            $widdevice = idgenerator("dev");

                            $wquery2   = "insert into devices (iddevice, iduser, devicetag, dateincl, lastact, idinterface, regstatus, pkpub, pkpri, pkmod, pkpux, pkprx, pkpr1, pkpr2, pkdmp, pkdmq, pkiqm)
                                                       values ('$widdevice', '$widuser', '$wtag', '$wnow', '$wnow', '$wid', 'a',
                                                               '$wdevpub', '$wdevpri', '$wdevmod', '$wdevpux', '$wdevprx', '$wdevpr1', '$wdevpr2', '$wdevdmp', '$wdevdmq', '$wdeviqm')";

                            while ( !mysql_query($wquery2) )
                            {

#                               Find new default Device tag for the user (Device-N)

                                $wnext = 0;

                                do
                                {

                                    $wnext   = $wnext + 1;
                                    $wtag    = "Device-" . $wnext;
                                    $wquery  = "select iddevice from devices where iduser = '$widuser' and devicetag = '$wtag'";
                                    $wres    = mysql_query($wquery);
                                    $wnumreg = mysql_num_rows($wres);

                                } while ( $wnumreg > 0 );

                                $widdevice = idgenerator("dev");

                                $wquery2   = "insert into devices (iddevice, iduser, devicetag, dateincl, lastact, idinterface, regstatus, pkpub, pkpri, pkmod, pkpux, pkprx, pkpr1, pkpr2, pkdmp, pkdmq, pkiqm)
                                                           values ('$widdevice', '$widuser', '$wtag', '$wnow', '$wnow', '$wid', 'a',
                                                                   '$wdevpub', '$wdevpri', '$wdevmod', '$wdevpux', '$wdevprx', '$wdevpr1', '$wdevpr2', '$wdevdmp', '$wdevdmq', '$wdeviqm')";

                            }

#                           Build response

                            $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup>";
                            $wresponse = $wresponse . "<uid>$widuser</uid>";
                            $wresponse = $wresponse . "<did>$widdevice</did>";
                            $wresponse = $wresponse . "<pub>$wdevpub</pub>";
                            $wresponse = $wresponse . "<mod>$wdevmod</mod>";
                            $wresponse = $wresponse . "<pux>$wdevpux</pux>";
                            $wresponse = $wresponse . "</followzup>";

                            $wretframe1 = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $wkey3, $wresponse, MCRYPT_MODE_CBC, str_repeat(chr(0),16));
                            $wretframe  = base64_encode($wretframe1);

                        }

                    }

                }

            }

        }

    }

# ========================================================================================
#
#   Device requests
#
# ========================================================================================

    else
    {

#       Retrieve valid Device attributes

        $wquery = "select devices.iduser, devices.deviceseq, devices.pkpri, interfaces.stamp, devices.devicetag
                     from devices, interfaces, users as dusers, users as iusers
                    where devices.iddevice = '$wid' and devices.regstatus = 'a' and
                          devices.idinterface = interfaces.idinterface and interfaces.regstatus != 'd' and
                          devices.iduser = dusers.iduser and dusers.regstatus = 'a' and
                          interfaces.iduser = iusers.iduser and iusers.regstatus = 'a'";

        $wres    = mysql_query($wquery);
        $wnumreg = mysql_num_rows($wres);

#       Verify the Device is ok

        if ( $wnumreg == 0 ) $wretcode = "7104";

        else
        {

#           Retrieve attributes

            $wvetor       = mysql_fetch_row($wres);
            $widuser      = $wvetor[0];
            $wdeviceseq   = $wvetor[1];
            $wpri64       = $wvetor[2];
            $istamp       = $wvetor[3];
            $wdevicetag   = $wvetor[4];

#           Decode and decrypt POST parameters using Private RSA key

            $wpri    = base64_decode($wpri64);
            $wkey2   = base64_decode($wkey1);
            $wframe2 = base64_decode($wframe1);

            openssl_private_decrypt($wkey2,$wkey3,$wpri);
            $wdecrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $wkey3, $wframe2, MCRYPT_MODE_CBC, str_repeat(chr(0),16));
            $wxml = @simplexml_load_string($wdecrypt);

#           Verify decrypt

            if ( $wdecrypt == "" or $wkey3 == "" or !isset($wxml->stp) or !isset($wxml->com) or !isset($wxml->seq) ) $wretcode = "7102";

            else
            {

#               Extract parameters from XML request

                $wcom      = preg_replace("/[^a-z]/","",strtolower($wxml->com));
                $wstamp    = preg_replace("/[^a-z0-9]/","",$wxml->stp);
                $wseq      = (int)$wxml->seq;

#               Verify stamp

                if ( $wstamp != $istamp ) $wretcode = "7105";

#               Verify command

                elseif ( "$wcom" != "ureg" and "$wcom" != "chck" and "$wcom" != "dmsg" and "$wcom" != "lsub" and
                         "$wcom" != "lkup" and "$wcom" != "schn" and "$wcom" != "uchn" and "$wcom" != "icon" and "$wcom" != "resp" ) $wretcode = "7103";

#               Verify sequence

                elseif ( $wseq != $wdeviceseq + 1 )
                {

                    $wretcode = "7101";

#                   Build response (return last sequence used when wrong sequence)

                    $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup><seq>$wdeviceseq</seq></followzup>";

                    $wretframe1 = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $wkey3, $wresponse, MCRYPT_MODE_CBC, str_repeat(chr(0),16));
                    $wretframe  = base64_encode($wretframe1);

                }

                else
                {

#                   Update Device sequence

                    $wquery = "update devices set deviceseq = $wseq, lastact = utc_timestamp() where iddevice = '$wid'";
                    $wres   = mysql_query($wquery);

# ========================================================================================
#
#   CHCK command - CHECK FOR NEW MESSAGES
#
#      Param:  FZUP_STAMP   <stp> = stamp
#              FZUP_COMMAND <com> = chck
#              FZUP_LASTSEQ <seq> = sequence
#              FZUP_LASTMSG <msg> = last idmessage
#
#      Return: <md5>MD5-list</md5>                                Channel list MD5 hash
#              <msg>tag;idmessage;dateincl;msg-text;msg-url</msg> Message list
#
# ========================================================================================

                    if ( $wcom == "chck" )
                    {

#                       Sanitize parameters

                        $wlastmsg  = (int)$wxml->msg;

#                       Calculate current MD5-list

                        $wquery = "select tag, subscode, md5icon, if(responseurl='','n','y'), welcomeurl
                                     from devices, subscriptions, channels, users
                                    where devices.iddevice = '$wid' and devices.regstatus = 'a' and
                                          devices.iduser = subscriptions.iduser and subscriptions.regstatus = 'a' and
                                          subscriptions.idchannel = channels.idchannel and channels.regstatus != 'd' and
                                          subscriptions.iduser = users.iduser and users.regstatus = 'a'
                                    order by tag";

                        $wres = mysql_query($wquery);
                        $wcountchn = mysql_num_rows($wres);

                        $wstr = "$wdevicetag;$wcountchn";

                        while ( $wvetor = mysql_fetch_row($wres) ) $wstr .= ";" . $wvetor[0] . ";" . $wvetor[1] . ";" . $wvetor[2] . ";" . $wvetor[3] . ";" . $wvetor[4];

                        $wmd5list = md5("$wstr");

#                       Retrieve new messages

                        $wquery = "select channels.tag, messages.dateincl, messages.idmessage, messages.regstatus, messages.dateterm, medias.mediatext, medias.mediaurl
                                     from channels, devices, subscriptions, messages, users, medias
                                    where devices.iddevice = '$wid' and devices.regstatus = 'a' and
                                          devices.iduser = subscriptions.iduser and subscriptions.regstatus = 'a' and
                                          subscriptions.idchannel = channels.idchannel and channels.regstatus = 'a' and
                                          channels.iduser = users.iduser and users.regstatus = 'a' and
                                          subscriptions.idchannel = messages.idchannel and subscriptions.iduser = messages.iduser and
                                          (messages.regstatus = 'p' or messages.regstatus = 's') and messages.dateterm >= '$wnow' and
                                          messages.idchannel = medias.idchannel and messages.mediamd5 = medias.mediamd5 and
                                          messages.idmessage > '$wlastmsg'
                                    order by channels.tag, messages.idmessage";

                        $wres    = mysql_query($wquery);
                        $wnumreg = mysql_num_rows($wres);

#                       Build response

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup>";
                        $wresponse = $wresponse . "<md5>$wmd5list</md5>";

                        $wnewterm = gmdate("Y-m-d H:i:s", strtotime("+24 hours"));

                        while ( $wvetor = mysql_fetch_row($wres) )
                        {

                            $wtag       = $wvetor[0];
                            $wdateincl  = $wvetor[1];
                            $widmessage = $wvetor[2];
                            $wregstatus = $wvetor[3];
                            $wdateterm  = $wvetor[4];
                            $wmsgtext   = $wvetor[5];
                            $wmsgurl    = $wvetor[6];

#                           Add new message to the response

                            $wresponse .= "<msg>$wtag;$widmessage;$wdateincl;$wmsgtext;$wmsgurl</msg>";

#                           If message not sent yet, update status to "sent" and time live to 24h

                            if ( $wregstatus == "p" )
                            {

                                if ( $wdateterm < $wnewterm ) $wquery1 = "update messages set regstatus = 's'                         where idmessage = $widmessage";
                                else                          $wquery1 = "update messages set regstatus = 's', dateterm = '$wnewterm' where idmessage = $widmessage";

                                $wres1 = mysql_query($wquery1);

                            }

                        }

                        $wresponse .= "</followzup>";

                    }

# ========================================================================================
#
#   LSUB command - LIST CHANNELS
#
#      Param:  FZUP_STAMP   <stp> = stamp
#              FZUP_COMMAND <com> = lsub
#              FZUP_LASTSEQ <seq> = sequence
#
#      Return: <tag>Device-tag</tag>                                              Device Tag
#              <cnt>Channel-count</cnt>                                           Channels count
#              <chn>Channel-tag;Subscription-code;MD5-icon;flag-responseurl</chn> Channels subscription list
#
# ========================================================================================

                    elseif ( $wcom == "lsub" )
                    {

#                       Retrieve Channels subscriptions list

                        $wquery = "select tag, subscode, md5icon, if(responseurl='','n','y')
                                     from devices, subscriptions, channels, users
                                    where devices.iddevice = '$wid' and devices.regstatus = 'a' and
                                          devices.iduser = subscriptions.iduser and subscriptions.regstatus = 'a' and
                                          subscriptions.idchannel = channels.idchannel and channels.regstatus != 'd' and
                                          channels.iduser = users.iduser and users.regstatus = 'a'
                                    order by tag";

                        $wres = mysql_query($wquery);
                        $wcountchn = mysql_num_rows($wres);

#                       Build response

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup>";
                        $wresponse = $wresponse . "<tag>$wdevicetag</tag>";
                        $wresponse = $wresponse . "<cnt>$wcountchn</cnt>";

                        while ( $wvetor = mysql_fetch_row($wres) ) $wresponse .= "<chn>"  . $wvetor[0] . ";" . $wvetor[1] . ";" . $wvetor[2] . ";" . $wvetor[3] . "</chn>";

                        $wresponse .= "</followzup>";

                    }

# ========================================================================================
#
#   RESP command - SEND RESPONSE TO CHANNEL
#
#      Param:  FZUP_STAMP    <stp> = stamp
#              FZUP_COMMAND  <com> = resp
#              FZUP_LASTSEQ  <seq> = sequence
#              FZUP_CHANNEL  <chn> = channel tag
#              FZUP_RESPONSE <res> = response text (char 60)
#
# ========================================================================================

                    elseif ( $wcom == "resp" )
                    {

#                       Sanitize parameters

                        $wtag  = sanitizeTag($wxml->chn);
                        $wsend = substr(sanitizeText($wxml->res),0,60);

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup></followzup>";

#                       Verify response

                        if ( $wsend == "" ) $wretcode = "7272";

                        else
                        {

#                           Retrieve valid Channel attributes

                            $wquery  = "select channels.idchannel, channels.responseurl, pkeys.pkpri
                                          from channels, pkeys
                                         where channels.tag = BINARY '$wtag' and channels.regstatus != 'd' and channels.idkey = pkeys.idkey and
                                               channels.idchannel in (select idchannel from subscriptions where iduser = '$widuser')";

                            $wres    = mysql_query($wquery);
                            $wnumreg = mysql_num_rows($wres);

#                           Verify Channel is ok

                            if ( $wnumreg == 0 ) $wretcode = "7273";

                            else
                            {

#                               Retrieve attributes

                                $wvetor     = mysql_fetch_row($wres);
                                $widchannel = $wvetor[0];
                                $wurl       = $wvetor[1];
                                $wpri64     = $wvetor[2];

                                $wpri = base64_decode($wpri64);

                                if ( $wurl != "" )
                                {

#                                   Encrypt and encode message using Private RSA key

                                    $wdecrypt    = "$wnow;$widuser;$wsend";
                                    $werrorssl   = openssl_private_encrypt($wdecrypt, $wencrypt, $wpri);
                                    $wencrypt64  = base64_encode($wencrypt);
                                    $wpostfields = array ( "fzupidchannel" => "$widchannel", "fzupresponse" => "$wencrypt64" );

#                                   Send POST to Channel ResponseURL

                                    $fzup_ch   = curl_init();

                                    curl_setopt ( $fzup_ch, CURLOPT_URL, "$wurl" );
                                    curl_setopt ( $fzup_ch, CURLOPT_POST, 1);
                                    curl_setopt ( $fzup_ch, CURLOPT_HTTPHEADER, array ( "Content-Type: application/x-www-form-urlencoded" ) );
                                    curl_setopt ( $fzup_ch, CURLOPT_POSTFIELDS, http_build_query($wpostfields) );
                                    curl_setopt ( $fzup_ch, CURLOPT_RETURNTRANSFER, true );

                                    $fzup_resp = curl_exec($fzup_ch);

                                    $fzup_errno = curl_errno($fzup_ch);

                                    curl_close($fzup_ch);

                                }

                            }

                        }

                    }

# ========================================================================================
#
#   ICON command - GET ICONS
#
#      Param:  FZUP_STAMP   <stp> = stamp
#              FZUP_COMMAND <com> = icon
#              FZUP_LASTSEQ <seq> = sequence
#              FZUP_CHANNEL <chn> = tag,tag... (tag list)
#
#      Return: <ico>icon-string</ico> (null = invalid tag)
#
# ========================================================================================

                    elseif ( $wcom == "icon" )
                    {

#                       Sanitize parameters

                        $wtaglist = explode(",",preg_replace("/[^A-Za-z0-9\-\,]/","",$wxml->chn));

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup>";

                        foreach ( $wtaglist as $wtag )
                        {

#                           Retrieve icon for each Channel

                            $wquery1 = "select channels.channelicon
                                          from channels, users
                                         where channels.regstatus != 'd' and channels.tag = BINARY '$wtag' and
                                               channels.iduser = users.iduser and users.regstatus = 'a'";

                            $wres1 = mysql_query($wquery1);
                            $wnumreg1 = mysql_num_rows($wres1);

#                           Set null icon when invalid Channel

                            if ( $wnumreg1 == 0 )
                            {
                                $wretcode = "7232";
                                $wresponse .= "<ico>null</ico>";
                            }

                            else
                            {

#                               Retrieve attributes

                                $wvetor1    = mysql_fetch_row($wres1);
                                $wicon      = $wvetor1[0];

#                               Add icon to response

                                $wresponse .= "<ico>$wicon</ico>";

                            }

                        }

                        $wresponse .= "</followzup>";

                    }

# ========================================================================================
#
#   LKUP command - SEARCH CHANNELS
#
#      Param:  FZUP_STAMP   <stp> = stamp
#              FZUP_COMMAND <com> = lkup
#              FZUP_LASTSEQ <seq> = sequence
#              FZUP_CHANNEL <chn> = search tag
#              FZUP_MORE    <mor> = search more
#
#      Return: <chn>Channel-tag;Flag-private;Flag-private-code;MD5-icon;brief</chn> Search list result
#              <mor>more-tag</mor>                                                  Continuation tag
#
# ========================================================================================

                    elseif ( $wcom == "lkup" )
                    {

#                       Sanitize parameters

                        $wtag  = sanitizeTag($wxml->chn);
                        $wmore = sanitizeTag($wxml->mor);

#                       Set search list result limit

                        $wlimit = 10;

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup>";

#                       Verify minimum length for search parameter

                        if ( strlen($wtag) < 3 ) $wretcode = "7242";

                        else
                        {

#                           Retrieve result list count for public and private channels

                            $wquery = "select
                                           ( select count(*)
                                               from channels
                                              where channels.regstatus != 'd' and channels.channeltype = 'u' and channels.tag like '$wtag%' and channels.tag > '$wmore' and
                                                    channels.idchannel not in (select idchannel from subscriptions where iduser = '$widuser' and regstatus = 'a') ) as total1,
                                           ( select count(*)
                                               from channels
                                              where channels.regstatus != 'd' and channels.channeltype = 'r' and channels.tag = BINARY '$wtag' and channels.tag > '$wmore' and
                                                    channels.idchannel not in (select idchannel from subscriptions where iduser = '$widuser' and regstatus = 'a') ) as total2";

                            $wres    = mysql_query($wquery);
                            $wvetor  = mysql_fetch_row($wres);
                            $wtotal1 = $wvetor[0];
                            $wtotal2 = $wvetor[1];

#                           Retrieve Channel attributes

                            $wquery = "(select tag, 'n', 'n', md5icon, briefing
                                          from channels
                                         where channels.regstatus != 'd' and channels.channeltype = 'u' and channels.tag like '$wtag%' and channels.tag > '$wmore' and
                                               channels.idchannel not in (select idchannel from subscriptions where iduser = '$widuser' and regstatus = 'a') )
                                        union
                                       (select tag, 'y', if(privcode='','n','y'), md5icon, briefing
                                          from channels
                                         where channels.regstatus != 'd' and channels.channeltype = 'r' and channels.tag = BINARY '$wtag' and channels.tag > '$wmore' and
                                               channels.idchannel not in (select idchannel from subscriptions where iduser = '$widuser' and regstatus = 'a') )
                                         order by 1 limit $wlimit";

                            $wres = mysql_query($wquery);

                            $wlast = "";

#                           Build response

                            while ( $wvetor = mysql_fetch_row($wres) )
                            {
                                $wresponse .= "<chn>"  . $wvetor[0] . ";" . $wvetor[1]  . ";" . $wvetor[2]  . ";" . $wvetor[3] . ";" . base64_encode($wvetor[4]) . "</chn>";
                                $wlast = $wvetor[0];
                            }

#                           Add continuation tag when there are more results to retrieve

                            if ( ( $wtotal1 + $wtotal2 ) > $wlimit ) $wresponse .= "<mor>$wlast</mor>";
                            else                                     $wresponse .= "<mor></mor>";

                        }

                        $wresponse .= "</followzup>";

                    }

# ========================================================================================
#
#   SCHN command - SUBSCRIBE CHANNEL
#
#      Param:  FZUP_STAMP    <stp> = stamp
#              FZUP_COMMAND  <com> = schn
#              FZUP_LASTSEQ  <seq> = sequence
#              FZUP_CHANNEL  <chn> = channel tag
#              FZUP_PRIVCODE <pvc> = private code
#
# ========================================================================================

                    elseif ( $wcom == "schn" )
                    {

#                       Sanitize parameters

                        $wtag  = sanitizeTag($wxml->chn);
                        $wcode = sanitizeText($wxml->pvc);

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup></followzup>";

#                       Retrieve Channel attributes

                        $wquery = "select channels.idchannel, channels.welcome, channels.channeltype, channels.privcode, channels.welcomeurl
                                     from channels, users
                                    where channels.tag = BINARY '$wtag' and channels.regstatus != 'd' and
                                          channels.iduser = users.iduser and users.regstatus = 'a' and
                                          channels.idchannel not in (select idchannel from subscriptions where iduser = '$widuser' and regstatus = 'a')";

                        $wres    = mysql_query($wquery);
                        $wnumreg = mysql_num_rows($wres);

#                       Verify Channel is ok

                        if ( $wnumreg == 0 ) $wretcode = "7252";

                        else
                        {

#                           Retrieve attributes

                            $wvetor     = mysql_fetch_row($wres);
                            $widchannel = $wvetor[0];
                            $welcome    = $wvetor[1];
                            $wtype      = $wvetor[2];
                            $wprivcode  = $wvetor[3];
                            $welcomeurl = $wvetor[4];

#                           Verify Channel is Private and Private Code match

                            if ( $wtype == "r" and $wprivcode != "" and $wprivcode != $wcode ) $wretcode = "7253";

                            else
                            {

#                               Generate random Subscription Code

                                $wsubscode = rand(10000000,99999999);

#                               Verify subscription already exists and status is "deleted"

                                $wquery  = "select regstatus from subscriptions where idchannel = '$widchannel' and iduser = '$widuser'";
                                $wres    = mysql_query($wquery);
                                $wnumreg = mysql_num_rows($wres);

#                               Add a new subscription or update the old one

                                if ( $wnumreg == 0 )
                                     $wquery = "insert into subscriptions (iduser, idchannel, dateincl, subscode, regstatus)
                                                                   values ('$widuser','$widchannel','$wnow','$wsubscode','a')";
                                else
                                     $wquery = "update subscriptions set subscode = '$wsubscode', regstatus = 'a', dateincl = utc_timestamp()
                                                 where idchannel = '$widchannel' and iduser = '$widuser'";

                                $wres   = mysql_query($wquery);

#                               Verify welcome message exists

                                if ( $welcome != "" )
                                {

#                                   Encode welcome message and URL

                                    $welcome    = base64_encode($welcome);
                                    $welcomeurl = base64_encode($welcomeurl);

                                    $wdateterm = gmdate("Y-m-d H:i:s", strtotime("+24 hours"));

#                                   Create message media (text and URL)

                                    $wmediamd5 = md5("$welcome;$welcomeurl");
                                    $wquery2   = "insert into medias (idchannel, mediamd5, mediatext, mediaurl) values ('$widchannel', '$wmediamd5', '$welcome', '$welcomeurl')";
                                    $wres2     = mysql_query($wquery2);

#                                   Register message

                                    $wquery = "insert into messages (idchannel, iduser, mediamd5, dateincl, dateterm, hours, regstatus)
                                                             values ('$widchannel', '$widuser', '$wmediamd5', '$wnow', '$wdateterm', 24, 'p')";

                                    $wres   = mysql_query($wquery);

                                }

                            }

                        }

                    }

# ========================================================================================
#
#   UCHN - UNSUBSCRIBE CHANNEL
#
#      Param:  FZUP_STAMP    <stp> = stamp
#              FZUP_COMMAND  <com> = uchn
#              FZUP_LASTSEQ  <seq> = sequence
#              FZUP_CHANNEL  <chn> = channel tag
#
# ========================================================================================

                    elseif ( $wcom == "uchn" )
                    {

#                       Sanitize parameters

                        $wtag = sanitizeTag($wxml->chn);

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup></followzup>";

#                       Retrieve Channel attributes

                        $wquery = "select channels.idchannel
                                     from channels
                                    where channels.tag = BINARY '$wtag' and channels.regstatus != 'd' and
                                          channels.idchannel in (select idchannel from subscriptions where iduser = '$widuser')";

                        $wres    = mysql_query($wquery);
                        $wnumreg = mysql_num_rows($wres);

#                       Verify Channel is ok

                        if ( $wnumreg == 0 ) $wretcode = "7262";

                        else
                        {

#                           Retrieve attributes

                            $wvetor     = mysql_fetch_row($wres);
                            $widchannel = $wvetor[0];

#                           Delete subscription (set status)

                            $wquery = "update subscriptions set regstatus = 'd' where idchannel = '$widchannel' and iduser = '$widuser'";

                            $wres   = mysql_query($wquery);

#                           Delete pending messages (set status);

                            $wquery = "update messages set regstatus = 'd' where idchannel = '$widchannel' and iduser = '$widuser' and regstatus != 'd'";

                            $wres   = mysql_query($wquery);

                        }

                    }

# ========================================================================================
#
#   DMSG - DELETE MESSAGE
#
#      Param:  FZUP_STAMP    <stp> = stamp
#              FZUP_COMMAND  <com> = icon
#              FZUP_LASTSEQ  <seq> = sequence
#              FZUP_MESSAGE  <msg> = idmessage
#
# ========================================================================================

                    elseif ( $wcom == "dmsg" )
                    {

#                       Sanitize parameters

                        $widmessage  = (int)$wxml->msg;

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup></followzup>";

#                       Verify Message-ID is ok

                        if ( $widmessage == 0 ) $wretcode = "7282";

                        else
                        {

#                           Retrieve valid message attributes

                            $wquery = "select idmessage
                                         from messages, subscriptions
                                        where messages.idmessage = $widmessage and messages.iduser = '$widuser' and
                                              messages.iduser = subscriptions.iduser and messages.idchannel = subscriptions.idchannel and
                                              subscriptions.regstatus = 'a'";

                            $wres    = mysql_query($wquery);
                            $wnumreg = mysql_num_rows($wres);

#                           Verify Message is ok

                            if ( $wnumreg == 0 ) $wretcode = "7282";

                            else
                            {

#                               Delete message (set status);

                                $wquery = "update messages set regstatus = 'd' where idmessage = $widmessage and iduser = '$widuser'";

                                $wres   = mysql_query($wquery);

                            }

                        }

                    }

# ========================================================================================
#
#   UREG - UNREGISTER DEVICE
#
#      Param:  FZUP_STAMP    <stp> = stamp
#              FZUP_COMMAND  <com> = ureg
#              FZUP_LASTSEQ  <seq> = sequence
#
# ========================================================================================

                    elseif ( $wcom == "ureg" )
                    {

#                       Delete Device (set status)

                        $wresponse = "<" . '?xml version="1.0" encoding="utf-8"?' . "><followzup></followzup>";

                        $wquery = "update devices set devicetag = concat('.',iddevice,'.',devicetag), regstatus = 'd' where iddevice = '$wid' and iduser = '$widuser'";

                        $wres   = mysql_query($wquery);

                        sleep(1);

                    }

#                   Encrypt and encode XML response

                    $wretframe1 = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $wkey3, $wresponse, MCRYPT_MODE_CBC, str_repeat(chr(0),16));
                    $wretframe  = base64_encode($wretframe1);

                }

            }

        }

    }

#   Clear XML response when any Return Code not "0" (request ok) nor "7101" (invalid sequence)

    if ( $wretcode != "0" and $wretcode != "7101" ) $wretframe = "";

#   Calculate MD5 hash for XML response

    if ( $wretframe != "" ) $wretmd5 = md5("$wretframe");

#   Build POST response including Return Code, Return Frame (Encrypted XML response) and hash MD5

    header("Content-Type: application/xml; charset=utf-8;");
    echo "<" . '?xml version="1.0" encoding="utf-8"?' . ">";
    echo "<followzup>";
    echo    "<retcode>$wretcode</retcode>";
    echo    "<retframe>$wretframe</retframe>";
    echo    "<retmd5>$wretmd5</retmd5>";
    echo "</followzup>";

?>


br-222-wsdevice.txt · Last modified: 2017/06/20 06:07 by admin

Page Tools