API Docs for: WebTemplate API v2.0
Show:

File: /data/www/webtemplate/wtv2/codedoc/wt.php

<?php
/**
 *  WebTemplate Core
 *
 *  @version 2.0
 *  @module WebTemplate Core
 */


session_start();
//session_regenerate_id();

/**
 * @global string $GLOBALS["WTDIRECTORY"] 
 * @name WTDIRECTORY
 *
*/

include "config.php";

include_once($GLOBALS["WTDIRECTORY"] . "code/wtNode.php");
include_once($GLOBALS["WTDIRECTORY"] . "code/wtControl.php");
include_once($GLOBALS["WTDIRECTORY"] . "code/wtBuiltInOptions.php");

if($GLOBALS["WTDBUSERNAME"] && $GLOBALS["WTDBPASSWORD"]) {
  mysql_connect("localhost", $GLOBALS["WTDBUSERNAME"], $GLOBALS["WTDBPASSWORD"]);
} else {
  mysql_connect("localhost", DBUSERNAME, DBPASSWORD);
}

function wtmysqlquery($sql) {
  $result = mysql_query($sql);

  return $result;
}



$GLOBALS["WTNODECACHE"] = Array();
$GLOBALS["WTTYPECACHE"] = Array();
$GLOBALS["WTVALUECACHE"] = Array();
$GLOBALS["WTURICACHE"] = Array();

$GLOBALS["WTURIHANDLERS"] = Array();
$GLOBALS["WTPAGENOTFOUNDHANDLER"] = NULL;
$GLOBALS["WTURIPROCESSOR"] = NULL;

if(isset($GLOBALS["WTSITEID"])) {
  $_SESSION["WTCLIENTID"] = $GLOBALS["WTSITEID"];
} else if(isset($_SESSION["WTCLIENTID"])) {
  $GLOBALS["WTSITEID"] = $_SESSION["WTCLIENTID"];
}


/**
 *  The WebTemplate class
 *
 *  @class WebTemplate
 */
class WebTemplate 
{
  var $m_contactGuid;
  var $m_contactIsAdministrator;
  var $m_contactGroups;
  var $m_nodeRegistry;
  var $m_currentPage;
  var $m_moderationEnabled;
  var $m_extensions;
  var $m_siteSettings;
  var $m_renderContext;
  var $m_browserDetails;

  public static function errorHandler($errno, $errstr, $errfile, $errline) {
    // if error has been supressed with an @
    if (error_reporting() == 0) {
        return;
    }

    $errorType = array (
               E_ERROR            => 'ERROR',
               E_WARNING        => 'WARNING',
               E_PARSE          => 'PARSING ERROR',
               E_NOTICE         => 'NOTICE',
               E_CORE_ERROR     => 'CORE ERROR',
               E_CORE_WARNING   => 'CORE WARNING',
               E_COMPILE_ERROR  => 'COMPILE ERROR',
               E_COMPILE_WARNING => 'COMPILE WARNING',
               E_USER_ERROR     => 'USER ERROR',
               E_USER_WARNING   => 'USER WARNING',
               E_USER_NOTICE    => 'USER NOTICE',
               E_STRICT         => 'STRICT NOTICE',
               E_RECOVERABLE_ERROR  => 'RECOVERABLE ERROR'
               );

    if($errno != E_ERROR && $errno != E_WARNING) {
      return;
    }
    // create error message
    if (array_key_exists($errno, $errorType)) {
        $err = $errorType[$errno];
    } else {
        $err = 'CAUGHT EXCEPTION';
    }

    if(count($GLOBALS["WTTEMPLATESTACK"]) > 0) {
      print "Template: '";
      $templateCount = count($GLOBALS["WTTEMPLATESTACK"]);

      for($i = 0; $i < count($GLOBALS["WTTEMPLATESTACK"]); $i++) {
        if($i != 0) {
          print " > ";
        }

        if($i == $templateCount  - 1) {
          print "<strong>";
        }      
        print $GLOBALS["WTTEMPLATESTACK"][$i];
        if($i == $templateCount - 1) {
          print "</strong>";
        }
       
      }
      print "': ";
    }
    $errMsg = "$err: $errstr in $errfile on line $errline<br/>";

//    $module = (int)$GLOBALS["WT"]->getRequestValue("__module");

    $module = (int)$_REQUEST["__module"];
    if($module) {
      $response = Array("wtphperror" => true, "wterrormessage" => $errMsg);
      print json_encode($response);
      exit();
    } else {
      print $errMsg;
    }
    return true;
  }

  
  public static function clearCache() {
    $GLOBALS["WTNODECACHE"] = Array();
    $GLOBALS["WTTYPECACHE"] = Array();
    $GLOBALS["WTVALUECACHE"] = Array();
    $GLOBALS["WTURICACHE"] = Array();
  }

  public function initURICache() {

    if(count($GLOBALS["WTURICACHE"]) > 0) {
      return;
    }

    $pages = $GLOBALS["WT"]->getNode("/Pages");

    $results = Array();
    $q = Array();
    $q["Node Type"] = "wtNode";
    $q["Path"] = $pages->m_guid . "/*";
    $q["Results Array"] = &$results;
    $GLOBALS["WT"]->query($q);

    foreach($results as $result) {
      $GLOBALS["WTURICACHE"][$result["__guid"]] = "";
    }
  }

  function WebTemplate() 
  {

    set_error_handler(Array("WebTemplate", "errorHandler"));

    $this->m_browserDetails = NULL;

    if($_SESSION["WTCLIENTDATABASE"] == "") {
      $_SESSION["WTCLIENTDATABASE"] = "wt";
    }


    if(isset($GLOBALS["WTSITEID"])) {
      $_SESSION["WTCLIENTID"] = $GLOBALS["WTSITEID"];
    } else if(isset($_SESSION["WTCLIENTID"])) {
      $GLOBALS["WTSITEID"] = $_SESSION["WTCLIENTID"];
    }

    if(!isset($GLOBALS["WTSITEDATABASE"])) {
      $GLOBALS["WTSITEDATABASE"] = $_SESSION["WTDBNAME"];
    }

    if(!$GLOBALS["WTSITEDATABASE"]) {


    //  exit("");
    }
    mysql_select_db($GLOBALS["WTSITEDATABASE"]);
    $this->m_contactGuid = 0;
    $this->m_contactIsAdministrator = false;
    $this->m_contactGroups = Array();
    $this->m_nodeRegistry = Array();
    $this->m_controlRegistry = Array();
    $this->m_extensions = Array();
    $this->m_renderContext = Array();
    $this->m_currentPage = NULL;
    if(!isset($_SESSION["WTMODE"])) {
      $_SESSION["WTMODE"] = "view";
    }


    // maybe put this in an init function??
    $this->m_moderationEnabled = false;
    $moderationEnabledGuid = $this->pathExists("/Config/Settings/Content Manager/Moderation Enabled");
    if($moderationEnabledGuid) {
      $sql = "SELECT
                `Value`
              FROM
                wtConfig
              WHERE
                __guid = $moderationEnabledGuid";
      $query = mysql_query($sql);
      if($row = mysql_fetch_row($query)) {
        $this->m_moderationEnabled = $row[0] == 'Yes';
      } 
    }


    $this->registerNodeTypeClass("wtType", "WTType");
    $this->registerNodeTypeClass("wtAttribute", "WTAttribute");
    $this->registerNodeTypeClass("wtFile", "WTFile");
    $this->registerNodeTypeClass("Template", "WTTemplate");
    $this->registerNodeTypeClass("Page", "WTPage");
    $this->registerNodeTypeClass("Contact", "WTContact");
//    $this->registerNodeTypeClass("wtWidget", "WTWidget");
    $this->registerNodeTypeClass("wtExtension", "WTExtension");
    $this->registerNodeTypeClass("wtModule", "WTModule");
    $this->registerNodeTypeClass("wtNewsletter", "WTNewsletter");
    $this->registerNodeTypeClass("Product", "WTProduct");
    $this->registerNodeTypeClass("Category", "WTCategory");
    $this->registerNodeTypeClass("Group", "WTGroup");
    $this->registerNodeTypeClass("Freight Zone", "WTFreightZone");
    $this->registerNodeTypeClass("wtForm", "WTForm");
    $this->registerNodeTypeClass("wtConfig", "WTConfig");
    $this->registerNodeTypeClass("wtProgress", "WTProgress");
    $this->registerNodeTypeClass("wtOrder", "WTOrder");
    $this->registerNodeTypeClass("wtPayment", "WTPayment");
    $this->registerNodeTypeClass("wtCommunication", "WTCommunication");

    $sessionContactGuid = WTSession::get("WTCONTACTGUID");
    $username = "__public";
    if($sessionContactGuid) {
      $sql = "SELECT
                Username
              FROM
                wtNode, Contact
              WHERE
                wtNode.__guid = Contact.__guid
                AND wtNode.__guid = $sessionContactGuid
                AND wtNode.__deleted = 0";
      $query = wtmysqlquery($sql);
      if($row = mysql_fetch_row($query)) {
        $username = $row[0];
      }
    }

    $this->setUser($username);

/*    if(!$contact) {
      $this->setUser("__public");
    }*/

    if(!$sessionContactGuid) {
      // no session so check the cookie
//      if(array_key_exists("WTAUTH", $_COOKIE)) {
//        $cookie = $this->decrypt($_COOKIE["WTAUTH"]);
      if(array_key_exists("WTAUTH", $_SESSION)) {
        $cookie = $this->decrypt($_SESSION["WTAUTH"]);


        list($version, $created, $username) = explode("|", $cookie);

        if(trim($username) != "") {
          if(!$this->setUser($username)) {
            $this->setUser("__public");
          }
          if(trim($username) != "__public") {
            $_SESSION["WTLOGGEDIN"] = true;
          }
        }
      } else {
        $this->setUser("__public");
      }
    }

    $this->m_siteSettings = Array();
    $settings = $this->getNode("/Config/Settings");
    if($settings != NULL) {
      $sql = "SELECT
                Name, Value
              FROM
                wtNode, wtConfig
              WHERE
                __parentGuid = {$settings->m_guid}";
      $query = wtmysqlquery($sql);
      while($row = mysql_fetch_row($query)) {
        $this->m_siteSettings[$row[0]] = $row[1];
      }

      
      if(isset($GLOBALS["WTSITEBASE"])) {
        $this->m_siteSettings["Site Base"] = $GLOBALS["WTSITEBASE"];
      } else {
        $this->m_siteSettings["Site Base"] = $this->m_siteSettings["Site Directory"];
      }
      if ( !array_key_exists('Path Mode',$this->m_siteSettings) ) {
        $this->m_siteSettings["Path Mode"] = "rewrite";
      }
     
    }

    $this->m_siteSettings["Template Directory"] = $GLOBALS["WTSITEDIRECTORY"] . $this->m_siteSettings["Site Directory"] . "/templates/";

    

   // $GLOBALS["WTTEMPLATEDIRECTORY"] = $this->m_siteSettings["Template Directory"];
  

/*
    if(array_key_exists("WTUNAME", $_SESSION) && $_SESSION["WTUNAME"] != "") {
      $this->Authenticate($_SESSION["WTUNAME"], "", true);
    } else {
      $this->Authenticate("__public", "");
    }
*/

  }
  function setSiteSetting($name, $value) {
    $this->m_siteSettings[$name] = $value;
  }

  function siteSettingExists($name) {
    return array_key_exists($name, $this->m_siteSettings);
  }
  function getSiteSetting($name) 
  {
    if(array_key_exists($name, $this->m_siteSettings)) {
      return $this->m_siteSettings[$name];
    }

    switch($name) {
      case 'Site ID':
        return $GLOBALS["WTSITEID"];
        break;
      case 'Site Abbreviation': 
        $sql = "SELECT
                  clientAbbreviation
                FROM 
                  dbWebtemplate.tblClient
                WHERE
                  id = {$GLOBALS["WTSITEID"]}";
        $query = wtmysqlquery($sql);
        if($row = mysql_fetch_row($query)) {
          return $row[0];
        }       
        break;
      case 'Site Name':
        $sql = "SELECT
                  clientName
                FROM
                  dbWebtemplate.tblClient
                WHERE
                  id = {$GLOBALS["WTSITEID"]}";
        $query = wtmysqlquery($sql);
        if($row = mysql_fetch_row($query)) {
          return $row[0];
        }  
    }
    return false;
  }
  

  function logError($errorMessage) {
  }


  /**
   *  Encrypt a string
   *
   *  @method encrypt
   *  @param {String} value The string to encrypt
   *  @return {String} The encrypted string
   */

  function encrypt($value) 
  {
    $key = $GLOBALS["WTMCRYPTKEY"];

    $text = $value;
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    return $crypttext; 
  }

  /**
   *  Decrypt a string
   *
   *  @method decrypt
   *  @param {String} value The string to decrypt
   *  @return {String} The decrypted string
   */

  function decrypt($value) 
  {
    $key = $GLOBALS["WTMCRYPTKEY"];
    $crypttext = $value;
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
    return trim($decrypttext); 
  }

  /**
   *  Set the mode of Webtemplate
   *
   *  @method setMode
   *  @param {String} mode "view", "edit", "moderate", "index"
   */
  function setMode($mode) 
  {
    switch($mode) {
      case "view":
        $_SESSION["WTMODE"] = "view";
        break;
      case "edit":
        $_SESSION["WTMODE"] = "edit";
        break;
      case "moderate":
        $_SESSION["WTMODE"] = "moderate";
        break;
      case "index":
        $_SESSION["WTMODE"] = "index";
        break;
    }
  }

  /**
   *  Get the mode of WebTemplate
   *
   *  @method getMode
   *  @return Returns "view", "edit", "moderate" or "index"
   */
  function getMode() 
  {
    return $_SESSION["WTMODE"];
  }


  /**
   *  Get the Object for the current user
   *
   *  @method getCurrentUser
   *  @return {Object} The object for the current user
   */
  function getCurrentUser() 
  {
    if($this->m_contactGuid != 0) {
      return $this->getNode($this->m_contactGuid);
    } else {
      return NULL;
    }
  }

  /**
   *  Return the country the current user is in
   *
   *  @method getUserLocation
   *  @param [ipAddress=""] An optional IP address to use instead of the current user's ip address
   *  @return {Array} an associative array containing "country" and "countryCode"
   *
   */
  function getUserLocation($ipAddress = "") {
    if($ipAddress == "") {
      $ipAddress = WTSession::get("ipaddress");
      if(!$ipAddress) {
        $ipAddress = $_SERVER["REMOTE_ADDR"];
      }
    }

    $location = Array("country" => "UNKNOWN", "countryCode" => "");
    if($ipAddress) {

/*
      $ipAddress = WTSession::get("ipaddress");
      if($ipAddress == "203.122.246.187") {
        return Array("country" => "USA", "countryCode" => "US");
      }
*/
      $components = explode(".", $ipAddress);
      if(count($components) == 4) {
        $ipNumber = $components[0] * (256 * 256 * 256) + $components[1] * (256 * 256) + $components[2] * (256) + $components[3];
        $sql = "SELECT
                  *
                FROM
                  dbIPCountry.ipcountry
                WHERE
                  ipFROM <= $ipNumber
                  AND ipTO >= $ipNumber";
        $query = mysql_query($sql);
        if($row = mysql_fetch_array($query)) {
          $location["country"] = $row["countryLONG"];
          $location["countryCode"] = $row["countrySHORT"];
        }
      }
    }
//    $location = Array("country" => "Poland", "countryCode" => "PL");
    return $location;
  }


  /**
   *  Return the object for the current page
   *
   *  @method getCurrentPage
   *  @return {Object} The object for the current page
   */
  function getCurrentPage() 
  {
    return $this->m_currentPage;
  }

  /**
   *  Log out the current user
   *
   *  @method logout
   *  
   */

  function logout() 
  {
    $loginID = WTSession::get("WTLOGINID");
    if($loginID) {
      $loginTime = (int)WTSession::get("WTLOGINTIME");
      $duration = mktime() - $loginTime;
      $sql = "UPDATE
                tblLogin
              SET
                loginDuration = $duration
              WHERE
                loginID = $loginID";
      mysql_query($sql); 
      WTSession::set("WTLOGINID", "");
      WTSession::set("WTLOGINTIME", "");
      
    }
    $this->m_contactGuid = 0;
    $this->m_contactIsAdministrator = false;
    $this->m_contactGroups = Array();
//    $_COOKIE["WTAUTH"] = "";
//    setcookie("WTAUTH", "", 0, "/");
    $_SESSION["WTAUTH"] = "";

    WTSession::set("WTCONTACTGUID", ""); 

    $_SESSION["WTLOGGEDINAS"] = "";
    $_SESSION["WTLOGGEDINASORIGINALUSER"] = "";
//    $_SESSION["WTUNAME"] = "";
    $this->setUser("__public");
  }

  /**
   *  Return true if the current contact is an administrator
   *
   *  @method contactIsAdministrator
   *  @return {boolean} Returns true if the current user is an administrator
   */
  function contactIsAdministrator() {
    if($this->m_contactIsAdministrator) {
      return true;
    }

    $currentUser = $this->getCurrentUser();
    return $this->nodesAreLinked("/Groups/__Administrators", $currentUser);
  }

  /**
   *  Return true if the current contact is the global administrator
   *
   *  @method contactIsGlobalAdministrator
   *  @return {boolean} Returns true if the current user is the global administrator
   */
  function contactIsGlobalAdministrator() {
    return $this->m_contactIsAdministrator;
  }

  /**
   *  Get an authorisation challenge for logging in
   *
   *  @method getAuthChallenge
   *  @return The authorisation challenge to be used the in the login form
   */
  function getAuthChallenge() 
  {
    if(!isset($_SESSION["WTAUTHCHALLENGE"])) {
      $_SESSION["WTAUTHCHALLENGE"] = substr(md5(uniqid(rand(), true)), 0, 32);
    }
    return $_SESSION["WTAUTHCHALLENGE"];
  }

  /**
   *  If loginAs has been called, swich back to the previous user
   *
   *  @method unloginAs
   *
   */
  function unloginAs() 
  {
    if(array_key_exists("WTLOGGEDINASORIGINALUSER", $_SESSION)) {
      $GLOBALS["WT"]->setUser($_SESSION["WTLOGGEDINASORIGINALUSER"]);
      $_SESSION["WTLOGGEDINAS"] = ""; 
    }
  }

  /**
   *  If the user is an administrator, allow them to login as a different user
   *
   *  @method loginAs
   *  @param {String} username The user to log in as
   */
  function loginAs($username) 
  {     
      if($this->contactIsAdministrator()) {
        $currentUser = $GLOBALS["WT"]->getCurrentUser();

        if($GLOBALS["WT"]->setUser($username)) {
          $_SESSION["WTLOGGEDINAS"] = $username;
          if(!array_key_exists("WTLOGGEDINASORIGINALUSER", $_SESSION)) {
            $_SESSION["WTLOGGEDINASORIGINALUSER"] = $currentUser->getAttribute("Username");            
          }
          return true;
        }
      }
      return true;
  }

  /**
   *  Set the current user
   *
   *  @method setUser
   *  @param {String} The username of the user to set
   */
  function setUser($username, $rememberUser = false) 
  {

    if(trim($username) == "") {
      return false;
    }
    $sql = "SELECT
              Contact.__guid
            FROM
              Contact, wtNode
            WHERE
              Contact.__guid = wtNode.__guid
	      AND wtNode.__deleted = 0
              AND Contact.__active <> 0
              AND Status <> 'Inactive'
              AND Status <> 'On Hold'
              AND Status <> 'Awaiting Approval'
             	
              AND Username = '" . mysql_escape_string($username) . "'";
    $query = wtmysqlquery($sql);
    print mysql_error();
    if($row = mysql_fetch_row($query)) {
      $this->m_contactGuid = $row[0];

      $sql = "SELECT
                `Group`.__guid, `Group`.Name, `wtNode`.__hidden
              FROM
                `Group`
              JOIN
                wtNode ON `Group`.__guid = wtNode.__parentGuid
              WHERE
                `Group`.__active <> 0
		AND wtNode.__deleted = 0
                AND `Group`.__guid = wtNode.__parentGuid
                AND wtNode.__nodeIsHolderForGuid = $this->m_contactGuid";
//print $sql;
      $query = wtmysqlquery($sql);
      if(!$query) {
        print $sql. "\n";
        print mysql_error();
      }
      while($row = mysql_fetch_row($query)) {
        $this->m_contactGroups[] = $row[0];
        if($row[1] == "__Global Administrators") {// || $row[1] == "__Administrators") {
          $this->m_contactIsAdministrator = true;
        }
      }

      // find what group sets this contact is a member of
      if(count($this->m_contactGroups) > 0) {
        $groups = implode(",", $this->m_contactGroups);
        $sql = "SELECT
                  DISTINCT wtNode.__parentGuid
                FROM
                  wtNode
                JOIN
                  `Group`
                ON
                  wtNode.__parentGuid = `Group`.__guid
                WHERE
                  __nodeIsHolderForGuid IN ($groups)";
        $query = wtmysqlquery($sql);
        while($row = mysql_fetch_row($query)) {
          $this->m_contactGroups[] = $row[0];
        }
      }

//print "remember user = $rememberUser<br>";

//      if($username != "__public") {
        WTSession::set("WTCONTACTGUID", $this->m_contactGuid);
//      }


/*
      if( $username != "__public" && (!array_key_exists("WTAUTH", $_COOKIE) || $_COOKIE["WTAUTH"] == "" )) {
        $cookie = $this->encrypt("1|" . time() . "|" . $username);
        if($rememberUser) {
          setcookie("WTAUTH", $cookie, time() + 60 * 60 * 24 * 7, "/");
        } else {
          setcookie("WTAUTH", $cookie, 0, "/");
        }
      }
*/
      if( $username != "__public" && (!array_key_exists("WTAUTH", $_SESSION) || $_SESSION["WTAUTH"] == "" )) {
        $cookie = $this->encrypt("1|" . time() . "|" . $username);
        if($rememberUser) {
          $_SESSION["WTAUTH"] = $cookie;
       //   setcookie("WTAUTH", $cookie, time() + 60 * 60 * 24 * 7, "/");
        } else {
         $_SESSION["WTAUTH"] = $cookie;
       //   setcookie("WTAUTH", $cookie, 0, "/");
        }
      }
      


      return true;
//      $_SESSION["WTUNAME"] = $username;
    }

    return false;
  }

  /**
   *  Sets the current user
   *
   *  @method authenticate
   *  @param {string} username
   *  @param {string} password
   *  @param {boolean} passwordIsHash is the password an md5 hash?
   *  @param {boolean} $rememberUser should the login be stored in a cookie
   *  @return {boolean} true if successful, false otherwise
   */
  function authenticate($username, $password, $passwordIsHash = true, $rememberUser = false) 
  {
    $username = trim($username);
    $password = trim($password);
    $sql = "SELECT 
              Contact.__guid, Contact.Password
            FROM 
              Contact, wtNode
            WHERE
              Contact.__guid = wtNode.__guid
              AND wtNode.__deleted = 0
              AND Contact.__active <> 0 
              AND Status <> 'Inactive'
              AND Status <> 'On Hold'
              AND Status <> 'Awaiting Approval'
              AND Type <> '' 
              AND Username = '" . mysql_escape_string($username) . "'";	    
    $query = wtmysqlquery($sql);
    print mysql_error();
    if($row = mysql_fetch_row($query)) {
      $contactGuid = $row[0];
      if($passwordIsHash) {

        if(md5($this->getAuthChallenge() . $row[1]) != $password) {
          return false;
        }
      } else {
        $password =  md5($username . WTSYSTEMSALT . $password);
//print $password;
        if($row[1] != $password) {
          return false;
        }
      }
      $this->logout();

      $this->setUser($username, $rememberUser);

      $ipaddress = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]);
      $sql = "INSERT INTO tblLogin (
                contactGuid,
                loginDate,
                loginIPAddress
              ) VALUES (
                $contactGuid,
                NOW(),
                '$ipaddress'
              )";
      if(mysql_query($sql)) {
        $loginID = mysql_insert_id();
        WTSession::set("WTLOGINID", $loginID);
        WTSession::set("WTLOGINTIME", mktime());
      }
      return true;

    }
  }

  /**
   *  Get the guid for a path
   *
   *  @method getGuid 
   *  @param {String} path
   *  @return {int} the guid for a path
   */
  function getGuid($path) {
    return $this->pathExists($path);
  }

  /**
   *  Check if a path exists in the WebTemplate tree and optionally create the path if it does not exist
   *
   *  @method pathExists
   *  @param {String} path the path to check
   *  @param {boolean} create should the path be created with wtNodes if it does not exist?
   *  @return {boolean} true if the path exists, false otherwise
   */

  function pathExists($path, $create = false) 
  {
    $guid = 0;
    if(is_numeric($path))
    {
      $guid = (int)$path;

      if($guid == 0) {
        return 0;
      }

      // need to check if guid refers to a real active node
      $sql = "SELECT
                __guid
              FROM
                wtNode
              WHERE
                (__guid = $guid OR __nodeIsHolderForGuid = $guid)
                AND __deleted = 0";
      $query = wtmysqlquery($sql);
      if(!mysql_fetch_row($query)) {
        return false;
      }

    } else {
      $guid = 0;
      $parentGuid = 0;
      $pathParts = explode("/", $path);
      $pathParts = array_map("trim", $pathParts);
//      $pathParts = array_map("mysql_escape_string", $pathParts);
      $first = true;
      foreach($pathParts as $part) {
        if($part != "") {
          if($first && is_numeric($part)) {
            $parentGuid = (int)$part;
          } else {
            $sql = "SELECT
                      __guid, __nodeIsHolderForGuid
                    FROM
                      wtNode
                    WHERE
                      __name = '" . mysql_escape_string($part) . "'
                      AND __deleted = 0
                      AND __parentGuid = $parentGuid";

            $query = wtmysqlquery($sql);
            if($row = mysql_fetch_row($query)) {
              $guid = $row[0];
              $parentGuid = $row[0];
              if($row[1] > 0) {
                $parentGuid = $row[1];
              }
            } else {
              if($create) {
                $parentNode = $this->getNode($parentGuid);
                if($parentNode == NULL) { 
                  return false;
                }
                $node = $parentNode->createChild("wtNode", Array("Node Name" => $part));
                if($node == NULL) {
                  return false;
                }
                $parentGuid = $node->m_guid;
              } else {
                return false;
              }
            }
          }
          $first = false;
        }
      }
    }
    return $guid;
  }

  function getNodeFromURI($uri)
  {

    $parts = explode("/", $uri);
    $parents = "";

    $pagesGuid = 0;
    $sql = "SELECT 
              __guid
            FROM
              wtNode
            WHERE
              __deleted = 0
              AND __name = 'Pages'
              AND __parentGuid = 0";
    $query = mysql_query($sql);
    if($row = mysql_fetch_row($query)) {
      $pagesGuid = $row[0];
    }

    if($pagesGuid == 0) {
      return NULL;
    }

    $sql = "SELECT
              __guid 
            FROM
              wtNode 
            WHERE
              __deleted = 0
              AND __parentGuid = $pagesGuid";
    $query = mysql_query($sql);
    while($row = mysql_fetch_row($query)) {
      if($parents != "") {
        $parents .= ",";
      }
      $parents .= $row[0];
    }


/*
    $sql = "SELECT
              wtNode.__guid
            FROM
              wtNode, wtWebRoot
            WHERE
              wtNode.__guid = wtWebRoot.__guid
              AND __deleted = 0";
    $query = mysql_query($sql);
    while($row = mysql_fetch_row($query)) {
      if($parents != "") {
        $parents .= ",";
      }
      $parents .= $row[0];
    }

*/
    $nodeGuid = 0;
    $sql = "SELECT
              __parentGuid
            FROM
              wtNode
            WHERE
              __parentGuid IN ($parents)
              AND __uri = '" . mysql_escape_string($parts[0]) . "'
              AND __deleted = 0";

    $query = mysql_query($sql);
    if($row = mysql_fetch_row($query)) {
      $nodeGuid = $row[0];
    } else {
      return NULL;
    }


    foreach($parts as $part) {
      $part = trim($part);
      if($part) {
        $sql = "SELECT
                  __guid
                FROM
                  wtNode
                WHERE
                  __deleted = 0
                  AND __uri = '" . mysql_escape_string($part) . "'
                  AND __parentGuid = $nodeGuid";
        $query = mysql_query($sql);
        if($row = mysql_fetch_array($query)) {
          $nodeGuid = $row["__guid"];
        }
      }
    }
    if($nodeGuid) {
      return $this->getNode($nodeGuid);
    }
    return NULL;
  }

  /**
   *  Return the object for a node given its guid or path
   *
   *  @method getNode
   *  @param {String} path The path or the guid of the node
   *  @return {Object} The object of the node, NULL if the node does not exist
   */
  function getNode($path) 
  {
    if(!isset($path)) {
      return NULL;
    }

    if(array_key_exists($path, $GLOBALS["WTNODECACHE"])) {
      $node = $GLOBALS["WTNODECACHE"][$path];
      if($node) {
        return $node;
      }
    }

    if(is_numeric($path)) {
      $guid = $path;
    } else {
      $guid = $this->pathExists($path);
      if($guid === false) {
        return NULL;
      }
    }

    $typeName = "wtNode";

    if(array_key_exists($guid, $GLOBALS["WTTYPECACHE"])) {
      $typeName = $GLOBALS["WTTYPECACHE"][$guid];
    } else if($guid != 0) {
/*      $sql = "SELECT
              `Type Name`
            FROM 
              wtNode, wtType
            WHERE
              wtNode.__typeGuid = wtType.__guid
              AND wtNode.__deleted = 0
              AND wtNode.__guid = $guid
              AND wtType.__active <> 0";*/

    
    $sql = "SELECT
              wtNode.*,
              wtType.`Type Name`
            FROM
              wtNode
            LEFT JOIN
              wtType
            ON
              wtNode.__typeGuid = wtType.__guid
            WHERE
              wtNode.__deleted = 0              
              AND wtNode.__guid = $guid";


      $query = wtmysqlquery($sql);
      print mysql_error();
      if($row = mysql_fetch_array($query)) {
        if($row["Type Name"] != NULL) {
          $typeName = $row["Type Name"];
        }
        $GLOBALS["WTTYPECACHE"][$guid] = $typeName;
      } else {
        return NULL;
//        $GLOBALS["WT"]->debugMessage("$guid is null");
//        WebTemplate::debugMessage("$guid is null");
      } 
    }

    if(array_key_exists($typeName, $this->m_nodeRegistry)) {
      $node = new $this->m_nodeRegistry[$typeName]($guid);
    } else {
      $node = new WTNode($guid);
    }
    $GLOBALS["WTNODECACHE"][$path] = $node;

    
    return $node;
  }

  function getButtonHTML($buttonType, $args) {
    $html = '';
    switch($buttonType) {
      case 'edit':
        $guid = $args["guid"];
        $noteditable = '';
        if(array_key_exists("noteditable", $args)) {
          $noteditable = "&noteditable=" . $args["noteditable"];
        }
        $hidden = '';
        if(array_key_exists("hidden", $args)) {
          $hidden = "&hidden=" . $args["hidden"];
        }
        $forceeditable = '';
        if(array_key_exists("forceeditable", $args)) {
          $forceeditable = "&forceeditable=" . $args["forceeditable"];
        }
        $language = '';
        if($GLOBALS["WTLANGUAGEID"]) {
          $language = "&languageID=" . $GLOBALS["WTLANGUAGEID"];
        }
        $buttonLabel = "Edit";
        if(array_key_exists("label", $args)) {
          $buttonLabel = $args["label"];
        }

        $page = '';
        $pageNode = $GLOBALS["WT"]->getCurrentPage();
        if($pageNode) {
          $page = "&page=" . $pageNode->m_guid;
        }
        $html = '<button type="button" class="wteditbutton" onclick="void window.open(\'' . $GLOBALS["WTURL"] . 'code/wtEditNode.php?guid=' . $guid . $noteditable . $hidden . $forceeditable . $language . $page . '\', \'wteditnode\', \'width=500, height=520, status=0, toolbar=0,location=0,menubar=0,resizable=1,scrollbars=1\')" title="' . $buttonLabel . '"/><span>' . $buttonLabel . '</span></button>';
        break;
    }
    return $html;
  }
  function getNodeFormHTML($nodeType, $values = NULL, $args = NULL) 
  {
    if(array_key_exists($nodeType, $this->m_nodeRegistry)) {
      return call_user_func(Array($this->m_nodeRegistry[$nodeType], "getFormHTML"), $nodeType, $values, $args);
    }
    return WTNode::getFormHTML($nodeType, $values, $args);
  }

  function getFormAttributeHTML($nodeType, $attributeInfo, $values) 
  {
    if(array_key_exists($nodeType, $this->m_nodeRegistry)) {
      return call_user_func(Array($this->m_nodeRegistry[$nodeType], "getFormAttributeHTML"), $attributeInfo, $values);
    }
    return WTNode::getFormAttributeHTML($attributeInfo, $values);
  }

  function getFormRowHTML($nodeType, $label, $control) 
  {
    if(array_key_exists($nodeType, $this->m_nodeRegistry)) {
      return call_user_func(Array($this->m_nodeRegistry[$nodeType], "getFormRowHTML"), $label, $control);
    }
    return WTNode::getFormRowHTML($label, $control);
  }

  function getControlHTML($fieldName, $attributeInfo, $value) 
  {
    $attributeSettings = Array();
    parse_str($attributeInfo["Attribute Settings"], $attributeSettings);

    if(array_key_exists("control", $attributeSettings)) {
      $control = $attributeSettings["control"];
      if(array_key_exists($control, $this->m_controlRegistry)) {
        return call_user_func(Array($this->m_controlRegistry[$control], "getControlHTML"), $fieldName, $attributeInfo, $value);
      }
    }
    return WTControl::getControlHTML($fieldName, $attributeInfo, $value);
  }

  function getControlFormValue($fieldName, $attributeInfo, $formValues) 
  {
    $attributeSettings = Array();
    parse_str($attributeInfo["Attribute Settings"], $attributeSettings);

    if(array_key_exists("control", $attributeSettings)) {
      $control = $attributeSettings["control"];
      if(array_key_exists($control, $this->m_controlRegistry)) {
        return call_user_func(Array($this->m_controlRegistry[$control], "getControlFormValue"), $fieldName, $attributeInfo, $formValues);
      }
    }

    return WTControl::getControlFormValue($fieldName, $attributeInfo, $formValues);
  }


  function deleteNode($path) 
  {
    $node = $this->getNode($path);
    if($node == NULL) {
      return false;
    }

    //DEH:20080102: added this here while looking to add to saving nodes...
    if(array_key_exists($nodeType, $this->m_nodeRegistry)) {
      return call_user_func(Array($this->m_nodeRegistry[$nodeType], "deleteNode"), $path);
    }

    $node->deleteNode();
  }

  function createNode($parentGuid, $nodeType, $attributes = Array()) 
  {
    if(!is_array($attributes)) {
      return NULL;
    }

    if(array_key_exists($nodeType, $this->m_nodeRegistry)) {
      return call_user_func(Array($this->m_nodeRegistry[$nodeType], "create"), $parentGuid, $nodeType,  $attributes);
    }

    return WTNode::create($parentGuid, $nodeType, $attributes);
  }


  /**
   *  Register a class to a node type, once registered, getNode will return objects of this class for this type of node
   *
   *  @method registerNodeTypeClass
   *  @param {String} typeName
   *  @param {String} className
   */
  function registerNodeTypeClass($typeName, $className) 
  {
    $this->m_nodeRegistry[$typeName] = $className;
  }

  function registerControlClass($controlName, $className) 
  {
    $this->m_controlRegistry[$controlName] = $className;
  }

  /**
   *  Copy a node's children to another node
   *
   *  @method copyNodeChildren
   *  @param {String} from The guid or path of the node to copy the children from
   *  @param {String} to The guid or path of the node to copy the children to
   *  @param {int} [ignore] The guid of the type to ignore when copying the children
   */

  function copyNodeChildren($fromGuid, $toGuid, $ignoreTypeGuid = -1) {
    $children = Array();
    $q = Array();
    $q["Path"] = "$fromGuid/*";
    $q["Results Array"] = &$children;
    $GLOBALS["WT"]->query($q);

    $toNode = $GLOBALS["WT"]->getNode($toGuid);

    foreach($children as $child) {
      if($child["__typeGuid"] != $ignoreTypeGuid) {
        $newChildNode = null;
        if($child["__typeGuid"] == 0) {
          $name = $child["Node Name"];
          $newChildNode = $toNode->createChild("wtNode", Array("Node Name" => $name));
        } else {
          $newAttributes = Array();
          foreach($child as $key => $value) {
            if(strpos($key, "__") === false || strpos($key, "__") > 0) {
              $newAttributes[$key] = $value;
            }
          }

          $nodeTypeNode = $GLOBALS["WT"]->getNode($child["__typeGuid"]);
          if($nodeTypeNode) {
            $nodeType = $nodeTypeNode->getName();
            if($nodeType == "Page") {
              unset($newAttributes["URI"]);
            }
            $newChildNode = $toNode->createChild($nodeType, $newAttributes);
          }
        }

        $this->copyNodeChildren($child["__guid"], $newChildNode->m_guid, $ignoreTypeGuid);
      }
    }
  }

  /**
   *  Copy a node's properties (used for linking nodes)
   *
   *  @method copyNode
   *  @private
   *  @param {int} srcGuid The guid of the source node
   *  @param {int} dstGuid The guid of the destination node
   */

  function copyNode($srcGuid, $dstGuid) 
  {
    $nodeAttributes = Array("__luid", "__nodeIsHolderForGuid", "__typeGuid", "__name", "__locked", "__hidden", "__allList", "__allRead", "__allWrite", "__groupList", "__groupRead", "__groupWrite");

    $sql = "SELECT
              *
            FROM
              wtNode
            WHERE
              __guid = $srcGuid";
    $query = wtmysqlquery($sql);

    $sql = "";

    if($row = mysql_fetch_assoc($query)) {
      foreach($nodeAttributes as $attribute) {
        if($sql != "") {
          $sql .= ",";
        }
        $sql .= "$attribute = '" . mysql_escape_string($row[$attribute]) . "'";
      }
    }
    $sql = "UPDATE wtNode SET $sql  WHERE __guid = $dstGuid";
    if(!wtmysqlquery($sql)) {
      print "$sql<br>";
      print mysql_error();
    }
  }


  /**
   * Unlink two nodes
   *
   *  @method unlinkNodes
   *  @param {String} parent The guid or path to the parent node
   *  @param {String} child The guid or path to the child node
   */

  function unlinkNodes($parent, $child) 
  {
    $parentNode = $this->getNode($parent);
    $childNode = $this->getNode($child);
    if($parentNode == NULL || $childNode == NULL) {
      return false;
    }

    $sql = "SELECT
              COUNT(*)
            FROM
              wtNode
            WHERE
              __deleted = 0
              AND __parentGuid = {$parentNode->m_guid}
              AND (__guid = {$childNode->m_guid}
                   OR __nodeIsHolderForGuid = {$childNode->m_guid})";
    $query = wtmysqlquery($sql);
    $row = mysql_fetch_row($query);
    if($row[0] == 0) {
      return true;
    }

    $sql = "DELETE FROM
              wtNode
            WHERE
              __parentGuid = {$parentNode->m_guid}
            AND
              __nodeIsHolderForGuid = {$childNode->m_guid}";

    if(!wtmysqlquery($sql)) {
      print $sql;
      print mysql_error();
      return false;
    }

    $childNode->setNodeParents();
    $childNode->unlinkedFromParent($parentNode);
    return true;
  }

  /**
   *  Test if two nodes are linked
   *
   *  @method nodesAreLinked
   *  @param {String} parent The guid or path to the parent node
   *  @param {String} child The guid or path to the child node
   *  @return {boolean} Returns true if the two nodes are linked
   *
   */
  function nodesAreLinked($parent, $child) 
  {
    if(is_object($parent)) {
      $parentNode = $parent;
    } else {
      $parentNode = $this->getNode($parent);
    }
    if(is_object($child)) {
      $childNode = $child;
    } else {
      $childNode = $this->getNode($child);
    }
    if($parentNode == NULL || $childNode == NULL) {
      return false;
    } 
    $sql = "SELECT
              COUNT(*) 
            FROM
              wtNode 
            WHERE
              __parentGuid = {$parentNode->m_guid}
              AND (__guid = {$childNode->m_guid}
                   OR __nodeIsHolderForGuid = {$childNode->m_guid})";
    $query = wtmysqlquery($sql);
    $row = mysql_fetch_row($query);
    return $row[0] > 0;     
  }

  /**
   *  Link two nodes
   *
   *  @method linkNodes
   *  @param {String} parent The guid or path of the parent node
   *  @param {String} child The guid or path of the child node
   */
  function linkNodes($parent, $child) 
  {
    if(is_object($parent)) {
      $parentNode = $parent;
    } else {
      $parentNode = $this->getNode($parent);
    }
    if(is_object($child)) {
      $childNode = $child;
    } else {
      $childNode = $this->getNode($child);
    }

    if($parentNode == NULL || $childNode == NULL) {
      return false;
    }
    //  check if items already linked
    $sql = "SELECT
              COUNT(*)
            FROM 
              wtNode
            WHERE
              __deleted = 0 
              AND __parentGuid = {$parentNode->m_guid}
              AND (__guid = {$childNode->m_guid}
                   OR __nodeIsHolderForGuid = {$childNode->m_guid})";
    $query = wtmysqlquery($sql);
    $row = mysql_fetch_row($query);
    if($row[0] > 0) {
      return true;
    }
             
    $holderNode = WTNode::create($parentNode->m_guid, "wtNode", Array("Node Name" => $childNode->getName()));
    $this->copyNode($childNode->m_guid, $holderNode->m_guid);    
    $sql = "UPDATE 
              wtNode
            SET
              __nodeIsHolderForGuid = {$childNode->m_guid}
            WHERE
              __guid = {$holderNode->m_guid}";
    if(!wtmysqlquery($sql)) {
      print $sql . "<br>";
      print mysql_error();
    } 

    $childNode->setNodeParents();
    $childNode->linkedToParent($parentNode);
  }

  /**
   *  Write a debug message to the files/debug.txt file inside the current site's directory
   *
   *  @method debugMessage
   *  @param {String} message The debug message
   */
  function debugMessage($message) {
    $debugFile = $GLOBALS["WTSITEDIRECTORY"] . $this->getSiteSetting("Site Directory") . "files/debug.txt";
    
    $fd = @fopen($debugFile, "a");
    if($fd) {
      fwrite($fd, date("Y-m-d H:i:s") . " " . $message . "\n");
      fclose($fd);
    }
   
  }


  /**
   *  Get the the translation node for a node, return NULL if the node does not exist
   *
   *  @method getTranslationNode
   *  @param {int} guid The guid of the node to get the translation for
   *  @param {int} languageID The guid of the language to get the translation node
   */
  function getTranslationNode($guid, $languageID) {
    $translationNodeGuid = 0;
    $sql = "SELECT
              __guid
            FROM 
              wtNode
            WHERE
              __translationOfGuid = $guid
              AND __languageID = $languageID
              AND __deleted = 0";
    $query = mysql_query($sql);

    if($row = mysql_fetch_row($query)) {
      $translationNodeGuid = $row[0];
    }

    if($translationNodeGuid != 0) {
      return $GLOBALS["WT"]->getNode($translationNodeGuid);
    }
    return NULL;
  }


  function getTranslation($data, $languageID) {
    if(array_key_exists("__guid", $data)) {
      $translationNode = $this->getTranslationNode($data["__guid"], $languageID);
      if($translationNode) {
        return $translationNode->getAttributes();
      }
    }
    return $data;
  }

  /**
   *  Set the translation for some text
   *
   *  @method setTextTranslation
   *  @param {String} text The text to set the translation for
   *  @param {int} languageID The id of the language the translation is being provided for
   *  @param {String} translation The text of the translation
   */
  function setTextTranslation($text, $languageID, $translation) {
    $q = Array();
    $q["Node Type"] = "wtText";
    $q["Path"] = "/Languages/Text/*";
    $q["Criteria"] = "`Text` = '" . mysql_escape_string($text) . "'";
    $q["Limit"] = 1;
    $q["Select"] = "wtNode.__guid";
    $textID = $GLOBALS["WT"]->query($q, "singleValueCallback");
    if(!$textID) {
      $textParentNode = $GLOBALS["WT"]->getNode("/Languages/Text");
      $textNode = $textParentNode->createChild("wtText", Array("Text" => $text));
    } else {
      $textNode = $GLOBALS["WT"]->getNode($textID);
    }
    $translationNode = $textNode->getTranslationNode($languageID, true);
    $translationNode->setAttributes(Array("Text" => $translation));
  }


  /**
   *  Get the translation of some text
   *
   *  @method getTextTranslation
   *  @param {String} text
   *  @param {int} languageID The ID of the language to get the translation for
   *  @return The translation of the text, or the original text if no translation exists
   */
  function getTextTranslation($text, $languageID, $isstatic = false) {
    if($languageID == 0) {
      return $text;
    }
    $translation = $text;
    $currentLanguageID = $GLOBALS["WTLANGUAGEID"];
    $GLOBALS["WTLANGUAGEID"] = 0;
/*
    $q = Array();
    $q["Node Type"] = "wtText";
    $q["Path"] = "/Languages/Text/*";
    $q["Criteria"] = "`Text` = '" . mysql_escape_string($text) . "'";
    $q["Select"] = "wtNode.__guid";
    $q["Limit"] = 1;
    $textID = $GLOBALS["WT"]->query($q, "singleValueCallback");
*/
    $textID = 0;

    $sql = "SELECT                    
              wtNode.__guid
            FROM
              wtNode, `wtText`                    
            WHERE
              `wtText`.__guid = wtNode.__nodeIsHolderForGuid
              AND wtNode.__deleted = 0
              AND `wtText`.__active = 1
              AND wtNode.__hidden = 0
              AND __translationOfGuid = 0
              AND (`Text` = '" . mysql_escape_string($text) . "') 
              ORDER BY wtNode.__position
              LIMIT 1";
    $query = mysql_query($sql);
    if($row = mysql_fetch_row($query)) {
      $textID = $row[0];
    }
    
    if(!$textID && $isstatic) {
      $textParentNode = $GLOBALS["WT"]->getNode("/Languages/Text");
      $textNode = $textParentNode->createChild("wtText", Array("Text" => $text, "Is Static Text" => "Yes"));
      $textID = $textNode->m_guid;
    }

    if($textID) {


      $sql = "SELECT
                __guid
              FROM
                wtNode
              WHERE
                __translationOfGuid = $textID
                AND __languageID = $languageID
                AND __deleted = 0";
      $query = mysql_query($sql);
      if($row = mysql_fetch_row($query)) {

        $translationNodeGuid = $row[0];
        $sql = "SELECT
                  `Text`
                FROM
                  `wtText` 
                WHERE
                  __guid = $translationNodeGuid";
        $query = mysql_query($sql);
        if($row = mysql_fetch_row($query)) {
          $translation = $row[0];
        }  

      }

/*

      $textNode = $GLOBALS["WT"]->getNode($textID);
      if($textNode) {
//print "found text $text";
        $translationNode = $textNode->getTranslationNode($languageID);
        

        if($translationNode) {
          $translation =  $translationNode->getAttribute("Text");
        }
      }
*/
    }  
    $GLOBALS["WTLANGUAGEID"] = $currentLanguageID;  
    return $translation;
  }


  function logEvent($event, $description, $node) {
    $events = $GLOBALS["WT"]->getNode("/Events");
    if($events != NULL) {
      $events->createChild("wtEvent", Array("Event" => $event, "Description" => $description, "Contact ID" => $this->m_contactGuid, "Node" => $node));
    }

  }

  /**
   *  Perform a query on the WebTemplate Database
   *
   *  Examples:
   *
   *  The following example will print all contacts whose name starts with 'a'
   *  <code>
   *  $q = Array();
   *  $q["Node Type"] = "wtContact";
   *  $q["Path"] = "/Contacts/*";
   *  $q["Criteria"] = "`First Name` LIKE 'a%'"
   *  $q["Order By"] = "`First Name`";
   *  $q["Template Source"] = "[wt:First Name] [wt:Last Name]";
   *  print $GLOBALS["WT"]->query($q);
   *  </code>
   *
   *  The following example will call a callback for each result
   *
   *  <code>
   *  function callbackFunction($data, $args) {
   *    print 'name = ' . $data["First Name"];
   *  }
   *
   *  $q = Array()
   *  $q["Node Type"] = "wtContact";
   *  $GLOBALS["WT"]->query($q, "callbackFunction");
   *
   *
   *  </code>
   *
   *
   *
   *  @method query
   *  @param {Array} args the specification of the query
   *  @param {String} callback a function to be called for each result of the query, the callback will task 2 arguments, the first an array of results, the second information about the results
   *  @param {String} noresultscallback a function to be called if there are no results
   *  @return {String} the results from the query
   */

  function query($args, $callback = "renderCallback", $noresultscallback = NULL) 
  {
    if(array_key_exists("id", $args)) {
      $GLOBALS["WTQUERY_" . $args["id"]] = Array();
      $GLOBALS["WTQUERY_" . $args["id"]]["query"] = $args;
    }

    if(array_key_exists("Index", $args) && $args["Index"] = "no") {
      if($this->getMode() == "index") {
        return false;

      }
    }

    $path = false;
    if(array_key_exists("Path", $args)) {     
      $path = trim($args["Path"]);

      if($path == "") {
        return false;
      }
    }

    if($path !== false) {
      $nodeIsParent = false;
      if(substr($path, strlen($path) - 2) == '/*') {
        $nodeIsParent = true;
        $path = substr($path, 0, strlen($path) - 2);
      }
      $node = $this->getNode($path);

      if($node == NULL) {
        return false;
      }
    } else {
      $nodeIsParent = true;
    }
    
    $data = "";
    if($nodeIsParent) {

      $permissionsSql = "";

      if(!$this->m_contactIsAdministrator) {
        if($args != NULL && array_key_exists("Mode", $args) && strtolower($args["Mode"]) == "list") {
          $permissionsSql = "AND (wtNode.__allList = 1";
          if(count($this->m_contactGroups) > 0) {
            $permissionsSql .= " OR wtNode.__groupList IN (" . implode(",", $this->m_contactGroups) . ")";
          }
          $permissionsSql .= ")";

        } else {
          $permissionsSql = "AND (wtNode.__allRead = 1";
          if(count($this->m_contactGroups) > 0) {
            $permissionsSql .= " OR wtNode.__groupRead IN (" . implode(",", $this->m_contactGroups) . ")";
          }
          $permissionsSql .= ")";
        }
      }

      $permissionsSql .= " AND wtNode.__hidden = 0";

      if(array_key_exists("Ignore Permissions", $args) && $args["Ignore Permissions"] == "yes") {
        $permissionsSql = " AND wtNode.__hidden = 0";
      }


      if((isset($args["Node Type"]) && $args["Node Type"] != "") || (array_key_exists("Type", $args) && $args["Type"] != "")) {
        $typeName = $args["Node Type"];
        if($typeName == "") {
          $typeName = $args["Type"];
        }
 
/*        $permissionsSql = "";

        if(!$this->m_contactIsAdministrator) {
          if($args != NULL && array_key_exists("Mode", $args) && $args["Mode"] == "List") {
            $permissionsSql = "AND (__allList = 1";
            if(count($this->m_contactGroups) > 0) {
              $permissionsSql .= " OR __groupList IN (" . implode(",", $this->m_contactGroups) . ")";
            }
            $permissionsSql .= ")";
          } else {
            $permissionsSql = "AND (__allRead = 1";
            if(count($this->m_contactGroups) > 0) {
              $permissionsSql .= " OR __groupRead IN (" . implode(",", $this->m_contactGroups) . ")";
            }
            $permissionsSql .= ")";
          }
        }

        $permissionsSql .= " AND __hidden = 0";

*/

        $parentSql = "";
        if($path !== false) {
          $parentSql = " AND wtNode.__parentGuid = {$node->m_guid}";
        }


        $selectSql = "wtNode.__guid AS __nodeGuid, wtNode.*, `$typeName`.*";
        if($args != NULL && array_key_exists("Select", $args)) {
          if(trim($args["Select"]) != "") {
            $selectSql = $args["Select"];
          }
        }

        $joinSql = "";
        if($args != NULL && array_key_exists("Join", $args)) {
          if(trim($args["Join"]) != "") {
            $joinSql = $args["Join"];
          }
        }

        $criteriaSql = "";
        if($args != NULL && array_key_exists("Criteria", $args)) {
	  if(trim($args["Criteria"]) != "") {
            $criteriaSql = " AND ({$args["Criteria"]}) ";
	  }
        }

        $havingSql = "";
        if($args != NULL && array_key_exists("Having", $args)) {
          if(trim($args["Having"]) != "") {
            $havingSql = " HAVING " . $args["Having"];
          }
        }

//        if($GLOBALS["WTSITEID"] != 11249) {
        $orderBySql = "ORDER BY wtNode.__position";
//        }
        if($args != NULL && array_key_exists("Order By", $args)) {
          if(trim($args["Order By"]) != "") {
            $orderBySql = "ORDER BY " . $args["Order By"];
          }
        }

        $groupBySql = "";
        if($args != NULL && array_key_exists("Group By", $args)) {
          if(trim($args["Group By"]) != "") {
            $groupBySql = "GROUP BY " . $args["Group By"];
          }
        }

        $limitSql = "";
        if($args != NULL && array_key_exists("Limit", $args)) {
          if(trim($args["Limit"]) != "") {
            $limitSql = "LIMIT " . $args["Limit"];
          }
        }

        if($GLOBALS["WTSITEID"] == 11238 || $GLOBALS["WTSITEID"] == 11249) {
          $straightJoinSql = "STRAIGHT_JOIN";
        }

        if($args != NULL && array_key_exists("Straight Join", $args) && $args["Straight Join"] == "no") {
          $straightJoinSql = "";
        }

        if($args != NULL && array_key_exists("Straight Join", $args) && $args["Straight Join"] == "yes") {
          $straightJoinSql = "STRAIGHT_JOIN";
        }


        $allChildrenSql = "";
        if($args != NULL && array_key_exists("All Children", $args) && $path != false) {
          
          $joinSql .= " INNER JOIN tblNodeChildren ON wtNode.__guid = tblNodeChildren.childNodeGuid ";
          $parentSql = " AND tblNodeChildren.parentNodeGuid = {$node->m_guid}";
        }

        if($args != NULL && array_key_exists("Keywords", $args)) {
          if(trim($args["Keywords"]) != "") {
            $keywords = trim($args["Keywords"]);
            if($keywords != "") {
              //$keywords = mysql_escape_string($keywords);
/*              if($joinSql != "") {
                $joinSql .= ",";
              }*/
              $joinSql .= " INNER JOIN tblNodeKeywords ON wtNode.__nodeIsHolderForGuid = tblNodeKeywords.nodeGuid";
              if(array_key_exists("Extract", $args) && $args["Select"] != "COUNT(*)") {
                $selectSql .= ", tblNodeKeywords.nodeKeywords as __extract";
              }

              if(array_key_exists("Match", $args) && $args["Match"] == "partial") {
                if(array_key_exists("Splitkeywords", $args) && $args["Splitkeywords"] == "no") {
                  $keywordArray = Array();
                  $keywordArray[] = $keywords;
                } else {
                  $keywordArray = explode(" ", $keywords);
                }
                foreach($keywordArray as $keyword) {
                  $keyword = trim($keyword);
                  if($keyword != "") {
                    $criteriaSql .= " AND nodeKeywords LIKE '%" . mysql_escape_string($keyword) . "%' ";
                  }
                }

              } else {
                $keywordSql = "";
                $terms = wtFmtGetTerms($keywords);
                $terms = array_map("trim", $terms);
                foreach($terms as $term) {
                  if($term != "") {
                    $term = mysql_escape_string($term);
                    if($keywordSql != "") {
                      $keywordSql .= " ";
                    }
                    $keywordSql .= "+" . $term;
                  }
                }
                $criteriaSql .= " AND MATCH (nodeKeywords) AGAINST ('$keywordSql' IN BOOLEAN MODE) ";
              }
            }
          }         
        }
        $activeSql = "AND `$typeName`.__active = 1";
        if($this->getMode() == "edit" || $this->getMode() == "moderate" || $_SESSION["WTPREVIEWMODE"]) {
          $activeSql = "AND `$typeName`.__latest = 1";
        }

        if($typeName == "wtNode") {
          $sql = "SELECT
                    $selectSql
                  FROM
                    wtNode
                    $joinSql
                  WHERE
                    wtNode.__deleted = 0
                    AND wtNode.__typeGuid = 0
                    $parentSql
                    $permissionsSql
                    $criteriaSql
                    $groupBySql
                    $havingSql
                    $orderBySql
                    $limitSql";
        } else {
          $fromSql = "wtNode, `$typeName`"; 
     //     $fromSql = "`$typeName`, wtNode";
/*          if($args != NULL && array_key_exists("Order By", $args)) {
            $fromSql = "`$typeName`, wtNode";
          }*/

/*          $sql = "SELECT
                    STRAIGHT_JOIN
                    $selectSql
                  FROM
                    $fromSql
                    $joinSql
                  WHERE
                    (`$typeName`.__guid = wtNode.__guid
                    OR `$typeName`.__guid = wtNode.__nodeIsHolderForGuid)
                    AND wtNode.__deleted = 0
                    $activeSql
                    $parentSql
                    $permissionsSql
                    $criteriaSql
                    $orderBySql
                    $limitSql";
*/
          $sql = "SELECT
                    $straightJoinSql
                    $selectSql
                  FROM
                    $fromSql
                    $joinSql
                  WHERE
                    `$typeName`.__guid = wtNode.__nodeIsHolderForGuid
                    AND wtNode.__deleted = 0
                    $activeSql
                    $parentSql
                    $permissionsSql
                    $criteriaSql
                    $groupBySql
                    $havingSql
                    $orderBySql
                    $limitSql";

        }


/*
`$typeName`.__luid = wtNode.__luid
                    (`$typeName`.__guid = wtNode.__guid
                    OR `$typeName`.__guid = wtNode.__nodeIsHolderForGuid)

*/
//print $sql;


        $GLOBALS["WTLASTQUERY"] = $sql;
        $query = wtmysqlquery($sql);

        if(!$query) {
          print "$sql<br>";
          print mysql_error();
        }

        $count = 0;
        $numResults = mysql_num_rows($query);
        while($row = mysql_fetch_assoc($query)) {
          if($callback != NULL) {
            
            $args["Total Results"] = $numResults;
            $args["Result Number"] = $count + 1;

            if($GLOBALS["WTLANGUAGEID"] != 0) {
              $guid = $row["__guid"];
              if($guid) {
                $row = $this->getTranslation($row, $GLOBALS["WTLANGUAGEID"]);
                $row["__guid"] = $guid;
              }
            }

            $data .= $callback($row, $args);
              
          }
          $count++;
        }
      } else {
        $selectSql = "*";
        if($args != NULL && array_key_exists("Select", $args)) {
          if(trim($args["Select"]) != "") {
            $selectSql = $args["Select"];
          }
        }

        $criteriaSql = "";
        if($args != NULL && array_key_exists("Criteria", $args)) {
          if(strpos($args["Criteria"], "__name") !== false || strpos($args["Criteria"], "__guid") !== false) {
            if(trim($args["Criteria"]) != "") {
              $criteriaSql = " AND ({$args["Criteria"]}) ";
            }
          }
        }


        $sql = "SELECT
                  $selectSql
                FROM 
                  wtNode
                WHERE
                  wtNode.__parentGuid = {$node->m_guid}
                  $permissionsSql
                  $criteriaSql
                  AND wtNode.__deleted = 0
                ORDER BY
                  wtNode.__position";

//print $sql;

        $GLOBALS["WTLASTQUERY"] = $sql; 
        
        $query = wtmysqlquery($sql);
        if(!$query) {
          print $sql;
          print mysql_error();
        }

        $count = 0;
        $numResults = mysql_num_rows($query);
        while($row = mysql_fetch_assoc($query)) {
          if($callback != NULL) {
            if($args != NULL && array_key_exists("Select", $args)) {

              if($GLOBALS["WTLANGUAGEID"] != 0) {
                $guid = $row["__guid"];
                if($guid) {
                  $row = $this->getTranslation($row, $GLOBALS["WTLANGUAGEID"]);
                  $row["__guid"] = $guid;
                }
              }

              $data .= $callback($row, $args);
            } else {
              if($row["__nodeIsHolderForGuid"] > 0) {
                $child = $GLOBALS["WT"]->getNode($row["__nodeIsHolderForGuid"]);
              } else {
                $child = $GLOBALS["WT"]->getNode($row["__guid"]);
              }
              if($child != NULL) {
                $args["Total Results"] = $numResults;
                $args["Result Number"] = $count + 1;
               
                $attributes = $child->getAttributes();
                if($GLOBALS["WTLANGUAGEID"] != 0) {
                  $guid = $attributes["__guid"];
                  $attributes = $this->getTranslation($attributes, $GLOBALS["WTLANGUAGEID"]);
                  $attributes["__guid"] = $guid;
                }

                $data .= $callback($attributes, $args);
              }
            }
            $count++;
          }
        }
      }
              
    } else {
      if($callback != NULL) {
        $args["Total Results"] = 1;
        $args["Result Number"] = 1;
        $GLOBALS["WTLASTQUERY"] = "getNode()";
        $latest = false;
        if($_SESSION["WTPREVIEWMODE"]) {
          $latest = true;
        }
        $data .= $callback($node->getAttributes($latest), $args);
      }
    }

    if($count == 0 && $noresultscallback != NULL) {
      return $noresultscallback(Array(), $args);
    }

    return $data;
  }

  function csvPreview($file, $rows = 10) 
  {
    $data = Array();
    if(file_exists($file)) {
      $fp = fopen($file, "r");
      $count = 0;
      while(($row = fgetcsv($fp, 5000, ",")) && $count < $rows) {
        $data[] = $row; 
        $count++;
      }
    }
    return $data;
  }

  function csvCountRows($file, $requiredField = "") 
  {
    $count = 0;
    if(file_exists($file)) {
      $fp = fopen($file, "r");
      $headings = fgetcsv($fp, 5000, ",");
      $count = 0;
      while(($row = fgetcsv($fp, 5000, ","))) {

/*
        $data = Array();
        for($i = 0; $i < count($headings); $i++) {
          $data[$headings[$i]] = $row[$i];
        }
        if($requiredField != "" && trim($data[$requiredField]) == "") {
          continue;
        }
*/
        $count++;
      }
    }
    return $count;
  }

  function csvImport($type, $parent, $file, $idfield = "", $requiredField = "", $callback = null, $callbackData = null) 
  {
    $parentNode = $GLOBALS["WT"]->getNode($parent);
    if($parentNode == NULL) {
      return false;
    }
    if(file_exists($file)) {
      $fp = fopen($file, "r");
      $headings = fgetcsv($fp, 5000, ",");
      if($idfield != 0 && !in_array($idfield, $headings)) {
        return false;
      }
      while($row = fgetcsv($fp, 5000, ",")) {
        $data = Array();
        for($i = 0; $i < count($headings); $i++) {
          $data[$headings[$i]] = $row[$i];
        }
        $guid = 0;
        if($idfield != "") {
          $sql = "SELECT
                    wtNode.__guid 
                  FROM
                    `$type`, wtNode
                  WHERE
                    `$type`.__guid = wtNode.__guid
                    AND `$type`.`$idfield` = '" . mysql_escape_string($data[$idfield]) . "'
                    AND __active <> 0 
                    AND __deleted <> 1";

          $query = wtmysqlquery($sql);
          if($row = mysql_fetch_row($query)) {
            $guid = $row[0];
          } 
        }


        if($guid != 0) {
          $node = $GLOBALS["WT"]->getNode($guid);
          $node->setAttributes($data);
          if($callback != null) {
            $callback($node, $data, $callbackData);
          }
        } else {
          if(trim($data[$requiredField]) != "" || $requiredField == "") {
            $node = $parentNode->createChild($type, $data); 
            if($callback != null) {
              $callback($node, $data, $callbackData);
            }
          }
        }
      }
      fclose($fp);
    }
  }

  /**
   * Get the options defined in a string
   *
   *  @method getOptionsFromString
   *  @param {String} optionString
   *  @return {Array} The options as an array
   */
  function getOptionsFromString($optionString) 
  {
    $options = Array();
    $optionArray = explode(",", $optionString);
    foreach($optionArray as $option) {
      list($name, $id) = explode(":", $option);
      $options[$id] = $name;
    }
    return $options;
  }


  /**
   *  Get options as an array
   *
   *  @method optionsPath
   *  @param {String} optionsPath The path to the parent of the options, or the name of built in options (eg "wtCountries")
   *  @param {Array} [optionQuery=Array()] A WT query specifying which nodes to use as the options
   */
  function getOptions($optionsPath, $optionQuery = Array()) {

    $options = Array();
    if($optionsPath == "Member Groups") {
      $optionsPath = "/Groups";
      $optionQuery["Node Type"] = "Group";
      $optionQuery["Criteria"] = "`Type` = 'Member Group'";
    }
    if($optionsPath == "Admin Groups") {
      $optionsPath = "/Groups";
      $optionQuery["Node Type"] = "Group";
      $optionQuery["Criteria"] = "`Type` = 'Admin Group'";
    }

    if($optionsPath == "wtCountries") {
      $sql = "SELECT
                countryID, countryName
              FROM
                dbCountries.tblCountry
              ORDER BY
                countryName";
      $query = wtmysqlquery($sql);
      while($row = mysql_fetch_row($query)) {
        $options[$row[0]] = $row[1];
      }
      return $options;
    } else if(array_key_exists($optionsPath, $GLOBALS["WTBUILTINOPTIONS"])) {
      $options = $GLOBALS["WTBUILTINOPTIONS"][$optionsPath];
    } else {
      $optionNode = $GLOBALS["WT"]->getNode("/Config/Options/" . $optionsPath);
      if($optionNode == NULL) {
        $optionNode = $GLOBALS["WT"]->getNode($optionsPath);
      }
      if($optionNode != NULL) {
        $results = Array();
        $optionQuery["Path"] = $optionNode->m_guid . "/*";
	if(!array_key_exists("Select", $optionQuery)) {
          $optionQuery["Select"] = "wtNode.__guid, wtNode.__name";
        }	 
        $optionQuery["Results Array"] = &$results;


        $this->query($optionQuery);
        $options = Array();
        foreach($results as $result) {
          $options[$result["__guid"]] = $result["__name"];
        }

      }
    }

    return $options;
  }

  /**
   *  Given an id, get the related option as a String
   *
   *  @method getOptionValue
   *  @param {String} options The path to the options, or the name of some built in options (eg "wtCountries")
   *  @param {int} id The ID of the option
   *  @return {String} The String name of the option
   */
  function getOptionValue($options, $id)
  {
    if(array_key_exists($options, $GLOBALS["WTBUILTINOPTIONS"])) {
      return $GLOBALS["WTBUILTINOPTIONS"][$options][$id];
    } else if($options == "wtCountries") {
      $id = (int)$id;
      $sql = "SELECT
                countryName
              FROM
                dbCountries.tblCountry
              WHERE
                countryID = $id";
      $query = wtmysqlquery($sql);
      if($row = mysql_fetch_row($query)) {
        return $row[0];
      } 
    } else {
      $node = $this->getNode($id);
      if($node != NULL) {
        return $node->getName();
      }
    }
    return false;
  }

  /**
   *  Get the id of an option, given its string value
   *
   *  @method getOptionID
   *  @param {String} options The path to the options, or the name of some built in options (eg "wtCountries")
   *  @param {String} value The string value of the option
   *  @return {int} The ID of the option
   */
  function getOptionID($options, $value) 
  {
    if(array_key_exists($options, $GLOBALS["WTBUILTINOPTIONS"])) {
      foreach($GLOBALS["WTBUILTINOPTIONS"][$options] as $id => $optionvalue) {
        if($value == $optionvalue) {
          return $id;
        }
      }
      return false;
    } else if($options == "wtCountries") {
      $sql = "SELECT
                countryID
              FROM
                dbCountries.tblCountry
              WHERE
                countryName = '" . mysql_escape_string($value) . "'";
      $query = wtmysqlquery($sql);
      if($row = mysql_fetch_row($query)) {
        return $row[0];
      } else {
        return 0;
      }
    } else {
      $node = $this->getNode("/Config/Options/$options/$value");
      if($node != NULL) {
        return $node->m_guid;
      }

      $node = $this->getNode("$options/$value");
      if($node != NULL) {
        return $node->m_guid;
      }
    }
    return false;
  }


  /**
   *  Return true if moderation is enabled
   *
   *  @method getModerationEnabled
   *  @return {boolean} Returns true if moderation is enabled
   *
   */
  function getModerationEnabled() 
  {
    return $this->m_moderationEnabled;
  }

  /**
   *  Turn moderation on or off
   *
   *  @method setModerationEnabled
   *  @param {boolean} enabled Set to true to turn on moderation
   */
  function setModerationEnabled($enabled) 
  {
    $this->m_moderationEnabled = $enabled;
  }


  /**
   *  Test if a Request value exists
   *
   *  @method requestValueExists
   *  @param {String} name The name of the request value
   *
   */
  function requestValueExists($name) 
  {
    return array_key_exists($name, $_REQUEST);
  }

  /**
   *  Get a POST value, or return a default value if it doesn't exist
   *
   *  @method getPostValue
   *  @param {String} name The name of the post variable
   *  @param {String} [default=""] The default value if the post variable doesn't exist
   *  @return {String} The POST value
   */  
  function getPostValue($name, $default = "")
  {
    if(array_key_exists($name, $_POST)) {
      if(get_magic_quotes_gpc()) {
        return stripslashes($_POST[$name]);
      } else {
        return $_POST[$name];
      }
    } 
    return $default;
  }



  /**
   *  Get a REQUEST value, or return a default value if it doesn't exist
   *
   *  @method getRequestValue
   *  @param {String} name The name of the request variable
   *  @param {String} [default=""] The default value if the request variable doesn't exist
   *  @return {String} The REQUEST value
   */
  function getRequestValue($name, $default = "") 
  {
    if(array_key_exists($name, $_REQUEST)) {
      if(get_magic_quotes_gpc()) {
        return stripslashes($_REQUEST[$name]);
      } else {
        return $_REQUEST[$name];
      }
    }
    return $default;
  }

  function getRequestNode($name, $default = 0) 
  {
    $path = $this->getRequestValue($name);
    return $this->getNode($path);
  }

  /**
   *  Switch to secure mode
   *
   *  @method switchToSecure
   *  @param {String} [uri=""] If set, redirect to this uri in secure mode
   *  @param {String} [secureURL=""] If set, use this secure URL instead of the one in settings
   */
  function switchToSecure($uri = "", $secureURL = "") {
    if(!array_key_exists("HTTPS", $_SERVER) || strtolower($_SERVER["HTTPS"]) != "on" || $uri != "") {
      if($secureURL == "") {
        $secureURL = WTConfig::get("Site Details/Site Secure URL");
      }

      if($secureURL) {
        if($uri == "") {
          $uri = $_SERVER["REQUEST_URI"];
          $uri = substr($uri, strlen($this->getSiteSetting("Site Base")));
        }
        $secureURL .= "__session/" . WTSession::getKey() . "/" .$uri;
//            print "secure url = $secureURL";
        header("Location: $secureURL");
        exit("");
      }
    }
  }


  /**
   *  Set or add a parameter in the query part of a URI
   *
   *  @method setURIParameter
   *  @param {String} uri The uri to set the parameter for
   *  @param {String} param The name of the parameter
   *  @param {String} value The value of the parameter
   *  @param {boolean} [encodeValue=true] If true, then url encode the value
   *  @return {String} The url with the parameter set in the query section
   */

  function setURIParameter($uri, $param, $value, $encodevalue = true) 
  {
    $pos = strpos($uri, "#");
    $fragment = "";
    if($pos !== false) {
      $uri = substr($uri, 0, $pos);
      $fragment = substr($uri, $pos);
    }
    $pos = strpos($uri, "?");
    if($pos === false) {
      if($encodevalue) {
        $value = urlencode($value);
      }
      return $uri .= "?$param=" . $value . $fragment;
    } else {
      $base = substr($uri, 0, $pos);
      $query = substr($uri, $pos + 1);
       
      $queryArray = Array();
      parse_str($query, $queryArray);
      $queryArray[$param] = $value;
      if($encodevalue) {
        $queryArray = array_map("urlencode", $queryArray);
      }
      $query = "";
      foreach($queryArray as $k => $v) {
        if(trim($v) != "") {
          if($query != "") {
            $query .= '&';
          }
          $query .= "$k=$v";
        }
      }
//      $query = http_build_query($queryArray);
      if($query == "") {
        return "$base$fragment";
      } else {
        return "$base?$query$fragment";
      }
    }
    
  }


  /**
   *  Register a function to process a URI
   *
   *  @method registerURIHandler
   *  @param {String} uri The uri to handle
   *  @param {Function} function The function to call for the url
   */
  function registerURIHandler($uri, $function) 
  {
    $GLOBALS["WTURIHANDLERS"][$uri] = $function;
  }

  /**
   *  Register a function to be called when a page is not found
   *
   *  @method registerPageNotFoundHandler
   *  @param {Function} function The function to call on page not found
   */
  function registerPageNotFoundHandler($function) 
  {
    $GLOBALS["WTPAGENOTFOUNDHANDLER"] = $function;
  }

  function registerURIProcessor($function)
  {
    $GLOBALS["WTURIPROCESSOR"] = $function;
  }

  function getRequestURI($absolute = false) 
  {
    if($absolute) {
      return $_SERVER["REQUEST_URI"];
    } else {
      return $_SERVER["REQUEST_URI"];
    }
  }

  /**
   *  Get a wt value, eg getWTValue("wt.page.uri")
   *
   *  @method getWTValue 
   *  @param {String} path The path to get
   *  @return {String} The value for the path
   *
   */

  function getWTValue($path) 
  {
    if(in_array($path, $GLOBALS["WTVALUECACHE"])) {
      return $GLOBALS["WTVALUECACHE"][$path];
    }

    $pathElements = explode(".", $path);
    $countPathElements = count($pathElements);
    
    if($countPathElements <= 1) {
      return "";
    }

    switch($pathElements[1]) {
      case "currentuser":
        if($countPathElements > 2) {
          if($pathElements[2] == "guid") {
            return $this->m_contactGuid;
          } else if($pathElements[2] == "ismember") {
            return $GLOBALS["WT"]->nodesAreLinked("/Groups/__Members", $this->m_contactGuid);
          } else if($pathElements[2] == "isadmin") {
            return $GLOBALS["WT"]->contactIsAdministrator();
          } else if($pathElements[2] == "isglobaladmin") {
            return $GLOBALS["WT"]->m_contactIsAdministrator;
          } else if($pathElements[2] == "isadminloggedinas") {
            return array_key_exists("WTLOGGEDINAS", $_SESSION) && $_SESSION["WTLOGGEDINAS"];
          } else if($pathElements[2] == "ipaddress") {
            return $_SERVER["REMOTE_ADDR"];
          } else if($pathElements[2] == "location") {
            $location = $GLOBALS["WT"]->getUserLocation();
            return $location["country"];
          } else {
            $currentUser = $this->getCurrentUser();
            if($currentUser != NULL) {
              return $currentUser->getAttribute($pathElements[2]); 
            } else {
print "current user is null";
            }
          }
        }
        break;
      case "request":
        if($countPathElements > 2) {
          return $this->getRequestValue($pathElements[2]);
        }
        break;
    
      case "page":
        if($countPathElements > 2) {
          switch($pathElements[2]) {
            case 'guid':
              return $this->m_currentPage->m_guid;
              break;
            case 'depth':
              return $this->m_currentPage->getDepth("/Pages") - 1;
              break;
            case 'issecure':
              return array_key_exists("HTTPS", $_SERVER) && strtolower($_SERVER["HTTPS"]) == "on";
              break;
            case 'uri':
              if($this->m_currentPage) {
                return $this->m_currentPage->getURI();
              } else {
                return "";
              }

              break;
            default:
              return $this->m_currentPage->getAttribute($pathElements[2]);
          }
          if($pathElements[2] == "guid") {
            return $this->m_currentPage->m_guid;
          }
        }
        if($this->m_currentPage) {
          return $this->m_currentPage->getURI();
        } else {
          return "";
        }
        break;
      case "uri":
        return $_SERVER["REQUEST_URI"];
        break;
      case 'servername':
        return $_SERVER["SERVER_NAME"];
        break;
      case "mode":
        return $this->getMode();
        break;
      case "membership":
        return WTMembership::getValue($pathElements);
        break;
      case "date":
        if($countPathElements > 2) {
          switch($pathElements[2]) {
            case 'now':
              return date("Y-m-d H:i:s");
              break;
            case 'today':
              return date("Y-m-d");
              break;
            case 'tomorrow':
              return date("Y-m-d", time() + 24 * 60 * 60);
              break;
            case 'yesterday':
              return date("Y-m-d", time() - 24 * 60 * 60);
              break;
            case 'lastmonth':
              return date("Y-m-d", time() - 30 * 24 * 60 * 60);
            case 'monthstart':
              return date("Y", time()) . "-" . date("m", time()) . "-01";
          }
        } else {
          return date("Y-m-d");
        }
      case "vars":
        if($countPathElements > 2) {
          return $GLOBALS["WTVARS" . $pathElements[2]];
        }
        break;
      case "config":
      case "settings":
        $path = "/Config/Settings";
        $elementCount = count($pathElements);
        for($i = 2; $i < $elementCount; $i++) {
          $path .= '/' . $pathElements[$i];
        }
        $node = $GLOBALS["WT"]->getNode($path);
        if($node != NULL) {
          $value = $node->getAttribute("Value");
//          $GLOBALS["WTVALUECACHE"][$path] = $value;
          return $value;
        }
        break;
      case "language":
        if($pathElements[2] == 'guid') {
          return $GLOBALS["WTLANGUAGEID"];
        }
        if($pathElements[2] == 'defaultlanguageguid') {
          return WTConfig::get("Multilingual/Default Language");
        }
        if($pathElements[2] == 'direction') {
          if($GLOBALS["WTLANGUAGEID"] != 0) {
            $languageNode = $GLOBALS["WT"]->getNode($GLOBALS["WTLANGUAGEID"]);
            if($languageNode && $languageNode->m_typeName == "wtLanguage") {
              return $languageNode->getAttribute("Direction");
            }
          }
          return "";
        }
        break;
      case "cart":
        $cart = new WTCart();
        if($countPathElements > 2) {
          if($pathElements[2] == 'count') {
            return $cart->getTotalItemCount();
          } else {
            return $cart->getValue($pathElements);
          }
        }
        break;
      case "browser":
        if(!isset($_SESSION["WTBROWSERDETAILS"]) ) {
//          WTSession::set("WTBROWSERDETAILS", @get_browser(null, true));
          $_SESSION["WTBROWSERDETAILS"] = @get_browser(null, true);
        }

        if($countPathElements == 2) {
          return strtolower($_SESSION["WTBROWSERDETAILS"]["browser"]);
        } else {
          switch($pathElements[2]) {
            case 'version':
              return $_SESSION["WTBROWSERDETAILS"]["version"];
              break;
            case 'majorver':
              return $_SESSION["WTBROWSERDETAILS"]["majorver"];
              break;
            case 'minorver':
              return $_SESSION["WTBROWSERDETAILS"]["minorver"];
              break;
            case 'platform':
              return strtolower($_SESSION["WTBROWSERDETAILS"]["platform"]);
              break;
            case 'useragent':
              return $HTTP_USER_AGENT;
              break;
          }
        }
        break;
      case "session":
        $value = "";
        if($countPathElements > 2) {
          $value = WTSession::get($pathElements[2]);
          if($countPathElements > 3) {
            $value = $value[$pathElements[3]];
          }
          return $value;
        }
        break;
      case "site":
        if($countPathElements > 2) {
          $value = "";
          switch($pathElements[2]) {
            case 'base':
              $value = $this->getSiteSetting("Site Base");
              break;
            case 'name':
              $value = $this->getSiteSetting("Site Name");
              break;
            case 'abbreviation':
              $value = $this->getSiteSetting("Site Abbreviation");
              break;
            case 'id':
              $value = $this->getSiteSetting("Site ID");
              break;              
          }
//          $GLOBALS["WTVALUECACHE"][$path] = $value;
          return $value;
        }
        break;
      case "form":
        if($countPathElements > 2) {
          if($pathElements[2] == "error") {
            return $GLOBALS["WTFORMERROR"];
          }
        }
        break;
    }
    return "";
  }


  function getExtension($name)
  {

    if(array_key_exists($name, $this->m_extensions)) {
      return $this->m_extensions[$name];
    }

    $extension = $GLOBALS["WT"]->getNode("/Extensions/$name");


    if($extension != NULL) {
      $extension->initialise();
      $extensionClass = "WTE$name";
      $this->m_extensions[$name] = new $extensionClass($extension->m_guid);
      return $this->m_extensions[$name];
    }
    return NULL;
  }

  function installExtension($directory, $name)
  {
    if(file_exists($directory)) {
      $extension = $this->getExtension($name);
      if($extension == NULL) {
       
        $extensions = $this->getNode("/Extensions");
        $extension = $extensions->createChild("wtExtension", Array("Name" => $name, "Directory" => $directory));
//        $extension->initialise();
        $extension = $this->getExtension($name);
      }
      $extension->install();
    }

  }

  public function includeCodeInDirectory($codeDir) {
    if(file_exists($codeDir)) {
      $d = dir($codeDir);
      while(false !== ($entry = $d->read())) {
        if(strpos($entry, ".php") == strlen($entry) - 4) {
          if($entry[0] != '.' && $entry != '#') {
            include_once($codeDir . $entry);
          }
        }
      }
      $d->close();
    }
  }

  function loadModules() 
  {
    $siteDirectory = $GLOBALS["WTSITEDIRECTORY"] . WTConfig::get("Site Details/Site Directory");

    $modules = Array();
    $q = Array("Node Type" => "wtModule", "Path" => "/Modules/*", "Results Array" => &$modules);
    $this->query($q);


    foreach($modules as $module) {
      $directory = $module["Name"];
      if(file_exists($siteDirectory . "modules/$directory/code/")) {
        $this->includeCodeInDirectory($siteDirectory . "modules/$directory/code/");
      } else if(file_exists($GLOBALS["WTDIRECTORY"] . "modules/$directory/code/")) {
        $this->includeCodeInDirectory($GLOBALS["WTDIRECTORY"] . "modules/$directory/code/");
      }
    }
    
  }

  function uploadToTemp($fieldname) 
  {
    $temppath = $GLOBALS["WTDIRECTORY"] . "temp/" . md5(uniqid(""));
    if(!move_uploaded_file($_FILES[$fieldname]['tmp_name'], $temppath)) {
      print "couldn't upload file";
    }
    return $temppath;
  }

  function getTempFilename($fullpath = false)
  {
    $filename =  md5(uniqid(""));
    $path = $GLOBALS["WTDIRECTORY"] . "temp/" . $filename;
    while(file_exists($path)) {
      $filename = md5(uniqid(""));
      $path = $GLOBALS["WTDIRECTORY"] . "temp/" . $filename;

//      $temppath = $GLOBALS["WTDIRECTORY"] . "temp/" . md5(uniqid(""));
    }
    if($fullpath) {
      return $path;
    } else {
      return $filename;
    }
  }


  function output404() {
    $pagePath = $_SERVER["REDIRECT_URL"];
    $pagePath = substr($pagePath, strlen($GLOBALS["WT"]->getSiteSetting("Site Base")));

    // page not found
    $page = $GLOBALS["WT"]->getNode("/Pages/Special Pages/404 Not Found");
    if($page) {
      $content = $page->render();
      header("HTTP/1.0 404 Not Found");
      print $content;
    } else {
      header("HTTP/1.0 404 Not Found");
      print("<html><head></head><body>");
      print("<span style='font-family: Tahoma;font-size:12px;'><h2>This page cannot be found.</h2>");
      print("<p>The page you are looking for might have been removed, <br/>had its name changed, or is temporarily unavailable.</p>");
      print("Please try the following:<br/>");
      print("<ul><li>If you typed the page address in the Address bar, <br/>make sure that it is spelled correctly.</li><li>Click the <a href=\"javascript:history.back(1);\">Back</a> button to try another link. </li></ul>");
      print("<p style=\"font-size:10px;\">HTTP 404 - File not found</p>");
      print("<p style=\"font-size:9px;\"><b>$pagePath</b></p></span>");
      print("</body></html>");
    }

  }

  function outputURIContent($pagePath) {

    $GLOBALS["WTLANGUAGEID"] = 0;

    $pagePath = ltrim($pagePath, '/'); 
    $pagePathArray = explode("/", $pagePath);


 
    if(count($pagePathArray) > 0) {
      if(array_key_exists($pagePathArray[0], $GLOBALS["WTURIHANDLERS"])) {
        $pagePath = call_user_func($GLOBALS["WTURIHANDLERS"][$pagePathArray[0]], $pagePath);
        if($pagePath === true) {
          return true;
//          exit("");
        }
      }
    }

    if($GLOBALS["WTURIPROCESSOR"]) {
      $pagePath = call_user_func($GLOBALS["WTURIPROCESSOR"], $pagePath);
    }

    $multilingual = WTConfig::get("Multilingual");
    $pagePathArray = explode("/", $pagePath);
    if(count($pagePathArray) > 0) {
      // check for languages
      if(strlen($pagePathArray[0]) == 2) {
        if($multilingual == "Yes") {
          $q = Array();
          $q["Node Type"] = "wtLanguage";
          $q["Criteria"] = "Abbreviation = '" . mysql_escape_string($pagePathArray[0]) . "'";
          $q["Limit"] = "1";
          $languageGuid = $GLOBALS["WT"]->query($q, "singleValueCallback");
          $GLOBALS["WTLANGUAGEID"] = $languageGuid;

          $pagePath = "";
          $slash = "";
          for($i = 1; $i < count($pagePathArray); $i++) {
            $pagePath .= $slash . $pagePathArray[$i];
            $slash = "/";
          }
        }
      }

      if(WTSession::get("WTLANGUAGEID") != $GLOBALS["WTLANGUAGEID"]) {
        $languageCode = "";
        $languageID = WTSession::get("WTLANGUAGEID");
        if($languageID != 0) {
          $languageNode = $GLOBALS["WT"]->getNode($languageID);
          if($languageNode) {
            $languageCode = $languageNode->getAttribute("Abbreviation") . "/";
          }
        }

        $pagePath = $GLOBALS["WT"]->getWTValue("wt.site.base") . $languageCode . $pagePath;
        if($_SERVER["REDIRECT_QUERY_STRING"]) {
          $pagePath .= "?" . $_SERVER["REDIRECT_QUERY_STRING"];
        }

        header("Location: $pagePath");
        exit("");
      }
    }


    if($pagePath == "") {
      $defaultPage = $GLOBALS["WT"]->getNode("/Config/Settings/Site Details/Default Page");
      if($defaultPage != NULL) {
        $pagePath = $defaultPage->getAttribute("Value");
      }

      if(array_key_exists("WTDEFAULTPAGE", $GLOBALS)) {
        $pagePath = $GLOBALS["WTDEFAULTPAGE"];
      }

      if($pagePath == "") {
        $pagePath = "home";
      }
    }

    switch ($GLOBALS["WT"]->getSiteSetting("Path Mode")) {
      case 'rewrite':
        {


          if($GLOBALS["WTURIPERNODE"]) {
            $page = $GLOBALS["WT"]->getNodeFromURI($pagePath);
            if($page) {
              $active = $page->getAttribute("Active");
              if($active != "No" || $_SESSION["WTINOFFICE"]) {
                $pageGuid = $page->m_guid;
              }
            }
          } else {
            $language = $GLOBALS["WTLANGUAGEID"];
            $GLOBALS["WTLANGUAGEID"] = 0;

            $q = Array();
            if(array_key_exists("WTINOFFICE", $_SESSION) && $_SESSION["WTINOFFICE"]) {
              $q["Criteria"] = "URI = '" . mysql_real_escape_string($pagePath) . "'";
            } else {
              $q["Criteria"] = "URI = '" . mysql_real_escape_string($pagePath) . "' AND Active <> 'No'";
            }
            $q["Select"] = "Page.__guid";
            $q["Node Type"] = "Page";
            $q["Mode"] = "list";
            $q["Limit"] = 1;

            $pageGuid = $GLOBALS["WT"]->query($q, "singleValueCallback");
            $page = $GLOBALS["WT"]->getNode($pageGuid);

            $GLOBALS["WTLANGUAGEID"] = $language;
          }
          break;
        }
      case 'request_var':
        {
          $q = Array();
          $page = $GLOBALS["WT"]->getRequestValue('page');
          if ( $page == '' ) {
            $defaultPage = $GLOBALS["WT"]->getNode("/Config/Settings/Site Details/Default Page");
            if($defaultPage != NULL) {
              $page = $defaultPage->getAttribute("Value");
            }

            if($page == "") {
              $page = "home";
            }
          }
          $q["Criteria"] = "URI = '".$page."'";
          $q["Select"] = "Page.__guid";
          $q["Node Type"] = "Page";
          $pageGuid = $GLOBALS["WT"]->query($q, "singleValueCallback");
          $page = $GLOBALS["WT"]->getNode($pageGuid);

          break;
        }
      default:
        {
          $page = $GLOBALS["WT"]->getRequestValue("page");
          $pageGuid = $page->m_guid;
          break;
        }

    }

    $page = NULL;
    if($pageGuid != 0) {
      $page = $GLOBALS["WT"]->getNode($pageGuid);
    
      if($page != NULL) {
        if(!$page->userHasPermission("read")) {
    
          $page = $GLOBALS["WT"]->getNode("/Pages/Unstructured/Login");
          if($page == NULL) {
            $page = $GLOBALS["WT"]->getNode("/Pages/Special Pages/Login");
          }
          if($page == NULL) {
            $page = $GLOBALS["WT"]->getNode("/Pages/Special Pages/Login Required");
          }
        }
      }
    }

    if($page != NULL) {
      $html = $page->render();

 
/*
if($GLOBALS["WTSITEID"] == 11223 || $GLOBALS["WTSITEID"] == 11227 || $GLOBALS["WTSITEID"] == 11238 || $GLOBALS["WTSITEID"] == 11358) {
  if($page->getAttribute("Cache Page") == "Yes") {
    WTCache::cachePage($html);
  }
}
*/
      print $html;
      return true;
 // }
    } else {
      if($_SESSION["WTINOFFICE"]) {
        // check if its a page being moderated
        $currentMode = $GLOBALS["WT"]->getMode();
        $GLOBALS["WT"]->setMode("moderate");

        $language = $GLOBALS["WTLANGUAGEID"];
        $GLOBALS["WTLANGUAGEID"] = 0;

        $q = Array();

        $q["Criteria"] = "URI = '" . mysql_real_escape_string($pagePath) . "'";
        $q["Select"] = "Page.__guid";
        $q["Node Type"] = "Page";
        $q["Mode"] = "list";
        $q["Limit"] = 1;

        $pageGuid = $GLOBALS["WT"]->query($q, "singleValueCallback");

        $GLOBALS["WTLANGUAGEID"] = $language;
        $GLOBALS["WT"]->setMode($currentMode);

        if($pageGuid) {
          print "this page does not exist yet. it is waiting to be approved. you cannot view this page, however you can still add content by clicking the 'Edit' tab above'";
          exit("");
        }
      }
      return false;
    }
  }

};



function singleValueCallback($data, $args = NULL) 
{
  foreach($data as $name => $value) {
    return $value;
  }
}


function guidListCallback($data, $args = NULL) 
{
  if($args["Result Number"] != 0) {
    return "," . $data["__guid"];
  } else {
    return $data["__guid"];
  }
}


function renderCallback($data, $args = NULL) 
{
  $html = "";
  if($data != NULL) {
    if($args != NULL && array_key_exists("Results Array", $args)) {
      $args["Results Array"][] = $data;
    }

    if($args != NULL && array_key_exists("Result Number", $args)) {
      $data["__resultNumber"] = $args["Result Number"];
      $data["__totalResults"] = $args["Total Results"];
    }
    if($args != NULL && array_key_exists("Template Function", $args)) {
      if($GLOBALS["WT"]->m_currentPage != NULL) {
        if(!array_key_exists("id", $args)) {
          $args["id"] = $args["Template Function"];
        }
        $GLOBALS["WT"]->m_currentPage->preEvaluateTemplate($args["id"], $data, $args);
      }
      ob_start();
      $args["Template Function"]($data, $args);
      return ob_get_clean();
    } else if($args != NULL && array_key_exists("Template", $args)) {

      if($GLOBALS["WT"]->m_currentPage != NULL) {

        if(is_object($args["Template"])) {
          $GLOBALS["WT"]->m_currentPage->preEvaluateTemplate($args["Template"]->getPath(), $data, $args);
        }
      }
      if(is_object($args["Template"])) {
        return $args["Template"]->evaluate($data);
      }
    } else if($args != NULL && array_key_exists("Template Source", $args)) {
      $template = $args["Template Source"];
      return WTTemplate::compileAndEvaluate($template, $data);
    } else if($args != NULL && array_key_exists("Render As", $args)) {
      switch($args["Render As"]) {
        case "Checkbox":
          $checked = "";
          $checkedArray = Array();
          if($args != NULL && array_key_exists("Checked", $args)) {
            $checkedArray = explode(",", $args["Checked"]);
            $checkedArray = array_map("trim", $checkedArray);
          }
          if($GLOBALS["WT"]->getRequestValue("cb{$data["__guid"]}") == 1 || ($args != NULL && ($args["Checked"] == "all" || in_array($data["__name"], $checkedArray)))) {
            $checked = 'checked="checked"';
          }
          $html = '<input type="checkbox" name="cb' . $data["__guid"] . '" id="cb' . $data["__guid"] .'" value="1" ' . $checked . '><label for="cb' . $data["__guid"] . '">' . $data["__name"] .  '</label><br/>';

          return $html;
          break;
        case "Select Option":
          $selected = "";	 
          if($args != NULL && array_key_exists("Value", $args) && (int)$args["Value"] == $data["__guid"]) {
            $selected = 'selected="selected"';	   
          }	  
          $html = '<option value="' . $data["__guid"] . '" ' . $selected . '>' . $data["__name"] . '</option>';
          break;
      }
    } else {
      $html = '<table style="border-collapse: collapse">';
      foreach($data as $field => $value)
      {
        $html .= '<tr>';
        $html .= '<td style="border: 1px solid #999">';
        $html .= $field;
        $html .= '</td>';
        $html .= '<td style="border: 1px solid #999">';
        $html .= nl2br(htmlspecialchars($value));
        $html .= '</td>';
        $html .= '</tr>';
      }
      $html .= '</table>';
    }
  }
  return $html;
}


include_once($GLOBALS["WTDIRECTORY"] . "code/wtSession.php");

$GLOBALS["WT"] = new WebTemplate;

$GLOBALS["WT"]->registerURIHandler("__session", Array("WTSession", "processSessionURI"));


if(isset($_SESSION["WTUSERID"])) {
  if(array_key_exists("WTLOGGEDINAS", $_SESSION) && $_SESSION["WTLOGGEDINAS"]) {
    $GLOBALS["WT"]->setUser($_SESSION["WTLOGGEDINAS"], false);
  } else {
    $GLOBALS["WT"]->setUser("__admin", false);
  }
}

if(isset($_SESSION["WTUSERTYPE" . $GLOBALS["WTSITEID"]])) {
  $userType = $_SESSION["WTUSERTYPE" . $GLOBALS["WTSITEID"]];
  if($userType == "Administrator") {
    $GLOBALS["WT"]->setUser("__admin", false);
  } else if($userType == "Site Administrator") {
    $GLOBALS["WT"]->logout();
    $GLOBALS["WT"]->setUser("admin", false);
  }
}

  include_once($GLOBALS["WTDIRECTORY"] . "code/wtEvent.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtType.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtAttribute.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/extraControls.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtTemplate.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtPage.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtTags.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtFormatting.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtNewsletter.php");
  //if ( !defined('JETTTUPDATE') ) {

  include_once($GLOBALS["WTDIRECTORY"] . "code/wtFile.php");
  //}
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtContact.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtWidget.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtExtension.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtModule.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtMail.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtCategory.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtProduct.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtGroup.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtFreight.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtForm.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtCart.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtOrder.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtPayment.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtTransaction.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtConfig.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtProgress.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtCommunication.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtScheduler.php");
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtIndexer.php");

  if( $GLOBALS["WTSITEID"] == 11227 || $GLOBALS["WTSITEID"] == 11238 || $GLOBALS["WTSITEID"] == 11358) {
    include_once($GLOBALS["WTDIRECTORY"] . "code/wtCache.php");
  }
  
  include_once($GLOBALS["WTDIRECTORY"] . "code/wtMembership.php");


  $GLOBALS["WT"]->loadModules();

  
  if(!isset($GLOBALS["WTINCLUDESITECODE"]) || $GLOBALS["WTINCLUDESITECODE"]) {
  // include site specific files in the code dir
  $codeDir = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "code/";
  if(file_exists($codeDir)) {
    $d = dir($codeDir);
    while(false !== ($entry = $d->read())) {
      if(strpos($entry, ".php") == strlen($entry) - 4) {
        if($entry[0] != '.' && $entry != '#') {
          include_once($codeDir . $entry);
        }
      }
    }
    $d->close();
  }
  }

  $GLOBALS["WT"]->clearCache();




?>