API Docs for: WebTemplate API v2.0
Show:

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

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




$GLOBALS["WTMIMETYPES"] = Array(
  "ai" => "application/postscript",
  "aif" => "audio/x-aiff",
  "aifc" => "audio/x-aiff",
  "aiff" => "audio/x-aiff",
  "avi" => "video/x-msvideo",
  "bas" => "text/plain",
  "bin" => "application/octet-stream",
  "bmp" => "image/bmp",
  "c" => "text/plain",
  "csv" => "text/csv",
  "class" => "application/octet-stream",
  "css" => "text/css",
  "dll" => "application/x-msdownload",
  "doc" => "application/msword",
  "dot" => "application/msword",
  "eps" => "application/postscript",
  "exe" => "application/octet-stream",
  "gif" => "image/gif",
  "gtar" => "application/x-gtar",
  "gz" => "application/x-gzip",
  "htm" => "text/html",
  "html" => "text/html",
  "ico" => "image/x-icon",
  "jfif" => "image/pipeg",
  "jpe" => "image/jpeg",
  "jpeg" => "image/jpeg",
  "jpg" => "image/jpeg",
  "js" => "application/x-javascript",
  "latex" => "application/x-latex",
  "lha" => "application/octet-stream",
  "mov" => "video/quicktime",
  "movie" => "video/x-sgi-movie",
  "mp2" => "video/mpeg",
  "mp3" => "audio/mpeg",
  "mpa" => "video/mpeg",
  "mpe" => "video/mpeg",
  "mpeg" => "video/mpeg",
  "mpg" => "video/mpeg",
  "pbm" => "image/x-portable-bitmap",
  "pdf" => "application/pdf",
  "pot" => "application/vnd.ms-powerpoint",
  "png" => "image/png",
  "ppm" => "image/x-portable-pixmap",
  "pps" => "application/vnd.ms-powerpoint",
  "ppt" => "application/vnd.ms-powerpoint",
  "ps" => "application/postscript",
  "qt" => "video/quicktime",
  "snd" => "audio/basic",
  "swf" => "application/x-shockwave-flash",
  "tar" => "application/x-tar",
  "tgz" => "application/x-compressed",
  "tif" => "image/tiff",
  "tiff" => "image/tiff",
  "wav" => "audio/x-wav",
  "zip" => "application/zip",

   // office mime types
  "manifest" => "application/manifest",
  "xaml" => "application/xaml+xml", 
  "application" =>  "application/x-ms-application", 
  "deploy" => "application/octet-stream",
  "xbap" => "application/x-ms-xbap",
  "docm" => "application/vnd.ms-word.document.macroEnabled.12",
  "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "dotm" => "application/vnd.ms-word.template.macroEnabled.12",
  "dotx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
  "potm" => "application/vnd.ms-powerpoint.template.macroEnabled.12",
  "potx" => "application/vnd.openxmlformats-officedocument.presentationml.template",
  "ppam" => "application/vnd.ms-powerpoint.addin.macroEnabled.12",
  "ppsm" => "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
  "ppsx" => "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
  "pptm" => "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
  "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "xlam" => "application/vnd.ms-excel.addin.macroEnabled.12",
  "xlsb" => "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
  "xlsm" => "application/vnd.ms-excel.sheet.macroEnabled.12",
  "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  "xltm" => "application/vnd.ms-excel.template.macroEnabled.12",
  "xltx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.template"
);

class WTUpload 
{
  var $m_sessionKey;

  function WTUpload($sessionKey) 
  {
    $this->m_sessionKey = $sessionKey;
  } 


  function getUploadProgress() 
  {
    $sql = "SELECT 
              sessionBytes, sessionBytesUploaded
            FROM 
              dbWTFiles.tblSession
            WHERE
              sessionKey = '{$this->m_sessionKey}'";

    $query = mysql_query($sql);
    if($row = mysql_fetch_row($query)) {
      return Array("Total" => $row[0], "Uploaded" => $row[1]);
    }
    return Array("Total" => "0", "Uploaded" => "0");
  }

  function getFilename($fieldName) 
  {
    $sql = "SELECT
              sessionFilename
            FROM 
              dbWTFiles.tblSessionFile
            WHERE
              sessionKey = '{$this->m_sessionKey}'
              AND sessionFieldName = '$fieldName'";
    $query = mysql_query($sql);
    if($row = mysql_fetch_row($query)) {
      return $row[0];
    }
    return "";
  }

 

  function moveUploadedFile($fieldName, $filePath) 
  {
    $sql = "SELECT
              sessionTempFilename
            FROM
              dbWTFiles.tblSessionFile
            WHERE
              sessionKey = '{$this->m_sessionKey}'
              AND sessionFieldName = '$fieldName'";
    $query = mysql_query($sql);
    if($row = mysql_fetch_row($query)) {
      return rename($row[0], $filePath);
    }
    return false;
  }

  function clearSession() 
  {
    $sql = "SELECT
              sessionData 
            FROM
              dbWTFiles.tblSession
            WHERE
              sessionKey = '{$this->m_sessionKey}'";
    $query = mysql_query($sql);
    if($row = mysql_fetch_array($query)) {
      if(trim($row[0]) != "" && file_exists($row[0])) {
        unlink($row[0]);
      }
    }
    $sql = "SELECT
              sessionTempFilename
            FROM
              dbWTFiles.tblSessionFile
            WHERE
              sessionKey = '{$this->m_sessionKey}'";
    $query = mysql_query($sql);
    while($row = mysql_fetch_array($query)) {
      if(trim($row[0]) != "" && file_exists($row[0])) {
        unlink($row[0]);
      }
    }
    $sql = "DELETE FROM
              dbWTFiles.tblSession 
            WHERE 
              sessionKey = '{$this->m_sessionKey}'";
    mysql_query($sql);
    print mysql_error();

    $sql = "DELETE FROM
              dbWTFiles.tblSessionFile
            WHERE
              sessionKey = '{$this->m_sessionKey}'";
    mysql_query($sql);
    print mysql_error();
  }

}

/**
 *  The class representing wtFile Nodes
 *
 *  @class WTFile
 *  @extends WTNode
 */

class WTFile extends WTNode 
{

  /**
   *  Update a file
   *
   *  @method updateFile
   *  @param {Array} attributes An associative array of the new attributes of the file, should contain the key "Field Name" which is the name of the File upload control
   *
   */
  function updateFile($attributes) {
    if(array_key_exists("Form Field", $attributes)) {
      $formField = $attributes["Form Field"];
      $sessionID = $attributes["Session ID"];
      $wtUpload = new WTUpload($sessionID);
      $filename = $wtUpload->getFilename($formField);
      if($filename != "") {
        $pathParts = pathinfo($filename);
        $extension = strtolower($pathParts["extension"]);
        $fileType = "File";
        $attributes["File Name"] = $filename;
        $attributes["File Size"] = $filesize;
        $attributes["Extension"] = $extension;

        $protected = $this->getAttribute("Protected");

        if($protected == "Yes") {
          $filesDirectory = $GLOBALS["WTSITEPROTECTEDDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";
        } else {
          $filesDirectory = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";
        }

        $currentFile = $filesDirectory . $this->getFilename();

 
        $this->setAttributes($attributes);

        if($protected == "Yes") {
          $filePath = $GLOBALS["WTSITEPROTECTEDDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $this->m_guid . ".$extension";
        } else {
          $filePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $this->m_guid . ".$extension";
        }
        $this->clearCache();

        if(file_exists($currentFile)) {
          unlink($currentFile);
        }

        $wtUpload->moveUploadedFile($formField, $filePath);
        $wtUpload->clearSession();

        $filesize = filesize($filePath);

        $width = 0;
        $height = 0;
        if($extension == "jpg" || $extension == "gif" || $extension == "png" || $extension == "jpeg") {
          $fileType = "Image";
          $size = GetImageSize("$filePath");
          if($size) {
            $width = $size[0];
            $height = $size[1];
          }
        }

        $this->setAttributes(Array("File Size" => $filesize, "Width" => $width, "Height" => $height, "File Type" => $fileType));

      }
    } else if(array_key_exists("Field Name", $attributes)) {

      $fileField = $attributes["Field Name"];
      if(array_key_exists($fileField, $_FILES) && $_FILES[$fileField]['name'] != "") {

        $filename = $_FILES[$fileField]['name'];
        $pathParts = pathinfo($filename);
        $extension = strtolower($pathParts["extension"]);

        if(array_key_exists("Allowed Extensions", $attributes)) {
          $allowedExtensions = explode(",", $attributes["Allowed Extensions"]);
          $allowedExtensions = array_map("trim", $allowedExtensions);
          if(!in_array($extension, $allowedExtensions)) {
            return NULL;
          }
        }

        if(!array_key_exists("Title", $attributes)) {
          $attributes["Title"] = $filename;
        }
        $attributes["File Name"] = $filename;
        $attributes["Extension"] = $extension;


/*
        $fileNode = parent::create($parentGuid, $nodeType, $attributes);

        if(array_key_exists("Protected", $attributes) && $attributes["Protected"] == "Yes") {
          $wtFilePath = $GLOBALS["WTSITEPROTECTEDDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $fileNode->m_guid . ".$extension";
        } else {
          $wtFilePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $fileNode->m_guid . ".$extension";
        }

*/

        $currentFile = $filesDirectory . $this->getFilename();


        $this->setAttributes($attributes);

        if(WTConfig::get("Content Manager/Use Filename for Images") == "Yes") {
          $attributes["File Name"] = wtFile::stripInvalidChars($attributes["File Name"]);
          $filename = $attributes["File Name"];
          $fileFolder = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $this->m_guid;
          if(!file_exists($fileFolder)) {
            mkdir($fileFolder);
          }
          $wtFilePath = $fileFolder . "/" . $filename;
        } else {

          if($protected == "Yes") {
            $wtFilePath = $GLOBALS["WTSITEPROTECTEDDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $this->m_guid . ".$extension";
          } else {
            $wtFilePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $this->m_guid . ".$extension";
          }

        }

       
        $this->clearCache();

        if(file_exists($currentFile)) {
          unlink($currentFile);
        }

        move_uploaded_file($_FILES[$fileField]['tmp_name'], $wtFilePath);


        $filesize = filesize($wtFilePath);

        $width = 0;
        $height = 0;
        if($extension == "jpg" || $extension == "gif" || $extension == "png" || $extension == "jpeg") {
          $fileType = "Image";
          $size = GetImageSize("$wtFilePath");
          if($size) {
            $width = $size[0];
            $height = $size[1];
          }

/*
          if(array_key_exists("Max Width", $attributes) && $width > $attributes["Max Width"] ) {
            $newWidth = $attributes["Max Width"];
            $newHeight = round($height * $newWidth / $width);
            exec("convert -resize {$newWidth}x{$newHeight} $wtFilePath $wtFilePath");

            $size = GetImageSize("$wtFilePath");
            if($size) {
              $width = $size[0];
              $height = $size[1];
            }

          }
*/

        }


        $this->setAttributes(Array("File Size" => $filesize, "Width" => $width, "Height" => $height, "File Type" => $fileType));
      }


    }
  }

  public static function &create($parentGuid, $nodeType, $attributes) {
    if(array_key_exists("Form Field", $attributes)) {

      $formField = $attributes["Form Field"];
      $sessionID = $attributes["Session ID"];
      $wtUpload = new WTUpload($sessionID);
//      $filename = $_FILES[$formField]["name"];
      $filename = $wtUpload->getFilename($formField);
      
      if($filename != "") {
//        $filesize = filesize($_FILES[$formField]["tmp_name"]);
        $pathParts = pathinfo($filename);
        $extension = strtolower($pathParts["extension"]);
        $fileType = "File";
        if(!array_key_exists("Title", $attributes)) {
          $attributes["Title"] = $filename;          
        }
        $attributes["File Name"] = $filename;
        $attributes["File Size"] = $filesize;
        $attributes["Extension"] = $extension;
    
        $fileNode = parent::create($parentGuid, $nodeType, $attributes);
//        $filePath = $GLOBALS["WTSITEDIRECTORY"] . "/files/" . $fileNode->m_guid . ".$extension";       

        $filePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $fileNode->m_guid . ".$extension";
        $wtUpload->moveUploadedFile($formField, $filePath);
        $wtUpload->clearSession();
//        move_uploaded_file($_FILES[$formField]["tmp_name"], $filePath);
        $filesize = filesize($filePath);

        $width = 0;
        $height = 0;
        if($extension == "jpg" || $extension == "gif" || $extension == "png" || $extension == "jpeg") {
          $fileType = "Image";
          $size = GetImageSize("$filePath");
          if($size) {
            $width = $size[0];
            $height = $size[1];
          }
        }

        $fileNode->setAttributes(Array("File Size" => $filesize, "Width" => $width, "Height" => $height, "File Type" => $fileType));
        return $fileNode;
      }
    } else if(array_key_exists("File Path", $attributes)) {
      $filePath = $attributes["File Path"];
      $pathParts = pathinfo($filePath);
      $filename = $pathParts["basename"];
      $extension = strtolower($pathParts["extension"]);
      if(!array_key_exists("Title", $attributes)) {
        $attributes["Title"] = $filename;
      }
      $attributes["File Name"] = $filename;
      $attributes["Extension"] = $extension;
      $fileNode = parent::create($parentGuid, $nodeType, $attributes);

      $wtFilePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $fileNode->m_guid . ".$extension";
	  	  
      copy($filePath, $wtFilePath);
      $filesize = filesize($wtFilePath);

      $width = 0;
      $height = 0;
      if($extension == "jpg" || $extension == "gif" || $extension == "png" || $extension == "jpeg" || $extension == "bmp") {
        $fileType = "Image";
        $size = GetImageSize("$filePath");
        if($size) {
          $width = $size[0];
          $height = $size[1];
        }
      }

      $fileNode->setAttributes(Array("File Size" => $filesize, "Width" => $width, "Height" => $height, "File Type" => $fileType));
      return $fileNode;
    } else if(array_key_exists("Field Name", $attributes)) {

      $fileField = $attributes["Field Name"];
      if(array_key_exists($fileField, $_FILES) && $_FILES[$fileField]['name'] != "") {

        $filename = $_FILES[$fileField]['name'];
        $pathParts = pathinfo($filename);
        $extension = strtolower($pathParts["extension"]);

        if(array_key_exists("Allowed Extensions", $attributes)) {
          $allowedExtensions = explode(",", $attributes["Allowed Extensions"]);
          $allowedExtensions = array_map("trim", $allowedExtensions);
          if(!in_array($extension, $allowedExtensions)) {
            return NULL;
          }
        }

        if(!array_key_exists("Title", $attributes)) {
          $attributes["Title"] = $filename;
        }
        $attributes["File Name"] = $filename;
        $attributes["Extension"] = $extension;
        $fileNode = parent::create($parentGuid, $nodeType, $attributes);

        if(WTConfig::get("Content Manager/Use Filename for Images") == "Yes") {
          $attributes["File Name"] = wtFile::stripInvalidChars($attributes["File Name"]);
          $filename = $attributes["File Name"];
          $fileFolder = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $fileNode->m_guid;
          if(!file_exists($fileFolder)) {
            mkdir($fileFolder);
          }
          $wtFilePath = $fileFolder . "/" . $filename;
        } else {

          if(array_key_exists("Protected", $attributes) && $attributes["Protected"] == "Yes") {
            $wtFilePath = $GLOBALS["WTSITEPROTECTEDDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $fileNode->m_guid . ".$extension";
          } else {
            $wtFilePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $fileNode->m_guid . ".$extension";
          }
        }

        move_uploaded_file($_FILES[$fileField]['tmp_name'], $wtFilePath);

        $filesize = filesize($wtFilePath);

        $width = 0;
        $height = 0;
        if($extension == "jpg" || $extension == "gif" || $extension == "png" || $extension == "jpeg") {
          $fileType = "Image";
          $size = GetImageSize("$wtFilePath");
          if($size) {
            $width = $size[0];
            $height = $size[1];
          }

          if(array_key_exists("Max Width", $attributes) && $width > $attributes["Max Width"] ) {
            $newWidth = $attributes["Max Width"];
            $newHeight = round($height * $newWidth / $width);
            exec("convert -resize {$newWidth}x{$newHeight} $wtFilePath $wtFilePath");

            $size = GetImageSize("$wtFilePath");
            if($size) {
              $width = $size[0];
              $height = $size[1];
            }
            
           
          }
        }

        
        $fileNode->setAttributes(Array("File Size" => $filesize, "Width" => $width, "Height" => $height, "File Type" => $fileType));
        return $fileNode;        
      }
    }

    return NULL;
  }

  static function stripInvalidChars($filename) {
    $badChars = array_merge(
        array_map('chr', range(0,31)),
        array("<", ">", ":", ";", '"', "/", "\\", "|", "?", "*", "[", "]", "=", "+", "#", "@", "&", "%", "(", ")"));
    $filename = str_replace($badChars, "", $filename);
    $filename = str_replace(" ", "_", $filename);
    $dotpos = strrpos($filename, ".");
    if($dotpos) {
      $extension = substr($filename, $dotpos + 1);
      $name = substr($filename, 0, $dotpos);
      $filename = $name . "." . strtolower($extension);
    }
    return $filename;

  }
  function setAttributes($attributes, $log = true, $saveAsDraft = false) {
    if(WTConfig::get("Content Manager/Use Filename for Images") == "Yes") {
      $oldFilename = $this->getAttribute("File Name");
      if(array_key_exists("File Name", $attributes)) {
        $newFilename = wtFile::stripInvalidChars($attributes["File Name"]);
        $attributes["File Name"] = $newFilename;
        if($newFilename != $oldFilename) {
          $filesDirectory = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";
          $originalFile = $filesDirectory . $this->m_guid . "/" . $oldFilename;
          $newFile = $filesDirectory . $this->m_guid . "/" . $newFilename;
          if(file_exists($originalFile)) {
            rename($originalFile, $newFile);  
          }
        }
        $this->clearCache();

/*
 $retVal = parent::setAttributes($attributes, $log, $saveAsDraft);
print "move $originalFile to $newFile";
exit();
*/
      }
    }
    $retVal = parent::setAttributes($attributes, $log, $saveAsDraft);
    return $retVal;
  }

  function deleteNode($forceDelete = false) 
  {
    $extension = $this->getAttribute("Extension");
    $fileName = "{$this->m_guid}.$extension";
//    $filesDirectory = $GLOBALS["WTSITEDIRECTORY"] . "/files/";

    $filesDirectory = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";

    if(file_exists($filesDirectory . $fileName)) {
      unlink($filesDirectory . $fileName);
    }

    if(WTConfig::get("Content Manager/Use Filename for Images") == "Yes") {

      $fileName = $this->m_guid . "/" . $this->getAttribute("File Name");
      $filesDirectory = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";

      if(file_exists($filesDirectory . $fileName)) {
        unlink($filesDirectory . $fileName);
      }
    }


    $sql = "SELECT
              fileName
            FROM
              tblImageCache 
            WHERE
              fileGuid = {$this->m_guid}";
    $query = mysql_query($sql);
   
    while($row = mysql_fetch_array($query)) {
      if(file_exists($filesDirectory . $row[0])) {
        unlink($filesDirectory . $row[0]);
      }
    }
    parent::deleteNode($forceDelete);
  }


  /**
   *  Return the url of the icon for a file based on its extension
   *
   *  @method getIconURL
   *  @param {int} [size=16] The size of the icon to return: 16, 32, 48
   *  @return {String} The url of the icon
   */
  function getIconURL($size = 16) 
  {
    $extension = $this->getAttribute("Extension");
    if(!file_exists($GLOBALS["WTDIRECTORY"] . "include/images/doctypes/$size")) {
      return false;
    }

    $includeurl = $GLOBALS["WTINCLUDEURL"];
 
    if(array_key_exists("HTTPS", $_SERVER)) {
      $includeurl = $GLOBALS["WTSECUREINCLUDEURL"];

    } 

    if(file_exists($GLOBALS["WTDIRECTORY"] . "include/images/doctypes/$size/_$extension.gif")) {
      return $includeurl . "images/doctypes/$size/_$extension.gif";
    } else {
      return $includeurl . "images/doctypes/$size/_blank.gif";
    }
  }

  /**
   *  Return the filename to use when displaying or linking to a file on a website
   *
   *  @method getFilename
   *  @param {Array} [args] Options for the file. Possible keys are "width", "height", "watermark"
   *  @return {String} The filename of the file which meets the criteria in the optional arguments
   */
  function getFilename($args = NULL) 
  {
    $width = -1;
    $height = -1;
    if($args != NULL && array_key_exists("width", $args)) {
      $width = $args["width"];
    }
    if($args != NULL && array_key_exists("height", $args)) {
      $height = $args["height"];
    }

    $extension = $this->getAttribute("Extension");
    $originalWidth = $this->getAttribute("Width");
    $originalHeight = $this->getAttribute("Height");
    $protected = $this->getAttribute("Protected");
    $watermark = "";

    if($args) {
      if(array_key_exists("watermark", $args)) {
        $watermark = $args["watermark"];
      }
    }

    
    $filename = $this->getAttribute("File Name");
    if(WTConfig::get("Content Manager/Use Filename for Images") == "Yes") {
      $filesDirectory = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";
      $originalFile = $this->m_guid . "/" . $filename;
      if(!file_exists($filesDirectory . $originalFile)) {
        if(!file_exists($filesDirectory . $this->m_guid)) {
          mkdir($filesDirectory . $this->m_guid);
        }
        rename($filesDirectory .  $this->m_guid . "." . $extension, $filesDirectory . $originalFile);
 //         print "move " . $filesDirectory .  $this->m_guid . "." . $extension . " " .  $filesDirectory . $originalFile;
//	  exit();
        
      }
    } else {
      $originalFile = $this->m_guid . "." . $extension;
    }

    if($width == -1 && $height == -1) {
      return $originalFile;
    } 
    
//    $filesDirectory = $GLOBALS["WTSITEDIRECTORY"] . "/files/";
    $protectedFilesDirectory = $GLOBALS["WTSITEPROTECTEDDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";
    
    $filesDirectory = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";
    
    $newWidth = $originalWidth;
    $newHeight = $originalHeight;

    if($width > 0 && $height <= 0 && $width < $originalWidth) {
      $newWidth = $width;
      $newHeight = round($originalHeight * $newWidth / $originalWidth);
    } else if($width <= 0 && $height > 0 && $height < $originalHeight) {
      $newHeight = $height;
      $newWidth = round($originalWidth * $newHeight / $originalHeight);
      
    } else if($width > 0 && $height > 0 && ($width < $originalWidth || $height < $originalHeight) ) {
      if($originalWidth / $originalHeight > $width / $height) { 
        $newWidth = $width;
        $newHeight = round($originalHeight * $newWidth / $originalWidth);
      } else {
        $newHeight = $height;
        $newWidth = round($originalWidth * $newHeight / $originalHeight);
      }
    } else {
    }

    if($newWidth == $originalWidth && $newHeight == $originalHeight && $watermark == "") {
      return $originalFile;
    } else {
      if($GLOBALS["WTSITEID"] == 11473 || $GLOBALS["WTSITEID"] == 11588) {
        if($extension == "gif") {
          $extension = "png";
        }
      }
    


      if(WTConfig::get("Content Manager/Use Filename for Images") == "Yes") {
        $newFileDirectory = $this->m_guid;
        if(!file_exists($filesDirectory . $newFileDirectory)) {
          mkdir($filesDirectory . $newFileDirectory);
        }
        $newFileDirectory .= "/{$newWidth}x{$newHeight}";
        $newFilename = $newFileDirectory . "/" . $filename;

        if(!file_exists($filesDirectory . $newFileDirectory)) {
          mkdir($filesDirectory . $newFileDirectory);
        }
      } else {
        $newFilename = "{$this->m_guid}-{$newWidth}x{$newHeight}.$extension";
      }
      $fileProperties = "-resize {$newWidth}x{$newHeight}";
      $convertParameters =  $fileProperties;


      $watermarkFilePath = "";
      if($watermark != "") {
        $watermarkFile = $GLOBALS["WT"]->getNode($watermark);
        if($watermarkFile) {
          $watermarkGuid = $watermarkFile->m_guid;
          $newFilename = "{$this->m_guid}-{$newWidth}x{$newHeight}-w$watermarkGuid.$extension";
          $watermarkFilePath = $filesDirectory . $watermarkFile->m_guid . "." . $watermarkFile->getAttribute("Extension");
          $fileProperties = "-resize {$newWidth}x{$newHeight} -watermark $watermarkGuid";
        }
      } 

$filetext = "";
      $sql = "SELECT 
                fileName
              FROM
                tblImageCache
              WHERE 
                fileGuid = {$this->m_guid}
                AND fileProperties = '" . mysql_escape_string($fileProperties) . "'";
      $query = mysql_query($sql);
      if($row = mysql_fetch_row($query)) {
$filetext = $filesDirectory . $row[0];
        if(file_exists($filesDirectory . $row[0])) {
          return $row[0];
        }
      }
      
      if($protected == "Yes") {
        exec("convert $convertParameters {$protectedFilesDirectory}{$originalFile} {$filesDirectory}$newFilename");
        if($watermarkFilePath != "") {
          WTFile::addWatermark($filesDirectory . $newFilename, $watermarkFilePath);
        } else if($newWidth > 200 || $newHeight > 200) {
          WTFile::addWatermark($filesDirectory . $newFilename, "/data/www/webtemplate/bridgehead/Xpose2008/watermark.png");
        }

      } else {

        exec("convert $convertParameters " . escapeshellarg($filesDirectory . $originalFile) . " " . escapeshellarg($filesDirectory . $newFilename) );
        if($watermarkFilePath != "") {
          WTFile::addWatermark($filesDirectory . $newFilename, $watermarkFilePath);
        }
      }
      $sql = "INSERT INTO
                tblImageCache (fileGuid, fileName, fileProperties)
              VALUES 
                ({$this->m_guid}, '" . mysql_escape_string($newFilename) . "', '" . mysql_escape_string($fileProperties) . "')";
      if(!mysql_query($sql)) {
        print $sql;
        print mysql_error();
      }                
     
         if(WTConfig::get("Content Manager/Use Filename for Images") == "Yes") {

/*
print "filetext = $filetext<br>";
print "convert $convertParameters " . escapeshellarg($filesDirectory . $originalFile) . " " . escapeshellarg($filesDirectory . $newFilename) ;
exit();
*/
         }
 
      return $newFilename;
    }
  }

  function addWatermark($srcFile, $watermarkFile) {
    exec("composite -gravity center $watermarkFile $srcFile $srcFile");
    return;

/*
    $filetype = substr($srcFile,strlen($srcFile)-4,4);
    $filetype = strtolower($filetype);
    if($filetype == ".gif")  $image = imagecreatefromgif($srcFile);
    if($filetype == ".jpg" || $filetype == "jpeg")  $image = imagecreatefromjpeg($srcFile);
    if($filetype == ".png")  $image = imagecreatefrompng($srcFile);
    if (!$image) return;

    $watermarkfiletype = substr($watermarkFile,strlen($watermarkFile)-4,4);
    $watermarkfiletype = strtolower($watermarkfiletype);
    if($watermarkfiletype == ".gif")  $watermark = imagecreatefromgif($watermarkFile);
    if($watermarkfiletype == ".jpg")  $watermark = imagecreatefromjpeg($watermarkFile);
    if($watermarkfiletype == ".png")  $watermark = imagecreatefrompng($watermarkFile);

//    $watermark = imagecreatefrompng($watermarkFile);

    if(!$watermark) {
      return;
    }
    $imagewidth = imagesx($image);
    $imageheight = imagesy($image);
    $watermarkwidth =  imagesx($watermark);
    $watermarkheight =  imagesy($watermark);
    $startwidth = (($imagewidth - $watermarkwidth)/2);
    $startheight = (($imageheight - $watermarkheight)/2);
    imagecopy($image, $watermark,  $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
    if($filetype == ".gif") {
      imagegif($image, $srcFile);
    } else if($filetype == ".jpg" || $filetype == "jpeg") {
      imagejpeg($image, $srcFile);
    } else {
      imagepng($image, $srcFile);
    }
    imagedestroy($image);
    imagedestroy($watermark);
*/
  }

  /**
   * Clear the cache of the different sizes of an image file 
   * 
   *  @method clearCache
   *
   */
  function clearCache() {
    $filesPath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/";

    $sql = "SELECT
              fileName,
	      imageCacheID
            FROM
              tblImageCache
            WHERE
              fileGuid = {$this->m_guid}";

    $query = mysql_query($sql);
    while($row = mysql_fetch_row($query)) {
       $filePath = $filesPath . $row[0];
       if(file_exists($filePath)) {
         unlink($filePath);
       }

       // if using actual filenames, delete those files

       $location = "ic";
       $actualFilename = $this->getAttribute("File Name");
       $cachedDir = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "__files/$location/" .  $row[1];

       $dh = @opendir($cachedDir);
       if($dh) {
         while (false !== ($obj = readdir($dh))) 
         { 
           if($obj == '.' || $obj == '..') 
           { 
             continue; 
           }
           unlink($cachedDir . "/" . $obj); 

         } 

         closedir($dh); 
    
         rmdir($cachedDir); 
       }
    }

    $sql = "DELETE FROM
              tblImageCache
            WHERE
              fileGuid = {$this->m_guid}";
    mysql_query($sql);
  }


  /**
   *  Output the contents of a file. This function can read larger files than readfile
   *
   *  @method readfileChunked
   *  @method static
   *  @param {String} filepath The full path to the file
   *  @return {int} The number of bytes in the file
   */
  function readfileChunked($filename,$retbytes=true) {
    $chunksize = 1*(1024*1024); // how many bytes per chunk
    $buffer = '';
    $cnt =0;
   
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
      return false;
    }
   
    while (!feof($handle)) {
      $buffer = fread($handle, $chunksize);
      echo $buffer;
      ob_flush();
      flush();
      if ($retbytes) {
        $cnt += strlen($buffer);
      }
    }

    $status = fclose($handle);
    if ($retbytes && $status) {
      return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
  }


  /**
   *  Output a file
   *
   *  @method output
   *
   */

  function output($originalName = "") 
  {


    $filename = $this->getFilename();
    if($originalName == "") {
      $originalName = $filename;
    }
    $filePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $filename;

    if(file_exists($filePath)) {
      $extension = "";
      $pos = strrpos($filePath, ".");
      if($pos !== false) {
        $extension = substr($filePath, $pos + 1);
      }
      $mimeType = WTFile::getMimeType($extension);


      header("Pragma: public");
      header("Expires: 0"); // set expiration time
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

      header("Content-Type: $mimeType");
      header("Content-Transfer-Encoding: binary"); 
      //header("Content-Disposition: attachment; filename=\"" . $originalName . "\"");
      header("Content-Length: " . filesize($filePath));
      //readfile($filePath);
      WTFile::readfileChunked($filePath);
    }
  }



  /**
   *  Get the mime type of a file based on its extension
   *
   *  @method getMimeType
   *  @param {String} extension The extension to get the mime type for
   *  @param {String} [default="application/octet-stream"] The mime type to return if non is found
   *  @return {String} The MIME type
   *
   */
  static function getMimeType($extension, $default = "application/octet-stream") 
  { 
    $extension = strtolower($extension);
    if(array_key_exists($extension, $GLOBALS["WTMIMETYPES"])) {
      return $GLOBALS["WTMIMETYPES"][$extension];
    }
    return $default;
  }
  

  /**
   *  Process a URI beginning with __file and output the appropriate file
   *
   *  @method processFileURI
   *  @param {String} path A path beginning with __file
   */
  function processFileURI($path) 
  {


    $pathParts = explode("/", $path);
    $siteDirectory = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory");

    if($pathParts > 3) { 
      if($pathParts[1] == "purchase") {
        $key = $pathParts[2];
        $orderItemID = $pathParts[3];
        if(is_numeric($orderItemID)) {
          $orderItem = $GLOBALS["WT"]->getNode($orderItemID);
          $orderItemKey = $orderItem->getAttribute("Key");
          if($orderItemKey == $key) {
            $productID = $orderItem->getAttribute("Product ID");
            $product = $GLOBALS["WT"]->getNode($productID);
            if($product) {
              $fileID = $product->getAttribute("Image");
              $file = $GLOBALS["WT"]->getNode($fileID);
              if($file) {
                $filename = $file->getFilename();
                if($file->getAttribute("Protected") == "Yes") {
                  $filepath = $GLOBALS["WTSITEPROTECTEDDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $filename;
                } else {
                  $filepath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $filename; 
                }
                if(file_exists($filepath)) {
                  $extension = "";
                  $pos = strrpos($filepath, ".");
                  if($pos !== false) {
                    $extension = substr($filepath, $pos + 1);
                  }
      
                  header("Content-Type: " . WTFile::getMimeType($extension));
                  readfile($filepath);
                  exit("");
                }
              }
            }
          }
        }
        header("Content-Type: text/html");
        print "The file you have tried to download does not exist. Please contact the site administrator";
        exit("");
      } else if($pathParts[1] == 'i') {

 
        if(!file_exists($siteDirectory . "__files")) {
          mkdir($siteDirectory . "__files");
        }       
        if(!file_exists($siteDirectory . "__files/i")) {
          mkdir($siteDirectory . "__files/i");
        }
        $fileGuid = $pathParts[2];
        if(is_numeric($fileGuid)) {
          $file = $GLOBALS["WT"]->getNode($fileGuid);
          if($file) {
            $file->output($pathParts[3]);
          }
        }
        exit("");
      } else if($pathParts[1] == 'ic') {
        if(!file_exists($siteDirectory . "__files")) {   
          mkdir($siteDirectory . "__files");
        }       
        if(!file_exists($siteDirectory . "__files/ic")) {
          mkdir($siteDirectory . "__files/ic");
        }

        $imageCacheID = $pathParts[2];    
        if(is_numeric($imageCacheID)) {
          $sql = "SELECT
                    fileName
                  FROM
                    tblImageCache
                  WHERE
                    imageCacheID = $imageCacheID";     
          $query = mysql_query($sql);

          if($row = mysql_fetch_row($query)) {
	    $pos = strpos($row[0], "?");
	    if($pos !==false) {
              $row[0] = substr($row[0], $pos);
            }
            $filePath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $row[0];
            if(file_exists($filePath)) {


              if(!file_exists($siteDirectory . "__files/ic/$imageCacheID")) {
                mkdir($siteDirectory . "__files/ic/$imageCacheID");
              }
              copy($filePath, $siteDirectory . $path);

              $extension = "";
              $pos = strrpos($filePath, ".");
              if($pos !== false) {
                $extension = substr($filePath, $pos + 1);
              }
              $mimeType = WTFile::getMimeType($extension);

/*
              header("Pragma: public");
              header("Expires: 0"); // set expiration time
              header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

              header("Content-Type: $mimeType");
              header("Content-Transfer-Encoding: binary");
              header("Content-Length: " . filesize($filePath));

*/
              header("Content-Type: $mimeType");

              print WTFile::readfileChunked($filePath);
//                readfile($filePath);
            }
          } 

        }
        exit("");
      } else {



        $fileGuid = $pathParts[2];

        if(is_numeric($fileGuid)) {
          $file = $GLOBALS["WT"]->getNode($fileGuid);
          $contactGuid = $GLOBALS["WT"]->m_contactGuid;
          $ipAddress = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]);
          if($file && $ipAddress != '203.122.244.244') {
              $sql = "INSERT INTO tblFileDownload (
                        fileGuid,
                        contactGuid, 
                        fileDownloadDate,
                        fileDownloadIPAddress
                      ) VALUES (
                        $fileGuid,
                        $contactGuid,
                        NOW(),
                        '$ipAddress'
                      )";
              mysql_query($sql);
            }

//            $filename = $file->getFilename();
//            $filepath = $GLOBALS["WTSITEDIRECTORY"] . $GLOBALS["WT"]->getSiteSetting("Site Directory") . "files/" . $filename;

            if($file && $file->userHasPermission("read") ) {

 
              $file->output($pathParts[3]);
              exit("");
            } else {
              $GLOBALS["WT"]->output404();
	    }

/*            if(file_exists($filepath)) {
              $mimetype = WTFile::getMimeType($filepath); 
              header("Content-Type: text/plain");
              readfile($filepath);
              exit("");
            }
exit("");
*/
        //  }
        }
        exit("");
      }
      
    }
  }
}

$GLOBALS["WT"]->registerURIHandler("__files", Array("WTFile", "processFileURI"));
?>