Your IP : 216.73.216.163


Current Path : /home/user/web/pansionat-v-yaroslavle.ru/public_html/331ab/
Upload File :
Current File : /home/user/web/pansionat-v-yaroslavle.ru/public_html/331ab/ImageUploaderPHP.tar

Package.class.php000064400000011332150242777670007735 0ustar00<?php

require_once 'UploadCache.class.php';
require_once 'UploadedFile.class.php';

class Package {

  private $_uploadedFiles = NULL;
  private $_packageIndex = NULL;
  private $_uploadSession = NULL;
  private $_completed = false;
  private $_cached = false;
  private $_packageFields = NULL;
  private $_packageFiles = NULL;

  /**
   * Package constructor
   * @param UploadSession $uploadSession
   * @param int $index
   * @param array $post
   * @param array $files
   */
  function __construct($uploadSession, $index, $saveIntoCache = false) {
    if (empty($uploadSession)) {
      throw new Exception('Upload session can not be null');
    }

    $post = $uploadSession->getRequestFields();
    $files = $uploadSession->getRequestFiles();

    $this->_uploadSession = $uploadSession;
    $this->_packageIndex = $index;
    
    $uploadSessionId = $uploadSession->getUploadSessionId();

    if ($index < $post[PostFields::packageIndex]) {
      // This is previous package we save for AllPackages event
      $this->_completed = true;
      $this->_cached = true;
    } else if ($index == $post[PostFields::packageIndex]) {
      // this package is current package
      $this->_completed = @!empty($post[PostFields::packageComplete]);
      $cache = $this->_uploadSession->getUploadCache();
      $this->_cached = $cache->isPackageCached($uploadSessionId, $this->_packageIndex);

      // If package completed, but already cached then it is last chunk of the package
      // and we also need to save it.
      if (!$this->_completed || $this->_cached || $saveIntoCache) {
        $cache->saveRequestData($uploadSessionId, $this->_packageIndex, $post, $files);
        $this->_cached = true;
      } else {
        $this->_packageFields = $post;
        $this->_packageFiles = $files;
      }
    } else {
      throw new Exception('Incorrect $index value or POST fields.');
    }
  }

  private function loadSavedFields() {
    $uploadSessionId = $this->_uploadSession->getUploadSessionId();
    $cache = $this->_uploadSession->getUploadCache();
    $this->_packageFields = $cache->loadSavedFields($uploadSessionId, $this->_packageIndex);
  }

  private function loadSavedFiles() {
    $uploadSessionId = $this->_uploadSession->getUploadSessionId();
    $cache = $this->_uploadSession->getUploadCache();
    $this->_packageFiles = $cache->loadSavedFiles($uploadSessionId, $this->_packageIndex);
  }

  /**
   * Get package field value by field name
   * @param string $fieldName
   */
  public function getPackageField($fieldName) {
    $fields = $this->getPackageFields();
    $value = @$fields[$fieldName];
    return isset($value) ? $value : NULL;
  }

  /**
   * @return boolean Returns true if package received completely, otherwise returns false.
   */
  public function getCompleted() {
    return $this->_completed;
  }
  
  public function getCached() {
  	return $this->_cached;
  }

  /**
   * Get all package fields
   * @return array
   */
  public function getPackageFields() {
    if (empty($this->_packageFields)) {
      $this->loadSavedFields();
    }
    return $this->_packageFields;
  }

  /**
   * Get total package count for upload session
   */
  public function getPackageCount() {
    return $this->getPackageField(PostFields::packageCount);
  }

  /**
   * Get count of files selected to upload in this package
   */
  public function getPackageFileCount() {
    return $this->getPackageField(PostFields::packageFileCount);
  }

  /**
   * Get unique identificator for upload session
   */
  public function getPackageGuid() {
    return $this->getPackageField(PostFields::packageGuid);
  }

  /**
   * Get packahe index
   */
  public function getPackageIndex() {
    return $this->_packageIndex;
  }

  /**
   * Get uploaded files
   * @return array Array of UploadedFile objects
   */
  public function getUploadedFiles() {
    // Can not get files from incomplete package
    if (!$this->_completed) {
      return NULL;
    }
    if (!is_array($this->_uploadedFiles)) {
      $this->getUploadedFilesInternal();
    }
    return $this->_uploadedFiles;
  }

  private function getUploadedFilesInternal() {
    $this->_uploadedFiles = array();
    $count = $this->getPackageField(PostFields::packageFileCount);
    if ($count > 0) {
      if (!is_array($this->_packageFiles)) {
        if ($this->_cached) {
          $this->loadSavedFiles();
        } else {
          throw new Exception('Package claims to be non-cached, but packageFiles property is NULL');
        }
      }
      for ($i = 0; $i < $count; $i++) {
        $this->_uploadedFiles[] = new UploadedFile($this, $i, $this->_packageFiles);
      }
    }
  }
}UploadCache.class.php000064400000013721150242777670010556 0ustar00<?php

class UploadCache {

  private $_cacheRoot;

  /**
   * UploadCache constructor
   * @param UploadSession $uploadSession
   */
  function __construct($cacheRoot) {
    if (!empty($cacheRoot)) {
      $cacheRoot = rtrim($cacheRoot, '/\\');
    }

    if (empty($cacheRoot)) {
      throw new Exception('Cache root directory can not be null.');
    }

    $this->_cacheRoot = $cacheRoot;
  }

  /**
   * Get default root upload cache directory.
   */
  public function getCacheRoot() {
    return $this->_cacheRoot;
  }

  public static function moveFile($source, $destination) {
    $result = @rename($source, $destination);
    if (!$result) {
      // copy-remove otherwise
      $result = copy($source, $destination);
      unlink($source);
    }
    return $result;
  }

  public function getLastFullScanTimestamp() {
    $file = $this->getCacheRoot().DIRECTORY_SEPARATOR.'timestamp';
    $timestamp = 0;
    if (is_file($file)) {
      $timestamp = file_get_contents($file);
      $timestamp = @intval($timestamp, 10);
    }
    return $timestamp;
  }

  public function setLastFullScanTimestamp($value = NULL) {
    $file = $this->getCacheRoot().DIRECTORY_SEPARATOR.'timestamp';
    if ($value === NULL) {
      $value = time();
    }
    file_put_contents($file, $value);
  }

  /**
   * Check if package exists in the cache
   * @param $package
   */
  public function isPackageCached($uploadSessionId, $packageIndex) {
    return file_exists($this->getPackageCacheDirectory($uploadSessionId, $packageIndex));
  }

  public function loadSavedFields($uploadSessionId, $packageIndex) {
    $filePath = $this->getPackageCacheDirectory($uploadSessionId, $packageIndex) . DIRECTORY_SEPARATOR . 'post';
    return unserialize(file_get_contents($filePath));
  }

  public function loadSavedFiles($uploadSessionId, $packageIndex) {
    $path = $this->getPackageCacheDirectory($uploadSessionId, $packageIndex) . DIRECTORY_SEPARATOR;
    $items = scandir($path);
    $rg = '#^File\\d+_\\d+$#';
    $files = array();
    foreach ($items as $file) {
      if (preg_match($rg, $file)) {
        $files[$file] = array(
          'cached' => true,
          'tmp_name' => $path . $file,
          'type' => 'application/octet-stream',
          'error' => UPLOAD_ERR_OK,
          'size' => filesize($path . $file)
        );
      }
    }
    return $files;
  }

  /**
   * Save package fields and files into upload temp cache
   * @param Package $package
   */
  public function saveRequestData($uploadSessionId, $packageIndex, $fields, $files) {
    $path = $this->getPackageCacheDirectory($uploadSessionId, $packageIndex);

    if (!file_exists($path)) {
      mkdir($path, 0777, true);
    }

    $this->saveFields($path, $fields);
    $this->saveFiles($path, $files, $fields);

    $this->setWriteTimestamp($uploadSessionId);
  }

  private function saveFields($path, $fields) {
    $filePath = $path . DIRECTORY_SEPARATOR . 'post';
    if (file_exists($filePath)) {
      $data = file_get_contents($filePath);
      $data = unserialize($data);
    }
    if (isset($data)) {
      $fields = array_merge($data, $fields);
    }
    file_put_contents($path . DIRECTORY_SEPARATOR . 'post', serialize($fields));
  }

  private function saveFiles($path, $files, $fields) {
    foreach ($files as $key => $file) {
      $filePath = $path . DIRECTORY_SEPARATOR . $key;

      if (isset($file['in_request']) && $file['in_request'] === true) {
        $data = $fields[$key];
        $fdst = fopen($filePath, 'a');
        fwrite($fdst, $data);
        fclose($fdst);
      } else {
        if (is_uploaded_file($file['tmp_name']) && !file_exists($filePath)) {
          move_uploaded_file($file['tmp_name'], $filePath);
        } else {
          $this->appendToFile($file['tmp_name'], $filePath);
        }
      }
    }
  }

  private function appendToFile($source, $destination) {
    $buff = 4096;
    $fsrc = fopen($source, 'r');
    $fdst = fopen($destination, 'a');
    while (($data = fread($fsrc, $buff)) !== '') {
      fwrite($fdst, $data);
    }
    fclose($fsrc);
    fclose($fdst);
  }

  public function getSessionCacheDirectory($uploadSessionId) {
    return $this->getCacheRoot() . DIRECTORY_SEPARATOR . $uploadSessionId;
  }

  public function getPackageCacheDirectory($uploadSessionId, $packageIndex) {
    return $this->getSessionCacheDirectory($uploadSessionId) . DIRECTORY_SEPARATOR . $packageIndex;
  }

  private function setWriteTimestamp($uploadSessionId, $time = NULL) {
    if ($time === NULL) {
      $time = time();
    }
    file_put_contents($this->getSessionCacheDirectory($uploadSessionId).DIRECTORY_SEPARATOR.'timestamp', $time);
  }

  public function getWriteTimestamp($uploadSessionId) {
    $timestampFile = $this->getSessionCacheDirectory($uploadSessionId).DIRECTORY_SEPARATOR.'timestamp';
    $timestamp = -1;
    if (is_file($timestampFile)) {
      $timestamp = file_get_contents($timestampFile);
      $timestamp = @intval($timestamp, 10);
    }

    if ($timestamp <= 0) {
      // If no timestamp file then set current time
      $timestamp = time();
      $this->setWriteTimestamp($uploadSessionId, $timestamp);
    }

    return $timestamp;
  }

  public function cleanUploadSessionCache($uploadSessionId) {
    $dir = $this->getSessionCacheDirectory($uploadSessionId);
    if (!empty($dir) && file_exists($dir)) {
      UploadCache::rmdir_recursive($dir);
    }
  }

  private static function rmdir_recursive($dir) {
    if (is_dir($dir)) {
      $objects = scandir($dir);
      foreach ($objects as $object) {
        if ($object != '.' && $object != '..') {
          if (is_dir($dir.DIRECTORY_SEPARATOR.$object)) {
            UploadCache::rmdir_recursive($dir.DIRECTORY_SEPARATOR.$object);
          } else {
            unlink($dir.DIRECTORY_SEPARATOR.$object);
          }
        }
      }
      reset($objects);
      rmdir($dir);
    }
  }
}PostFields.class.php000064400000002707150242777670010464 0ustar00<?php
class PostFields {
  // package fields
  const packageIndex = 'PackageIndex';
  const packageCount = 'PackageCount';
  const packageGuid = 'PackageGuid';
  const packageFileCount = 'PackageFileCount';
  
  // source file fields
  const sourceName = 'SourceName_%d';
  const sourceSize = 'SourceSize_%d';
  const sourceCreatedDateTime = 'SourceCreatedDateTime_%d';
  const sourceLastModifiedDateTime = 'SourceLastModifiedDateTime_%d';
  const sourceCreatedDateTimeLocal = 'SourceCreatedDateTimeLocal_%d';
  const sourceLastModifiedDateTimeLocal = 'SourceLastModifiedDateTimeLocal_%d';
  const sourceWidth = 'SourceWidth_%d';
  const sourceHeight = 'SourceHeight_%d';
  const horizontalResolution = 'HorizontalResolution_%d';
  const verticalResolution = 'VerticalResolution_%d';
  
  // crop bounds
  const cropBounds = 'CropBounds_%d';
  
  // converted file fields
  const file = 'File%d_%d';
  const fileMode = 'File%dMode_%d';
  const fileName = 'File%dName_%d';
  const fileSize = 'File%dSize_%d';
  const fileWidth = 'File%dWidth_%d';
  const fileHeight = 'File%dHeight_%d';
  
  // other fields
  const angle = 'Angle_%d';
  const description = 'Description_%d';
  const tag = 'Tag_%d';
  
  // chunk fields
  const fileChunkCount = 'File%dChunkCount_%d';
  const fileChunkIndex = 'File%dChunkIndex_%d';
  
  // complete markers
  const requestComplete = 'RequestComplete';
  const packageComplete = 'PackageComplete';
  
}UploadHandler.class.php000064400000015466150242777670011140 0ustar00<?php

require_once 'UploadSession.class.php';

// sys_get_temp_dir function exists in PHP 5 >= 5.2.1
if ( !function_exists('sys_get_temp_dir')) {
  function sys_get_temp_dir() {
    if ($temp = ini_get('upload_tmp_dir')) {
      return $temp;
    }
    if ($temp = getenv('TMP')) {
      return $temp;
    }
    if ($temp = getenv('TEMP')) {
      return $temp;
    }
    if ($temp = getenv('TMPDIR')){
      return $temp;
    }
    $temp = tempnam(dirname(__FILE__), '');
    if (file_exists($temp)) {
      unlink($temp);
      return dirname($temp);
    }
    return null;
  }
}

/**
 * Handle upload requests from uploader.
 */
class UploadHandler {

  private static $_processed = false;

  private $_fileUploadedCallback = NULL;
  private $_allFilesUploadedCallback = NULL;

  private $_destination;
  private $_cacheAliveTimeout = 1800; // 30 minutes
  private $_cacheRoot;

  function __construct() {
    // set default cache directory
    $tempDir = rtrim(sys_get_temp_dir(), '/\\');
    $this->_cacheRoot = $tempDir . DIRECTORY_SEPARATOR . 'uploader_c2215afa418f4cc2bc2c0f92746882f0';
  }

  /**
   * Add file uploaded callback function. Function will be called for every uploaded file.
   * @param callback $callback
   */
  public function setFileUploadedCallback($callback) {
    $this->_fileUploadedCallback = $callback;
  }

  public function getFileUploadedCallback() {
    return $this->_fileUploadedCallback;
  }

  public function setAllFilesUploadedCallback($callback) {
    $this->_allFilesUploadedCallback = $callback;
  }

  public function getAllFilesUploadedCallback() {
    return $this->_allFilesUploadedCallback;
  }

  /**
   * Get upload cache expire timeout.
   */
  public function getCacheAliveTimeout() {
    return $this->_cacheAliveTimeout;
  }

  /**
   * Set upload cache expire timeout.
   * After timeout expires all files for this upload session will be removed.
   * @param int $value Timeout in seconds
   */
  public function setCacheAliveTimeout($value) {
    $this->_cacheAliveTimeout = $value;
  }

  /**
   * Get temp directory for uploaded files
   */
  public function getUploadCacheDirectory() {
    return $this->_cacheRoot;
  }

  /**
   * Set temp directory for uploaded files
   * @param string $value
   */
  public function setUploadCacheDirectory($value) {
    $this->_cacheRoot = $value;
  }

  public function processRequest() {
    // Ignore other requests except POST.
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST[PostFields::packageGuid])) {
      return;
    }

    if (UploadHandler::$_processed) {
      return;
    }

    UploadHandler::$_processed = true;

    if (array_key_exists('HTTP_X_PREPROCESS_REQUIRED', $_SERVER) && $_SERVER['HTTP_X_PREPROCESS_REQUIRED'] == 'true') {
      $files = $this->getRequestFiles($_POST);
    } else {
      $files = &$_FILES;
    }
    $uploadCache = new UploadCache($this->_cacheRoot);

    $uploadSession = new UploadSession($uploadCache, $_POST, $files, $_SERVER);

    if (!empty($this->_allFilesUploadedCallback)) {
      $uploadSession->setAllFilesUploadedCallback($this->_allFilesUploadedCallback);
    }

    if (!empty($this->_fileUploadedCallback)) {
      $uploadSession->setFileUploadedCallback($this->_fileUploadedCallback);
    }
    $uploadSession->processRequest();
    $this->removeExpiredSessions($uploadCache);

    // Flash requires non-empty response
    if (!headers_sent() && array_key_exists('HTTP_USER_AGENT', $_SERVER) && $_SERVER['HTTP_USER_AGENT'] === 'Shockwave Flash') {
      echo '0';
    }
  }

  /**
   * Image Uploader Flash upload files as ordinary field with binary data.
   * So it is placed in the $_POST and not in $_FILES
   */
  private function getRequestFiles($post) {
    $files = array();
    for ($i = 0; $i < 3; $i++) {
      $fileField = sprintf(PostFields::file, $i, 0);
      $fileNameField = sprintf(PostFields::fileName, $i, 0);
      $fileSizeField = sprintf(PostFields::fileSize, $i, 0);

      if (array_key_exists($fileField, $post) && isset($post[$fileField])) {
        $files[$fileField] = array(
          'name' => $post[$fileNameField],
          'in_request' => true,
          'size' => intval($post[$fileSizeField], 10)
        );
      }
    }

    return $files;
  }

  /**
   * Remove expired upload sessions
   */
  private function removeExpiredSessions($uploadCache) {
    $cacheRoot = $uploadCache->getCacheRoot();
    if (empty($cacheRoot) || !is_dir($cacheRoot)) {
      return;
    }

    $cacheRoot = rtrim($cacheRoot, '/\\');

    $lastFullScan = $uploadCache->getLastFullScanTimestamp();
    $currentTimestamp = time();

    // Do not scan all cache too often
    if ($lastFullScan + $this->_cacheAliveTimeout / 2 > $currentTimestamp) {
      return;
    }

    $dirs = scandir($cacheRoot);
    foreach ($dirs as $dir) {
      if ($dir != '.' && $dir != '..' && is_dir($cacheRoot . DIRECTORY_SEPARATOR . $dir)) {
        $uploadCache = new UploadCache($cacheRoot);
        $uploadSessionId = $dir;
        if ($uploadCache->getWriteTimestamp($uploadSessionId) + $this->_cacheAliveTimeout < $currentTimestamp) {
          $uploadCache->cleanUploadSessionCache($uploadSessionId);
        }
      }
    }

    $uploadCache->setLastFullScanTimestamp($currentTimestamp);
  }

  public function saveFiles($destination) {
    if (empty($destination)) {
      return;
    }
    rtrim($destination, '/\\');
    $this->_destination = $destination;

    $this->setFileUploadedCallback(array($this, 'saveUploadedFileCallback'));
    $this->processRequest();
  }

  /**
   * Save uploaded file callback
   * @param UploadedFile $uploadedFile
   */
  public function saveUploadedFileCallback($uploadedFile) {
    if (empty($this->_destination)) {
      return;
    }
    /* @var $uploadedFile UploadedFile */
    $relativePath = $uploadedFile->getRelativePath();
    if (empty($relativePath)) {
      $basePath = $this->_destination;
    } else {
      $relativePath = trim($relativePath, '/\\');
      $relativePath = preg_replace('#\\/#', DIRECTORY_SEPARATOR, $relativePath);
      $basePath = $this->_destination . DIRECTORY_SEPARATOR . $relativePath;
    }
    if (!is_dir($basePath)) {
      mkdir($basePath, 0777, true);
    }
    $basePath .= DIRECTORY_SEPARATOR;
    foreach ($uploadedFile->getConvertedFiles() as $convertedFile) {
      /* @var $convertedFile ConvertedFile */
      $name = $convertedFile->getName();
      $path_info = pathinfo($name);
      $i = 2;
      $fullFilePath = $basePath . $name;
      while (file_exists($fullFilePath)) {
        $fullFilePath = $basePath . $path_info['filename'] . '_' . $i . '.' . $path_info['extension'];
        $i++;
      }
      $convertedFile->moveTo($fullFilePath);
    }
  }
}UploadSession.class.php000064400000011521150242777670011172 0ustar00<?php

require_once 'PostFields.class.php';
require_once 'UploadCache.class.php';
require_once 'Package.class.php';

class UploadSession {

  private $_post = NULL;
  private $_files = NULL;
  private $_server = NULL;
  private $_uploadCache = NULL;

  private $_fileUploadedCallback = NULL;
  private $_allFilesUploadedCallback = NULL;

  function __construct($uploadCache, $post = NULL, $files = NULL, $server = NULL) {
    if (empty($uploadCache)) {
       throw new Exception('Upload cache can not be null.');
    }

    $this->_uploadCache = $uploadCache;

    $this->_post = $post === NULL ? $_POST : $post;
    $this->_files = $files === NULL ? $_FILES : $files;
    $this->_server = $server === NULL ? $_SERVER : $server;
  }

  public function processRequest() {

    if (!$this->validateRequest()) {
      return NULL;
    }

    // copy file names from files array to post array
    $this->addFileNames($this->_post, $this->_files);

    $packageIndex = intval($this->_post[PostFields::packageIndex], 10);
    $packageCount = intval($this->_post[PostFields::packageCount], 10);
    // If AllFilesUploaded callback set, then we need to cache package in any case.
    // No need to save last package into cache.
    $saveIntoCache = !empty($this->_allFilesUploadedCallback) && $packageCount > 1 && $packageIndex != $packageCount - 1;
    $package = new Package($this, $packageIndex, $saveIntoCache);
    if ($package->getCompleted()) {

      if (!empty($this->_fileUploadedCallback)) {
        foreach ($package->getUploadedFiles() as $uploadedFile) {
          call_user_func($this->_fileUploadedCallback, $uploadedFile);
        }
      }

      if (!empty($this->_allFilesUploadedCallback)) {
      
        // Is it last package?
        if ($packageCount - 1 == $packageIndex) {
          $allUploadedFiles = array();
          for ($i = 0; $i < $packageCount - 1; $i++) {
            $p = new Package($this, $i);
            $allUploadedFiles = array_merge($allUploadedFiles, $p->getUploadedFiles());
          }
          $allUploadedFiles = array_merge($allUploadedFiles, $package->getUploadedFiles());
          call_user_func($this->_allFilesUploadedCallback, $allUploadedFiles);
        }
      }
      // remove temp files
      if (!empty($this->_uploadCache) && (empty($this->_allFilesUploadedCallback) || $packageCount - 1 == $packageIndex)) {
        $this->getUploadCache()->cleanUploadSessionCache($this->getUploadSessionId());
      }
    }
  }

  private function addFileNames(&$fields, &$files) {
    $rg = '/^File(\d+)_(\d+)$/i';
    foreach ($files as $key => $file) {
      $mathes = null;
      if (preg_match($rg, $key, $mathes)) {
        $converterIndex = $mathes[1];
        $fileIndex = $mathes[2];
        $fileNameField = sprintf(PostFields::fileName, $converterIndex, $fileIndex);
        if (!isset($fields[$fileNameField])) {
          @$chunkIndex = $fields[sprintf(PostFields::fileChunkIndex, $converterIndex, $fileIndex)];
          if (empty($chunkIndex)) {
            $fields[$fileNameField] = $file['name'];
          }
        }
      }
    }
  }

  public function setFileUploadedCallback($callback) {
    $this->_fileUploadedCallback = $callback;
  }

  public function setAllFilesUploadedCallback($callback) {
    $this->_allFilesUploadedCallback = $callback;
  }

  public function getFileUploadedCallback() {
    return $this->_fileUploadedCallback;
  }

  public function getAllFilesUploadedCallback() {
    return $this->_allFilesUploadedCallback;
  }

  public function getRequestFields() {
    return $this->_post;
  }

  public function getRequestFiles() {
    return $this->_files;
  }

  public function getUploadSessionId() {
    return $this->_post[PostFields::packageGuid];
  }

  /**
   * Get upload cache object for upload session.
   * @return UploadCache
   */
  public function getUploadCache() {
    return $this->_uploadCache;
  }

  private function validateRequest() {
    if (empty($this->_server) || empty($this->_post) || $this->_server['REQUEST_METHOD'] !== 'POST') {
      return false;
    }

    // Every request have PackageGuid field
    if (empty($this->_post[PostFields::packageGuid])) {
      // If not - it is not image uploader request, ignore it.
      return false;
    } else if (!preg_match("/^\\{[a-z0-9-]+\\}$/i", $this->_post[PostFields::packageGuid])) {
        throw new Exception('Upload '.PostFields::packageGuid.' is invalid.');
    }

    // check if request completed
    if (@$this->_post[PostFields::requestComplete] != 1) {
      throw new Exception('Upload request is invalid.');
    }

    if (!isset($this->_post[PostFields::packageIndex]) || !isset($this->_post[PostFields::packageCount])) {
          throw new Exception('Upload request is invalid.');
    }

    return true;
  }

}ConvertedFile.class.php000064400000007731150242777670011143 0ustar00<?php

require_once 'UploadCache.class.php';

class ConvertedFile {

  private $_uploadedFile;
  private $_convertedFileIndex;
  private $_uploadedFileIndex;
  private $_file;
  private $_size;
  private $_type; // bitrix

  /**
   * ConvertedFile constructor
   * @param UploadedFile $uploadedFile
   * @param int $index
   * @param array $file
   */
  function __construct($uploadedFile, $index, $file) {
  
    if (empty($uploadedFile)) {
      throw new Exception('$uploadedFile parameter can not be empty');
    }

    if (empty($file)) {
    throw new Exception('$file parameter can not be empty');
    }
    $this->_convertedFileIndex = $index;

    $this->_uploadedFile = $uploadedFile;
    $this->_uploadedFileIndex = $uploadedFile->getIndex();
    $this->_file = $file;

    $expectedSize = $this->_uploadedFile->getPackage()->getPackageField(sprintf(PostFields::fileSize,
    $this->_convertedFileIndex, $this->_uploadedFileIndex));

    if ($expectedSize < 2*1024*1024*1024) {
      $actualSize = $this->_file['size'];
      if ($expectedSize != $actualSize) {
        throw new Exception('File is corrupted');
      }
    }

    $this->_size = intval($expectedSize, 10);
    $this->_type = $file['type'];
  }

  /**
   * Get height of converted file
   */
  public function getHeight() {
    return $this->_uploadedFile->getPackage()->getPackageField(sprintf(PostFields::fileHeight,
    $this->_convertedFileIndex, $this->_uploadedFileIndex));
  }

  /**
   * Get converter mode applied to the uploaded file
   */
  public function getMode() {
    return $this->_uploadedFile->getPackage()->getPackageField(sprintf(PostFields::fileMode,
    $this->_convertedFileIndex, $this->_uploadedFileIndex));
  }

  /**
   * Get converted file name
   */
  public function getName() {
    return $this->_uploadedFile->getPackage()->getPackageField(sprintf(PostFields::fileName,
    $this->_convertedFileIndex, $this->_uploadedFileIndex));
  }

  /**
   * Get converted file size
   * @return int
   */
  public function getSize() {
    return $this->_size;
  }
  
  /**
   * Get converted file size
   * @return int
   */
  public function getType() {
    return $this->_type;
  }

  /**
   * Get converted file width
   */
  public function getWidth() {
    return $this->_uploadedFile->getPackage()->getPackageField(sprintf(PostFields::fileWidth,
    $this->_convertedFileIndex, $this->_uploadedFileIndex));
  }

  /**
   * Get content of converted file into string
   * @return string
   */
  public function getFileContent() {
    if (isset($this->_file['in_request']) && $this->_file['in_request'] == true) {
      return $this->_uploadedFile->getPackage()->getPackageField(sprintf(PostFields::file, $this->_convertedFileIndex, $this->_uploadedFileIndex));
    } else {
      return file_get_contents($this->_file['tmp_name']);
    }
  }

  /**
   * Move converted file to a new location
   * @param $destination The destination of the moved file
   */
  public function moveTo($destination) {

    if (isset($this->_file['in_request']) && $this->_file['in_request'] == true) {
      $data = $this->_uploadedFile->getPackage()->getPackageField(sprintf(PostFields::file,
      $this->_convertedFileIndex, $this->_uploadedFileIndex));
      $handle = fopen($destination, 'w');
      $result = fwrite($handle, $data);
      if ($result !== FALSE) {
        // no error
        $result = TRUE;
      }
      $result &= fclose($handle);
    } else {
      $path = $this->_file['tmp_name'];
      if (is_uploaded_file($path)) {
        $result = move_uploaded_file($path, $destination);
      } else if ($this->_file['cached']) {
        $result = UploadCache::moveFile($path, $destination);
      } else {
        throw new Exception('File is not "is_uploaded_file" and is not cached file');
      }
    }
    if (!$result) {
      throw new Exception("Unable to move file \"$path\" to \"$destination\"");
    }
  }
}UploadedFile.class.php000064400000007763150242777670010754 0ustar00<?php

require_once 'ConvertedFile.class.php';

class UploadedFile {

  private $_package;
  private $_index;
  private $_packageFiles;
  private $_convertedFiles = NULL;

  /**
   * UploadedFile constructor
   * @param Package $package
   * @param int $index
   */
  function __construct($package, $index, $packageFiles) {
    if ($package == NULL) {
      throw new Exception('$package parameter can not be null');
    }
    if (@!is_numeric($index)) {
      throw new Exception('$index parameter should be a number');
    }
    if (@!is_array($packageFiles)) {
      throw new Exception('$packageFiles parameter should be an array');
    }
    $this->_package = $package;
    $this->_index = $index;
    $this->_packageFiles = $packageFiles;
  }

  private function initFileArray() {
    $rg = '/^File(\d+)_' . $this->_index . '$/i';
    $this->_convertedFiles = array();
    foreach ($this->_packageFiles as $key => $file) {
      $mathes = null;
      if (preg_match($rg, $key, $mathes)) {
        $converterIndex = $mathes[1];
        $this->_convertedFiles[$converterIndex] = new ConvertedFile($this, $converterIndex, $file);
      }
    }
  }
  
  public function getAngle() {
    return $this->_package->getPackageField(sprintf(PostFields::angle, $this->_index));
  }

  public function getConvertedFiles() {
    if (!is_array($this->_convertedFiles)) {
      $this->initFileArray();
    }
    return $this->_convertedFiles;
  }
  
  public function getCropBounds() {
    return $this->_package->getPackageField(sprintf(PostFields::cropBounds, $this->_index));
  }

  public function getDescription() {
    return $this->_package->getPackageField(sprintf(PostFields::description, $this->_index));
  }

  public function getIndex() {
    return $this->_index;
  }

  /**
   * Get package
   * @return Package
   */
  public function getPackage() {
    return  $this->_package;
  }

  public function getRelativePath() {
    $name = $this->_package->getPackageField(sprintf(PostFields::sourceName, $this->_index));
    if (empty($name)) {
      return NULL;
    } else {
      $dir = dirname($name);
      if (empty($dir) || $dir == '.') {
        return NULL;
      } else {
        return $dir;
      }
    }
  }

  public function getSourceCreatedDateTime() {
    return $this->_package->getPackageField(sprintf(PostFields::sourceCreatedDateTime, $this->_index));
  }

  public function getSourceCreatedDateTimeLocal() {
    return $this->_package->getPackageField(sprintf(PostFields::sourceCreatedDateTimeLocal, $this->_index));
  }

  public function getSourceHeight() {
    return $this->_package->getPackageField(sprintf(PostFields::sourceHeight, $this->_index));
  }

  public function getSourceLastModifiedDateTime() {
    return $this->_package->getPackageField(sprintf(PostFields::sourceLastModifiedDateTime, $this->_index));
  }

  public function getSourceLastModifiedDateTimeLocal() {
    return $this->_package->getPackageField(sprintf(PostFields::sourceLastModifiedDateTimeLocal, $this->_index));
  }

  public function getSourceName() {
    $name = $this->_package->getPackageField(sprintf(PostFields::sourceName, $this->_index));
    if (empty($name)) {
      return $name;
    } else {
      return basename($name);
    }
  }

  public function getSourceSize() {
    return $this->_package->getPackageField(sprintf(PostFields::sourceSize, $this->_index));
  }

  public function getSourceWidth() {
    return $this->_package->getPackageField(sprintf(PostFields::sourceWidth, $this->_index));
  }

  public function getHorizontalResolution() {
    return $this->_package->getPackageField(sprintf(PostFields::horizontalResolution, $this->_index));
  }

  public function getVerticalResolution() {
    return $this->_package->getPackageField(sprintf(PostFields::verticalResolution, $this->_index));
  }

  public function getTag() {
    return $this->_package->getPackageField(sprintf(PostFields::tag, $this->_index));
  }
}Utils.class.php000064400000005676150242777670007520 0ustar00<?php

define('SESSION_PARAM_NAME', 'PHP_SESSIONID');

final class Utils
{
  public static function getPhpLibraryDirectory() {
    $basePath = dirname($_SERVER['SCRIPT_FILENAME']);
    $basePath = str_replace('\\', '/', $basePath);

    $path = str_replace('\\', '/', dirname( __FILE__ ));

    $basePath = explode('/', $basePath);
    $path = explode('/', $path);
    while (count($basePath) > 0 && count($path) > 0 && $basePath[0] == $path[0]) {
      array_shift($basePath);
      array_shift($path);
    }

    while (count($basePath) > 0) {
      array_shift($basePath);
      array_unshift($path, '..');
    }

    $path = implode('/', $path);
    return $path;
  }

  public static function getDefaultScriptDirectory() {
    return self::getPhpLibraryDirectory() . '/Scripts';
  }

  public static function getRelativePath($path){

    if (array_key_exists('DOCUMENT_ROOT', $_SERVER)) {
      $docRoot = str_replace("\\", "/", $_SERVER['DOCUMENT_ROOT']);
    } elseif (array_key_exists('SCRIPT_NAME', $_SERVER) && array_key_exists('SCRIPT_FILENAME', $_SERVER)) {
      $scriptName = $_SERVER['SCRIPT_NAME'];
      $scriptFileName = str_replace("\\", "/", $_SERVER['SCRIPT_FILENAME']);
      $pos = strrpos($scriptFileName, $scriptName);
      if ($pos == strlen($scriptFileName) - strlen($scriptName)) {
        $docRoot = substr($scriptFileName, 0, $pos);
      }
    }

    if ($docRoot) {
      return str_replace($docRoot, '', str_replace("\\", "/", realpath($path)));
    }
    else {
      return $path;
    }

  }

  public static function throwException($message) {
    header('HTTP/1.0 500 Internal Server Error');
    throw new Exception($message);
  }

  /**
   * Recursive directory removal
   * @param $dir directoru path
   * @return bool True if directory was removed, otherwise false
   */
  public static function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir) || is_link($dir)) return unlink($dir);
    foreach (scandir($dir) as $item) {
      if ($item == '.' || $item == '..') continue;
      if (!self::deleteDirectory($dir . "/" . $item)) {
        chmod($dir . "/" . $item, 0777);
        if (!self::deleteDirectory($dir . "/" . $item)) return false;
      };
    }
    return rmdir($dir);
  }

  /**
   * Fix for the Flash Player Cookie bug in Non-IE browsers. Call this before session_start() function.
   * @return bool TRUE if session was restored.
   */
  public static function restoreSession() {
    /* Since Flash Player always sends the IE cookies even in FireFox
     * we have to bypass the cookies by sending the values as part of the POST
     * and overwrite the cookies with the passed in values.
     */
    $sessionId = $_POST[SESSION_PARAM_NAME];
    if ($sessionId) {
      // place right cookie with session id
      $_COOKIE[session_name()] = $sessionId;
      return TRUE;
    } else {
      return FALSE;
    }
  }

}