#!/usr/bin/perl
######################################################################
#
#   Copyright 2000 Phone.com, Inc.  All rights reserved.
#
#   Subject to the terms and conditions of the SDK License Agreement, 
#   Phone.com, Inc. hereby grants you the right to use the UP.SDK 
#   software and its related documentation.
#
#   The Phone.com name and logo and the family of terms carrying the "UP."
#   prefix are trademarks of Phone.com, Inc. All other brands and product 
#   names may be trademarks of the respective companies with which they 
#   are associated.
#
######################################################################

######################################################################
#
# sendalert.cgi - prefetch notification example (Windows-only)
#
#       This application returns a WML deck that allows the user
#       to send several different types of demo alerts back to
#       the phone via the UP.Link Messenger service.  
#
#       The application sends a "prefetch" notification type to
#       the UP.Link Messenger.  This results in the Messenger 
#       requesting the fetch.cgi companion script, which loads
#       the alert message and deck to the phone.   The notification
#       can be sent secure or non-secure.  The application must
#       provide an SSL certificate to post a secure notification.
#
# IMPORTANT: The application will only send alerts successfully
#            if the UP.Browser is connected to the UP.Link.  This
#            script will not work if called from the UP.Phone
#            Simulator in "HTTP Direct" mode.
#
#            The application calls the UP notification COM library
#            via the OLE package from ActiveState's Perl for 
#            Windows.  To download Perl for Windows, visit the
#            ActiveState website at www.ActiveState.com.  
#
#            You MUST set these constants in the source code for
#            this example to work from your own web environment:
#
#            $PREFETCH_URL           (for secure & non-secure)
#            $CERT_FILE, $PASSWORD   (for secure only) 
#
######################################################################

######################################################################
# AppUtils Loading and Configuration
######################################################################
# Include the apputils directory which has all the SDK utilities
BEGIN { push (@INC, "../apputils");	} # Path to SDK apputils

require 'DeckUtils.pl';

######################################################################
# Constants
######################################################################

#
# The Prefetch URL returns a digest containing an alert + WML deck.
#
# IMPORTANT:  Set this to the URL for your locally installed copy
#             of the fetch.cgi script.  The URL must be accessible 
#             via the public Internet.  If you send a secure 
#             notification, you must insure that your SSL certificate 
#             matches the server domain for the prefetch URL.  
#
$PREFETCH_URL = "http://updev.phone.com/dev/sdk.40/scripts/fetch.cgi";


# The TTL indicates how long the notification will remain pending in 
# the UP.Link Messenger's queue if it cannot be delivered.
#
$TTL = 1*60*60;

# Set to 1 if you require the UP.Link to support secure notifications.  
#
$REQUIRE_SECURE = 0;

# Path to the SSL certificate file and its password.
# NOTE: Backlashes (\) in path must be escaped for Perl.
#
$CERT_FILE = "c:\\config\\mycert.pem";
$PASSWORD  = "foobar";

# Tempory hack until we figure out how to reference COM Enum types
# from Perl (if possible).
#
$CHTTPStatusNoContent = "204";

#
# WML Decks
#
 
$HOME_DECK = '
<wml>

   <head>
      <meta forua="true" name="vnd.up.markable" content="true"/>
   </head>

   <card id="homecard" title="Send Alert">
      <do type="accept" label="Send">
         <go href="#c2"/>
      </do>
      <p>
         Alert demo:
         <select name="demo">
            <option value="DISPATCH">Dispatch</option>
            <option value="STOCK">Stock</option>
            <option value="MEETING">Meeting</option>
          </select>
      </p>
   </card>

   <card id="c2">
      <onevent type="onenterbackward">
         <prev/>
      </onevent>

      <do type="accept" label="Yes">
         <go href="?DEMO=$(demo)&amp;SECURE=yes"/>
      </do>

      <do type="options" label="No">
         <go href="?DEMO=$(demo)&amp;SECURE=no"/>
      </do>
      <p>
         Use SSL to secure?
      </p>
   </card>

</wml>';

$SUCCESS_DECK ='
<wml> 

   <head>
      <meta forua="true" name="vnd.up.markable" content="true"/>
   </head>

   <card>
      <p>
         Alert sent! <br/>
         Secure=%s
      </p>
   </card>

</wml>';


######################################################################
#
# Main routine 
#
###################################################################### 

# Read the HTTP headers for the subscriber number and UP.Link host
$subNo = $ENV{'HTTP_X_UP_SUBNO'};
$upLink = $ENV{'HTTP_X_UP_UPLINK'};

# Get the CGI variables.
%cgiVars = &AppUtils::ParseCGIVars();
$demo   = $cgiVars{"DEMO"};
$secure = $cgiVars{"SECURE"};

if (!defined($demo))
{
    # Output the HOME deck if no demo variable is found
    &AppUtils::OutputDeck($HOME_DECK);
}
else
{
    # Post a prefetch notification
    &PostPrefetch($subNo, $upLink, $demo, $secure);
}

######################################################################
#
# PostPrefetch
#
# Post a 'prefetch' notification to the UP.Link Messenger.
#
###################################################################### 
sub PostPrefetch
{
    local($subid, $server, $demo, $secure) = @_;
        
    $url = $PREFETCH_URL."?NEXT=".$demo;
    $ttl = $TTL; 

    use OLE;

    # Create a secure or non-secure notification object
    if ($secure eq "yes") {

        $ntfn = CreateObject OLE 'Ntfn3SClient.Ntfn3SClient.1';

    } else {

        $ntfn = CreateObject OLE 'Ntfn3Client.Ntfn3Client.1';
    }

    if (!$ntfn) {

        &AppUtils::ErrorExit(1, "Ntfn class error");

    } else {

        # Set the UP.Link server name
        $ntfn->NtfnSetHost($server);

        if ($secure eq "yes") {
    
            # Set the Certificate and Password
            $ntfn->NtfnLoadCertAndKey($CERT_FILE, $PASSWORD);
    
            # Set the fail-over state
            $ntfn->NtfnRequireSecureConnection($REQUIRE_SECURE);
        }
    
        # Post the prefetch notification
        $ntfn->NtfnPostPrefetch($subid, $url, $ttl);
    
        # Get the notification return status
        $result = $ntfn->NtfnGetLastResult();

        # StatusNoContent indicates success
        if ($result != $CHTTPStatusNoContent) {
        
            $err = $ntfn->NtfnGetErrorDetail();
            if ($err eq "") {

                &AppUtils::ErrorExit($result, "No error detail");
     
            } else {

                &AppUtils::ErrorExit($result, $err);
            }

        } else {

            $deck = sprintf($SUCCESS_DECK, $secure);
            &AppUtils::OutputDeck($deck);
        }
    }
}
