<?

// example.php

// Dated: 2009 November 14.

// Easy to get started example script.

// For the 20091114 finarea.php script

// This example now also shows how to use the non .com services.

// Simon G.

// ********************* Below is an EXAMPLE usage of the fincheck.php functions *********************************************
// *********

include("fincheck.php"); // Include the functions.

// ****** SETTINGS **************************************************************************************************

// Users array
// For each of your Finarea / Betamax accounts specify the user,pass and service below.
// You can set an "auth" to something secret if you want.
// If so then it is also required when running this example script.
//
// Then specify the usernumber when running this script.

// Don't forget to un-comment this !!

/*
$aUsers = array (array("user"=>"MYUSERNAME", "pass"=>"MYPASSWORD", "service"=>"MYSERVICE", "auth"=>"MYSECRET"),
        array("user"=>"MYUSERNAME", "pass"=>"MYPASSWORD", "service"=>"voipstunt"),
        array("user"=>"MYUSERNAME", "pass"=>"MYPASSWORD", "service"=>"sparvoip.de"));
*/

//

// NO MORE SETTINGS TO EDIT BELOW THIS LINE *****************************************************************************

function usage() {

    
$sOutput "<p>\n";
    
$sOutput .= "usage: ".$_SERVER['PHP_SELF'].
            
"?cmd=[freedays|creditcents|call|sms|tariffwizard|callforward]&usernumber=usernumber&auth=yoursecret [monthsago|daysago|sourcenumber|smstext] [destinationnumber]<br />\n";
    
$sOutput .= " Extra options when sending an sms. After [destinationnumber] there is [monthtosend] [daytosend] [hourtosend] [minutetosend] [gmt](difference in hours) and [callerid]<br />\n";
    
$sOutput .= " Extra options when using the callforward command. After [destinationnumber] there is " .
            
"fwdtype=[-1|0|1|2|3] for  Get current status, Never, Always, When offline and When offline or away.<br />\n";

    
$sOutput .= "</p>\n";

    
$sOutput .= "<p>\n";

    
$sExUsage $_SERVER['PHP_SELF']."?cmd=creditcents&usernumber=1&auth=yoursecret";

    
$sOutput .= "eg. <a href='".$sExUsage."'>".$sExUsage."</a>\n";
    
$sOutput .= "</p>\n";

    
$sOutput .= "<p>\n";

    
$sOutput .= "You can also run this php script as a shell or cron job ... <br />\n";
    
$sOutput .= "/pathToPHP/php " $_SERVER['PHP_SELF']." 'cmd=creditcents&usernumber=1&auth=yoursecret'<br />\n";

    
$sOutput .= "</p>\n";

    
$sOutput .= "<p>\n";
    
$sOutput .= "Use the example form below to get started.\n";
    
$sOutput .= "</p>\n";

    return 
$sOutput;
}

function 
html_select($sName,$aItems,$sSelected=""){
    
// Where $aItems is an array of POST VALUE => DISPLAY VALUE

    
$sOutput "";

    
$sOutput .= "<select name='"$sName ."'>\n";

    foreach (
$aItems as $sItemName => $sItemDispName){
        
$sOutput .= "<option ";

        if ( 
$sItemName == $sSelected ) { // Then this one was selected
            
$sOutput .= "selected='selected'";
        }

        
$sOutput .= "value='".$sItemName."' >".$sItemDispName."</option>\n";

    }

    
$sOutput .= "</select>\n";
    return 
$sOutput;
}

function 
num_to_array($iNum,$iStart=1){
    
$aArray "";
    for (
$i $iStart$i <= $iNum$i++) {
        
$aArray[$i] = $i;
    }
    return 
$aArray;
}

if (! 
function_exists('array_combine')) { // Exists from PHP5
        
function array_combine($a1$a2){
                if(
count($a1) != count($a2))
                        return 
false;

                if(
count($a1) <= 0)
                        return 
false;

                
$a1 array_values($a1);
                
$a2 array_values($a2);

                
$output = array();

                for(
$i 0$i count($a1); $i++)
                {
                        
$output[$a1[$i]] = $a2[$i];
                }

                return 
$output;
        }
}


function 
print_form() {

    
// TODO Get rid of these globals !!!
    
global $sCommand$aUsers$iSourceNum$iDestNum$iFwdType$sMsg$iUserNumber$sAuth,
        
$iMonthToSend$iDayToSend$iHourToSend$iMinuteToSend$iGmtDiff$iCallerId;

    
$sOutput "EXAMPLE FORM:<br />\n";

    
$sOutput .= "<p>\n";
    
$sOutput .= "<form method='GET'>\n";

    
$aCmds = array("","freedays","creditcents","call","sms","tariffwizard""callforward");
    
$aCmds array_combine($aCmds$aCmds); // Make the keys and values the same.
    
$sOutput .= "CMD: " html_select("cmd"$aCmds,$sCommand )."<br />\n";

    
// List of user numbers.
    
$aNums "";
    
$aNums num_to_array(count($aUsers));
    
$sOutput .= "USERNUMBER: "html_select("usernumber"$aNums$iUserNumber)."<br />\n";
    
//

    
$sOutput .= "AUTH: <input type='password' name='auth' value='' /><br />\n";

//    $sOutput .= "MONTHSAGO(creditcents): ". html_select("monthsago", num_to_array(12,0))."<br />\n";

//    $sOutput .= "DAYSAGO(creditcents): ". html_select("daysago", num_to_array(31,0))."<br />\n";

    
$sOutput .= "SOURCENUMBER(call): <input type='text' name='sourcenumber' value='".$iSourceNum."' /><br />\n";
    
$sOutput .= "CALLERID(sms): <input type='text' name='callerid' value='".$iCallerId."' /><br />\n";

    
$sOutput .= "SMSTEXT(sms): <input type='text' name='smstext' maxlength='160' value='".$sMsg."' /><br />\n";

    
$sOutput .= "DESTINATIONNUMBER(call|sms|tariffwizard|callforward): <input type='text' name='destinationnumber' value='".$iDestNum.
            
"' /><br />\n";

    
$sOutput .= "<hr />\n";
    
$sOutput .= "<h4>Leave these at 0 to send SMS NOW.</h4>\n";
    
$sOutput .= "MONTHTOSEND(sms): "html_select("monthtosend"num_to_array(12,0),$iMonthToSend)."<br />\n";
    
$sOutput .= "DAYTOSEND(sms): "html_select("daytosend"num_to_array(31,0),$iDayToSend)."<br />\n";
    
$sOutput .= "HOURTOSEND(sms): "html_select("hourtosend"num_to_array(24,0),$iHourToSend)."<br />\n";
    
$sOutput .= "MINUTETOSEND(sms): "html_select("minutetosend"num_to_array(60,0),$iMinuteToSend)."<br />\n";
    
$sOutput .= "GMTDIFF(sms): "html_select("gmt"num_to_array(12,-12),$iGmtDiff)."<br />\n";


    
$sOutput .= "<hr />\n";

    
$sOutput .= "<h4> Call Forward:</h4>\n";
    
// "fwdtype=[0|1|2|3] for  Never, Always, When offline and When offline or away.<br />\n";
    
$sOutput .= "Type: " html_select("fwdtype", array(-=> "Check"=> "Never"=> "Always"
                
=> "When offline"=> "When offline or away"),$iFwdType)."<br />\n";

    
$sOutput .= "<hr />\n";

    
$sOutput .= "<input type='submit' name='submit' />\n";
    
$sOutput .= "</form>\n";
    
$sOutput .= "</p>\n";

    return 
$sOutput;
}

// Here we set all the required GETs
$iUserNumber = (isset($_GET['usernumber'])) ? $_GET['usernumber'] : 1// If unspecified then use the 1st user 
$sCommand = (isset($_GET['cmd'])) ? $_GET['cmd'] : ""// Check for a command.
$sAuth = (isset($_GET['auth'])) ? $_GET['auth'] : ""// Auth if set.
$iSourceNum $_GET['sourcenumber'];
$iDestNum $_GET['destinationnumber'];
$sMsg $_GET['smstext'];

// The optional sms vars. [monthtosend] [daytosend] [hourtosend] [minutetosend] [gmt difference in hours]
$iMonthToSend $_GET['monthtosend'];
$iDayToSend $_GET['daytosend'];
$iHourToSend $_GET['hourtosend'];
$iMinuteToSend $_GET['minutetosend'];
$iGmtDiff $_GET['gmt'];
$iCallerId $_GET['callerid'];
//
// The optional callforward vars. [fwdtype]
$iFwdType $_GET['fwdtype'];
//

// If there is an auth for this user check it
if (isset($aUsers[($iUserNumber 1)]['auth'])){ // iUserNumber - 1 because arrays start at 0 NOT 1
    
$sDebugAuth "";
    if (
$sAuth <> ""){
        if ( 
$aUsers[($iUserNumber 1)]['auth'] <> $sAuth){
            
$bAuth FALSE// Auth required but did NOT match.
            
$sDebugAuth .= " Auth required but did NOT match. You used auth=\"".$sAuth."\" for user number ".$iUserNumber.".";
        } else {
            
$bAuth TRUE// Auth required and was correct.
            
$sDebugAuth .= " Auth required and was correct.";
        }
    } else {
        
$bAuth FALSE// Auth required but was not specified. ($_GET['auth'] NOT set)
        
$sDebugAuth .= " Auth required but was not specified.";
    }
} else {
        
$bAuth TRUE// Auth NOT required.
        
$sDebugAuth .= " Auth NOT required.";
}

if ( 
$bAuth === TRUE ){ // All ok then set-up the finarea account details. 
    
$USER $aUsers[($iUserNumber 1)]['user']; // iUserNumber - 1 because arrays start at 0 NOT 1
    
$PASS $aUsers[($iUserNumber 1)]['pass'];
    
$SERVICE $aUsers[($iUserNumber 1)]['service'];

    
$iMatchNonDotCom preg_match('/\./'$SERVICE$aMatches); // Look for a dot.
    
if ( $iMatchNonDotCom == ) { // .com Betamax service
        
$iMatchURLType preg_match('/intervoip/'$SERVICE$aMatches); // Look for intervoip service

        
print_r($aMatches);

        if ( 
$iMatchURLType == ){ // Normal .com Betamax service
            // echo "Betamax .com type 1 <br />\n";
        //    $BASEURL = "https://myaccount.".$SERVICE.".com/clx";
            
$BASEURL "https://www.".$SERVICE.".com/myaccount"// Where $SERVICE is intervoip
        
} else { // New Betamax service
            // echo "Betamax .com type 2 <br />\n";
            
$BASEURL "https://www.".$SERVICE.".com/myaccount"// Where $SERVICE is intervoip
        
}


    } else { 
// Non .com service eg. someservice.de

        
$BASEURL "https://myaccount.".$SERVICE."/clx";
    }
}


// ************************************** PRG STARTS HERE ***************************************************************
header('Content-Type: text/html; charset=utf-8');


if (empty(
$sCommand)){ // Then nothing to do !!
    
echo usage(); // Show the usage / help.
    
echo print_form(); // The demo html form.
    
exit;
}

// DEBUG 
echo "<b><font color=\"red\">DEBUG: Auth [".$sDebugAuth."]</font></b><br />\n";
//

if ( $bAuth === FALSE ){ // Then auth was required and failed
    
echo "ERROR: auth is required and FAILED!!<br />\n";
    echo 
print_form(); // The demo html form.
    
exit;
}
// Check that USER PASS and SERVICE are set
if ((empty($USER))||(empty($PASS))||(empty($SERVICE))){

    echo 
"ERROR: USER PASS or SERVICE is NOT set!!<br />\n";
    echo 
print_form(); // The demo html form.
    
exit;
}

// Try to login
list ($bResult$iResult$sDebug) = login($USER$PASS);
if (
$bResult == 0){ 

    echo 
"ERROR: Login Failed!!<br />\n";
    echo 
$sDebug;
    echo 
"<hr/>\n";
    echo 
print_form(); // The demo html form.
    
exit;

}

// #### go to index page as required by META Refresh .
list($sMainPage$iTSPtime$iResult$sDebug) = gomainpage();
echo 
$sDebug// Lets print the debug here.

// Now do something as requested or not.
switch ($sCommand){

    case 
"creditcents":

        list(
$iCents$iResult$sDebug) = creditcents($sMainPage); 
        echo 
"Credit cents is [".$iCents."] or &euro;".($iCents 100)."<br />\n";

    break;


    case 
"freedays":
        
// Freedays remaining:
        
list($iFreeDays$iResult$sDebug) = freedays($sMainPage); 

        echo 
"Free days remaining is [".$iFreeDays."]<br />\n";
        
    break;

    case 
"call":

        list(
$sResult$iResult$sDebug) = call($iSourceNum$iDestNum);        
        if (
$iResult 0){
            echo 
"ERROR:"$sResult."<br />\n";
        } else {
            echo 
"Call setup from [".$iSourceNum."] to [".$iDestNum."]<br />\n";
            
// echo $sDebug ;
        
}
    
    break;

    case 
"sms":

        
//OLD Function
        /*
        list($sResult,$iCents) = sms($iDestNum,$sMsg,$iMonthToSend,$iDayToSend,$iHourToSend,
                    $iMinuteToSend,$iGmtDiff,$iCallerId,$iTSPtime);
        */
        
        
if ((!empty($iMonthToSend))||(!empty($iDayToSend))||(!empty($iHourToSend))||(!empty($iMinuteToSend))){
            
// Timed SMS
            
echo "DEBUG : Timed SMS example.<br />\n";
            
$iTime gmmktime($iHourToSend$iMinuteToSend,0,$iMonthToSend$iDayToSend);
        } else {
            
// NOW SMS
            
echo "DEBUG : Now SMS example.<br />\n";
            
$iTime $iTSPtime// Use the TSPtime (Service providers current time)
            
$iGmtDiff 0// $iTSPtime should be GMT
        
}

        list(
$sResult$iCents$iResult$sDebug) = sms($iDestNum,$sMsg,$iTime,$iGmtDiff,$iCallerId);

        if (
$iResult 0){
            echo 
"ERROR:"$sResult."<br />\n";
            echo 
"<hr />\n";
            echo 
$sDebug;
        } else {
            echo 
"Message sent to service provider.<br />\n";
            echo 
"Credit cents is [".$iCents."] or &euro;[".($iCents 100)."]<br />\n";
        }

        break;


    case 
"tariffwizard":

        list(
$sUrl$iRatePerMinute$iCallSetup$iResult$sDebug) = tariffwizard($iDestNum);
        echo 
"<table>\n";
        echo 
"<tr><td>Destination number: </td><td>".$iDestNum."</td></tr>\n";
        echo 
"<tr><td>Service provider URL: </td><td>".$sUrl."</td></tr>\n";
        echo 
"<tr><td>Rate per Min.: </td><td>".$iRatePerMinute."</td></tr>\n";
        echo 
"<tr><td>Call setup cost: </td><td>".$iCallSetup."</td></tr>\n";
        echo 
"</table>\n";

    break;

    case 
"callforward":

        list(
$iCurrentType$iCurrentNumber$iResult$sDebug) = callforward($iFwdType$iDestNum);
        
$aCallFwdTypes = array (=> "Never"=> "Always" ,
                                
=> "When offline"=> "When offline or away");

        if ( 
$iResult == ) {
            
$sCurrentType $aCallFwdTypes[$iCurrentType];
            echo 
"CallForwarding is now set as Type[".$sCurrentType."(".$iCurrentType.")] Number[".$iCurrentNumber."]<br />\n";
            
// echo "<h2>Debug</h2>\n". $sDebug; // DEBUG
            
        
} else {
            echo 
"Oops something went wrong ... <br />\n";
            echo 
$sDebug;
        }
        
    break;

    default:

        echo 
"ERROR: UNKNOWN cmd [".$sCommand."]<br />\n";
        echo 
usage();
}

list (
$sContent,$iThisResult$sThisDebug) = logoff();

    
//$sContent = $sMainPage;
    //echo "CONTENT [".htmlentities ($sContent)."]<br />\n";

echo print_form(); // The demo html form.
?>

END OF EXAMPLE