#!/usr/local/bin/perl5.003
############################################################################
#
#   (c) Copyright 1997-1999, Unwired Planet, Inc.  All Rights Reserved.
#
#
#   Subject to the terms and conditions of the SDK LICENSE AGREEMENT,
#   Unwired Planet, Inc. hereby grants you a license to use the UP.SDK(TM)
#   software and its related documentation.
#
#   The following are trademarks or registered trademarks of Unwired Planet,
#   Inc. All Rights Reserved: Powered-By UP(TM), Powered-By UP logo((TM)),
#   Visual Voicemail(TM), Unwired Planet(TM) name, Unwired Planet logo((TM)),
#   uplanet.com(R), UP.Access(TM), UP.Admin(TM), UP.Alert(TM),
#   UP.Application(TM), UP.Bookmarks(TM), UP.Browser(TM), UP.Cast(TM),
#   UP.Dev(TM), UP.Developer(TM), UP.Device(TM), UP.Directory(TM),
#   UP.Encrypt(TM), UP.Fax(TM), UP.HomePage(TM), UP.Link(TM), UP.Mail(TM),
#   UP.Market(TM), UP.Monitor(TM), UP.Notify(TM), UP.Organizer(TM),
#   UP.Pager(TM), UP.Phone(R), UP.PIM(TM), UP.SDK(TM), UP.Simulator(TM),
#   UP.Secure(TM), UP.Transact(TM), UP.University(TM), UP.Web(TM),
#   and any other term carrying the "UP." prefix. All other brand,
#   company and product names are used for identification purposes only and
#   may be trademarks that are the sole property of their respective owners.
#
############################################################################

######################################################################
#
# notify.cgi -  notification example (Windows-only)
#
#     - This application returns an HDML deck that allows the user
#       to send several different types of notifications back to
#       the phone via the UP.Link Messenger service.  
#
#       When sending an alert, the application sends an "alert" 
#       notification type to the UP.Link Messenger with a URL of ?DEMO=TIME.
#       This URL calls notify.cgi and asks for the current time of day.
#       When Sending a CacheOp, the application sends a "cacheop" notification.
#       When Sending a Remove Alert, the appliction sends a RemoveAlertFromInbox
#       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 this constant in the source code for
#	     this example to work from your own web environment:
#
#		$CONTENT_URL           
#
######################################################################

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

require 'HDMLUtils.pl';

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

#
# PostAlert URL returns an alert with a pointer to HDML 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.  
#
$CONTENT_URL = "http://www.myserver.com/examples/scripts/notify.cgi?DEMO=TIME";

# 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;

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

#
# HDML Decks
#
 
$HOME_DECK =
    '<HDML version=2.0 markable=TRUE>
        <CHOICE NAME=notify KEY=demo>
            <ACTION TYPE=ACCEPT LABEL=Post TASK=GOSUB 
              VARS=demo=$(demo) DEST="?DEMO=$(demo)">
            <ACTION TYPE=SOFT1 LABEL=Inbox TASK=GO 
              DEST="device:status">
            Notify demo:
            <CE VALUE=ALERT>Send Alert
	    <CE VALUE=INVAL>Alert+Inval
            <CE VALUE=CACHE>Send CacheOp
            <CE VALUE=REMOVE>Remove Alert
        </CHOICE>
      </HDML>';

$SUCCESS_DECK =
    '<HDML version=2.0 TTL=0> 
	<DISPLAY>
	    <ACTION TYPE=ACCEPT TASK=CANCEL>
	    Alert sent!
	</DISPLAY>
    </HDML>';

$CACHE_DECK =
    '<HDML version=2.0 TTL=0> 
	<DISPLAY>
	    <ACTION TYPE=ACCEPT TASK=CANCEL>
	    CacheOp sent!
	</DISPLAY>
    </HDML>';

$REMOVAL_DECK =
    '<HDML version=2.0 TTL=0> 
	<DISPLAY>
	    <ACTION TYPE=ACCEPT TASK=CANCEL>
	    Alert Removed!
	</DISPLAY>
    </HDML>';

$TIME_DECK = 
    '<HDML version=2.0> 
	<DISPLAY>
	    <ACTION TYPE=ACCEPT TASK=CANCEL>
	    Cached at:
	    <BR><CENTER>%s
	</DISPLAY>
    </HDML>';
######################################################################
#
# 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"};



if($demo eq "ALERT"){
    # Post a prefetch notification
    &PostAlert($subNo, $upLink, $demo);
}
elsif($demo eq "INVAL"){
    #Post an Alert and Invalidate URL in Cache
    &PostAlertInval($subNo, $upLink, $demo);
}
elsif($demo eq "CACHE"){
    #Post a CacheOp to invalidate URL in Cache
    &PostCacheOp($subNo, $upLink, $demo);
}
elsif($demo eq "REMOVE"){
    #Remove an alert from the Inbox
    &RemoveAlert($subNo, $upLink, $demo);
}
elsif($demo eq "TIME"){
    #Return the current time
    &AppUtils::OutputDeck(sprintf($TIME_DECK, &getLocalTime));
}
else{
    # Output the HOME deck if no demo variable is found
    &AppUtils::OutputDeck($HOME_DECK);
}

######################################################################
#
# getLocalTime
#
######################################################################
sub getLocalTime
{
        my $time = localtime(time);
        return $time;
}



######################################################################
#
# PostAlert
#
# Post an alert notification to the UP.Link Messenger.
#
###################################################################### 
  sub PostAlert
{
    local($subid, $server, $demo) = @_;
        
    $url = $CONTENT_URL;
    $ttl = 3600;
    $alertString = "Notify.cgi";
    $strLen = length($alertString);
    $alertType = "D---";
    use OLE;

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

    if (!$ntfn) {

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

    } else {

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

	# Post the alert
        $ntfn->NtfnPostAlert($subid, $url, $ttl, $alertType, $alertString, $strLen);
    
        # 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);
            &AppUtils::OutputDeck($deck);
        }
    }
}

######################################################################
#
# PostAlertInval
#
# Post an alert and invalidate the URL on the UP.Link Messenger.
#
###################################################################### 
  sub PostAlertInval
{
    local($subid, $server, $demo) = @_;
        
    $url = $CONTENT_URL;
    $ttl = 3600;
    $alertString = "Notify.cgi";
    $strLen = length($alertString);
    $alertType = "D---";
    use OLE;

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

    if (!$ntfn) {

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

    } else {

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

	# Post the alert and invalidate the URL
        $ntfn->NtfnPostAlertAndInvalURL($subid, $url, $ttl, $alertType, $alertString, $strLen);
    
        # 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);
            &AppUtils::OutputDeck($deck);
        }
    }
}
######################################################################
#
# PostCacheOp
#
# Post a CacheOp notification to the UP.Link Messenger.
#
###################################################################### 
  sub PostCacheOp
{
    local($subid, $server, $demo) = @_;
        
    $url = $CONTENT_URL;
    $ttl = 3600;
    $cacheOpCode = "invalidateurl";
    
    use OLE;

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

    if (!$ntfn) {

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

    } else {

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

	# Post the CacheOp
        $ntfn->NtfnPostCacheOp($subid, $url, $ttl, $cacheOpCode);
    
        # 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($CACHE_DECK);
            &AppUtils::OutputDeck($deck);
        }
    }
}

######################################################################
#
# RemoveAlert
#
# Remove a notification from the Browser's Inbox
#
###################################################################### 
  sub RemoveAlert
{
    local($subid, $server, $demo) = @_;
        
    $url = $CONTENT_URL;
    $ttl = 60;
    $alertType = "D---";
    
    use OLE;

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

    if (!$ntfn) {

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

    } else {

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

	# Remove the Alert
        $ntfn->NtfnRemoveAlertFromInbox($subid, $url, $ttl, $alertType);
    
        # 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($REMOVAL_DECK);
            &AppUtils::OutputDeck($deck);
        }
    }
}