<%@ page language="java" import="com.cisco.ipphone.sdk.*, java.awt.*, java.awt.image.*, javax.swing.ImageIcon, java.net.*" %>

<%
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Title:  		PhotoDirectory
// Author: 		kstearns
// Source File(s): 	photodirectory.jsp
//
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Description:
//
// PhotoDirectory is an LDAP directory search service with advanced capabilities beyond those of
// the standard, embedded directories on CallManager. PhotoDirectory, as the name implies, retrieves
// a photo of the user (if available) along with other more detailed LDAP information such as userID,
// department, and manager. It also provides a Manager softkey which allows you retrieve directory
// info for a user's manager and "walk" up the management tree.
//
///////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Requirements and Caveats:
//
// - In order for the user's photo to appear, the photoUrl specified below must point to a web
//   page which returns JPG, GIF, or PNG images. This script will append the userID of the user
//   directly onto the end of the photoUrl string and attempt to load the image.
//   For example, when requesting the photo for 'kstearns' using the default photoUrl below,
//   the following URL -
//               http://directory.cisco.com/get_picture.cgi?name=kstearns
//   must return a valid photo for that user.
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//
//  Edit the following Strings for your environment.
//  This is for sample purposes only - placing passwords and other
//  sensitive information in an open text file is obviously NOT recommended !!!
//

String ldapServer = "10.0.0.1";
int ldapPort = 8404;
String ldapRoot = "o=cisco.com";
String ldapUserId = "cn=Directory Manager, o=cisco.com";
String ldapPassword = "cisco";

String photoUrl = "http://directory.cisco.com/get_picture.cgi?name=";

///////////////////////////////////////////////////////////////////////////////////////////////////////

String thisServer = InetAddress.getLocalHost().getHostAddress();
String thisPath = request.getRequestURI();
int thisPort = request.getServerPort();
String thisPage = "http://" + thisServer + ":" + thisPort + thisPath;

LDAPProvider lp = new LDAPProvider(ldapServer, ldapUserId, ldapPassword, ldapPort, ldapRoot);

String action = request.getParameter("action");
if (action == null) action="input";

response.setContentType("text/xml");

//////////////////////////////////////////////////

if (action.equals("input")) {
    String xml = "<CiscoIPPhoneInput><Title>PhotoDirectory</Title><URL>" + thisPage + "?action=search</URL>" +
	"<InputItem><DisplayName>Last Name</DisplayName><QueryStringParam>l</QueryStringParam><InputFlags>U</InputFlags></InputItem>" +
	"<InputItem><DisplayName>First Name</DisplayName><QueryStringParam>f</QueryStringParam><InputFlags>U</InputFlags></InputItem>" +
	"<InputItem><DisplayName>Number</DisplayName><QueryStringParam>n</QueryStringParam><InputFlags>N</InputFlags></InputItem>" +
	"</CiscoIPPhoneInput>";
    out.println(xml);
}

//////////////////////////////////////////////////
else if (action.equals("search")) {
    String firstName = request.getParameter("f");
    String lastName = request.getParameter("l");
    String number = request.getParameter("n");
    User[] users = User.searchUsers(firstName, lastName, number, lp);
    String xml = "<CiscoIPPhoneMenu>";
    for (int i=0; i < users.length; i++) {
	User user = users[i];
	String tn = users[i].getTelephoneNumber();
	if (tn == null) tn = "";
	xml = xml + "<MenuItem><Name>" + user.getLastName() + ", " + user.getFirstName() + "\r\n"+tn+"</Name>" +
		"<URL>QueryStringParam:number=" + tn + "&amp;userid=" + user.getUserId() + "</URL></MenuItem>";

    }
    xml = xml + "<SoftKeyItem><Name>Dial</Name><Position>1</Position><URL>" + thisPage + "?action=dial</URL></SoftKeyItem>";
    xml = xml + "<SoftKeyItem><Name>EditDial</Name><Position>2</Position><URL>" + thisPage + "?action=editdial</URL></SoftKeyItem>";
    xml = xml + "<SoftKeyItem><Name>Exit</Name><Position>3</Position><URL>SoftKey:Exit</URL></SoftKeyItem>";
    xml = xml + "<SoftKeyItem><Name>Details</Name><Position>4</Position><URL>" + thisPage + "?action=details</URL></SoftKeyItem>";
    xml = xml + "</CiscoIPPhoneMenu>";
    out.println(xml);
}

///////////////////////////////////////////////
else if (action.equals("details")) {
  String userId = request.getParameter("userid");
  String extension = request.getParameter("ext");

  if (userId == null) {
      Extension ext = Extension.getExtension(extension);
      User[] users = ext.getPrimaryUsers(lp, null);
      if (users.length != 0) {
        User theUser = users[0];
        userId = theUser.getUserId();
      }
  }

  if (userId == null) {
      out.println("<CiscoIPPhoneText><Text>User could not be found.</Text></CiscoIPPhoneText>");
  }
  else {
    URL photoUrlObj = null;
    try {
      photoUrlObj = new URL(photoUrl + userId);
    }
    catch (MalformedURLException e) {
      System.out.println(e);
    }
    ImageIcon image = new ImageIcon(photoUrlObj);
    BufferedImage bimage = new BufferedImage(133, 65, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bimage.getGraphics();

    // Clear the image background to all white
    g.setColor(Color.WHITE);
    g.fillRect(0,0,133,65);

    // Scale the image to fit on the left side of the display and draw it
    if (image != null) {
      int w = image.getIconWidth();
      int h = image.getIconHeight();
      if (w > 0 && h > 0) {
        int scale = ((w/55) > (h/65)) ? (w/55) : (h/65);
        g.drawImage(image.getImage(), 0, 0, (w/scale), (h/scale), null);
      }
    }

    // Draw the lines and headings in gray
    g.setColor(Color.GRAY);
    g.setFont(new Font("Dialog", Font.PLAIN, 9));
    g.drawString("UserID:",57,8);
    g.drawString("Department:",57,30);
    g.drawString("Manager:",57,51);

    g.drawLine(55,0,55,64);
    g.drawLine(55,21,133,21);
    g.drawLine(55,42,133,42);

    // Load the user attributes from LDAP
    User theUser = User.getUser(userId);
    theUser.loadAttributes(lp);

    // Change color to black for drawing the user information
    g.setColor(Color.BLACK);

    if (theUser.getUserId() != null) {
      g.drawString(theUser.getUserId(), 60, 18);
    }
    if (theUser.getDepartment() != null) {
      g.drawString(theUser.getDepartment(), 60, 39);
    }
    if (theUser.getManager() != null) {
      g.drawString(theUser.getManager(), 60, 62);
    }

    // Create the CIPImage object from the BufferedImage object we just created.
    // The CIPImage object essentially lets us convert from a BufferedImage to a CIPImage

    CIPImage cip = new CIPImage(bimage);

    // Now extract the XML image data from the CIPImage object to create the XML CiscoIPPhoneImage.
    String xml = "<CiscoIPPhoneImage>" +
        "<LocationX>0</LocationX><LocationY>0</LocationY>" +
        "<Width>133</Width><Height>65</Height><Depth>2</Depth>" +
        "<Data>" + cip.saveCIPDataToBuffer() + "</Data>" +
        "<SoftKeyItem><Position>3</Position><Name>Exit</Name>" +
        "<URL>SoftKey:Exit</URL></SoftKeyItem>";
    if (theUser.getTelephoneNumber() != null) {
      xml = xml + "<SoftKeyItem><Position>1</Position><Name>Dial</Name>" +
        "<URL>Dial:" + theUser.getTelephoneNumber() + "</URL></SoftKeyItem>";
    xml = xml + "<SoftKeyItem><Position>2</Position><Name>EditDial</Name>" +
        "<URL>EditDial:" + theUser.getTelephoneNumber() + "</URL></SoftKeyItem>";
    }

    // If the user has a Manager defined in LDAP, the provide a SoftKey to get to the Mgr's info
    if (theUser.getManager() != null) {
      xml = xml + "<SoftKeyItem><Position>4</Position><Name>Mgr</Name>" +
          "<URL>" + thisPage + "?action=details&amp;userid=" + theUser.getManager() +
          "</URL></SoftKeyItem>";
    }
    xml = xml + "<Prompt>" + theUser.getLastName() + ", " + theUser.getFirstName() + "  (" + theUser.getTelephoneNumber() + ")</Prompt>";
    xml = xml + "</CiscoIPPhoneImage>";
    out.println(xml);
  }
}

//////////////////////////////
else if (action.equals("dial") || action.equals("editdial")) {
    String number = request.getParameter("number");
    if (number == null) number = "";
    if (number.equals("")) {
      out.println("<CiscoIPPhoneText><Text>Unable to Dial:\r\nNo telephone number in directory.</Text></CiscoIPPhoneText>");
    }
    else {
      String uri = (action.equals("dial")) ? "Dial:" : "EditDial:";
      out.println("<CiscoIPPhoneExecute><ExecuteItem URL=\"" + uri + number + "\"/></CiscoIPPhoneExecute>");
    }
}



//  THIS SAMPLE APPLICATION AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND BY CISCO, 
//  EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY
//  FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, SATISFACTORY QUALITY OR ARISING FROM A COURSE
//  OF DEALING, LAW, USAGE, OR TRADE PRACTICE.  CISCO TAKES NO RESPONSIBILITY REGARDING ITS USAGE IN AN
//  APPLICATION., THE APPLICATION IS PROVIDED AS AN EXAMPLE ONLY, THEREFORE CISCO DOES NOT MAKE ANY
//  REPRESENTATIONS REGARDING ITS RELIABILITY, SERVICEABILITY, OR FUNCTION.  IN NO EVENT DOES CISCO
//  WARRANT THAT THE SOFTWARE IS ERROR FREE OR THAT CUSTOMER WILL BE ABLE TO OPERATE THE SOFTWARE WITHOUT
//  PROBLEMS OR INTERRUPTIONS.  NOR DOES CISCO WARRANT THAT THE SOFTWARE OR ANY EQUIPMENT ON WHICH THE
//  SOFTWARE IS USED WILL BE FREE OF VULNERABILITY TO INTRUSION OR ATTACK.  THIS SAMPLE APPLICATION IS
//  NOT SUPPORTED BY CISCO IN ANY MANNER. CISCO DOES NOT ASSUME ANY LIABILITY ARISING FROM THE USE OF THE
//  APPLICATION. FURTHERMORE, IN NO EVENT SHALL CISCO OR ITS SUPPLIERS BE LIABLE FOR ANY INCIDENTAL OR
//  CONSEQUENTIAL DAMAGES, LOST PROFITS, OR LOST DATA, OR ANY OTHER INDIRECT DAMAGES EVEN IF CISCO OR ITS
//  SUPPLIERS HAVE BEEN INFORMED OF THE POSSIBILITY THEREOF.

%>



