Beispiel #1
0
 public function testGetFileName()
 {
     $resource = fopen('php://memory', 'r+');
     fwrite($resource, 'foobar');
     rewind($resource);
     $file = new FileStream($resource, 'foo.txt', 'text/plain');
     $this->assertEquals('foo.txt', $file->getFileName());
     $this->assertEquals('text/plain', $file->getContentType());
     $file = new FileStream($resource, 'foo.txt');
     $this->assertEquals('foo.txt', $file->getFileName());
     $this->assertEquals(null, $file->getContentType());
 }
 public function test_fileNameFromHeader()
 {
     $fs = FileStream::fromHttp(dirname(__FILE__));
     $fs->headerCallback(null, "Content-Disposition: attachment; filename='test.doc'");
     $expected = "test.doc";
     $this->assertEquals($expected, $fs->getFileName());
 }
Beispiel #3
0
 public function testRead()
 {
     $stream = new FileStream(dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . 'data');
     $this->assertEquals('1', $stream->getBuffer()->read(8));
     $stream->skip(16);
     $this->assertEquals('a', $stream->getBuffer()->read(8));
     $stream->skip(8);
     $this->assertEquals('c', $stream->getBuffer()->read(8));
     $this->assertEquals('d', $stream->getBuffer()->read(8));
 }
Beispiel #4
0
         } else {
             throw new Exception($uploadResult->error_message);
         }
     } catch (Exception $e) {
         $error = 'ERROR: ' . $e->getMessage() . "\n";
         F3::set('error', $error);
     }
 }
 //Check is user choose upload local file
 if ($_FILES['file']["name"] != "") {
     //Temp name of the file
     $tmpName = $file['tmp_name'];
     //Original name of the file
     $name = $file['name'];
     //Creat file stream
     $fs = FileStream::fromFile($tmpName);
     //###Make a request to Storage API using clientId
     //Upload file to current user storage
     try {
         $uploadResult = $storageApi->Upload($clientId, $name, 'uploaded', "", 0, $fs);
         //###Check if file uploaded successfully
         if ($uploadResult->status == "Ok") {
             //Get file GUID
             $fileGuId = $uploadResult->result->guid;
             $fileId = "";
             //If it isn't uploaded throw exception to template
         } else {
             throw new Exception($uploadResult->error_message);
         }
     } catch (Exception $e) {
         $error = 'ERROR: ' . $e->getMessage() . "\n";
 /**
  * 
  * @param string $path
  * @param array $params
  */
 public function __construct($path, $params = null)
 {
     parent::__construct($path, $params);
     $this->append = isset($params[self::PARAM_APPEND]) ? $params[self::PARAM_APPEND] : false;
 }
Beispiel #6
0
 $storageApi->setBasePath($basePath);
 $docApi->setBasePath($basePath);
 //###Make a request to Doc API using clientId and file id
 //Obtaining all Metadata for file
 try {
     $docInfo = $docApi->GetDocumentMetadata($clientId, $fileId);
     //Selecting file names
     if ($docInfo->status == "Ok") {
         //Obtaining file name for entered file Id
         $name = $docInfo->result->last_view->document->name;
     } else {
         throw new Exception($docInfo->error_message);
     }
     //###Make a request to Storage Api for dowloading file
     //Obtaining file stream of downloading file and definition of folder where to download file
     $outFileStream = FileStream::fromHttp(dirname(__FILE__) . '/../temp', $name);
     //Downlaoding of file
     try {
         $file = $storageApi->GetFile($clientId, $fileId, $outFileStream);
         if ($file->downloadDirectory != "" && isset($file)) {
             //If request was successfull - set message variable for template
             $message = '<font color="green">File was downloaded to the <font color="blue">' . $outFileStream->downloadDirectory . '</font> folder</font> <br />';
             F3::set('message', $message);
         } else {
             throw new Exception("Something wrong with entered data");
         }
     } catch (Exception $e) {
         $error = 'ERROR: ' . $e->getMessage() . "\n";
         F3::set('error', $error);
     }
 } catch (Exception $e) {
 /**
  * Tag disponível apenas no PHPUnit 3.4, ainda não disponível no pacote
  * Pear PHPUnit-beta3. Note o uso do '@' para supressão das mensagens de
  * erro.
  *
  * @outputBuffering enabled
  */
 public function testStreamFileExtensionSupported()
 {
     $this->configVfs();
     $filename = 'tmp/example.pdf';
     $filepath = vfsStream::url($filename);
     fopen($filepath, 'a+');
     $directory = (array) vfsStream::url(vfsStreamWrapper::getRoot()->getName());
     $stub = $this->getMock('Mimetype');
     $stub->expects($this->once())->method('getType')->will($this->returnValue('application/pdf'));
     $fileStream = new FileStream($stub, $directory);
     $fileStream->setFilepath($filepath);
     @$fileStream->streamFile();
 }
Beispiel #8
0
     throw new Exception("Job is pending");
 }
 //Get file guid
 $guid = $jobInfo->result->inputs[0]->outputs[0]->guid;
 F3::set('fileId', $guid);
 //Get file name
 $name = $jobInfo->result->inputs[0]->outputs[0]->name;
 //Local path to the downloads folder
 $downloadFolder = dirname(__FILE__) . '/../downloads';
 //Check is folder exist
 if (!file_exists($downloadFolder)) {
     //If folder don't exist create it
     mkdir($downloadFolder);
 }
 //Obtaining file stream of downloading file and definition of folder where to download file
 $outFileStream = FileStream::fromHttp($downloadFolder, $name);
 //Download file from GroupDocs.
 $download = $storageApi->GetFile($clientId, $guid, $outFileStream);
 F3::set("message", "File was converted and downloaded to the " . $downloadFolder . "/" . $name);
 //### If request was successfull
 //Generation of iframe URL using $pageImage->result->guid
 //iframe to prodaction server
 if ($basePath == "https://api.groupdocs.com/v2.0") {
     $iframe = 'https://apps.groupdocs.com/document-viewer/embed/' . $guid;
     //iframe to dev server
 } elseif ($basePath == "https://dev-api-groupdocs.dynabic.com/v2.0") {
     $iframe = 'https://dev-apps-groupdocs.dynabic.com/document-viewer/embed/' . $guid;
     //iframe to test server
 } elseif ($basePath == "https://stage-api-groupdocs.dynabic.com/v2.0") {
     $iframe = 'https://stage-apps-groupdocs.dynabic.com/document-viewer/embed/' . $guid;
 } elseif ($basePath == "http://realtime-api.groupdocs.com") {
 protected function setUp()
 {
     $this->fs = FileStream::fromFile(dirname(__FILE__) . "/resources/test.doc");
 }
Beispiel #10
0
 /**
  * @param string $resourcePath path to method endpoint
  * @param string $method method to call
  * @param array $queryParams parameters to be place in query URL
  * @param array $postData parameters to be placed in POST body
  * @param array $headerParams parameters to be place in request header
  * @return unknown
  */
 public function callAPI($apiServer, $resourcePath, $method, $queryParams, $postData, $headerParams, FileStream $outFileStream = null)
 {
     $headers = array();
     foreach ($this->headers as $key => $val) {
         $headers[] = "{$key}: {$val}";
     }
     if ($headerParams != null) {
         foreach ($headerParams as $key => $val) {
             $headers[] = "{$key}: {$val}";
         }
     }
     $isFileUpload = false;
     if (empty($postData)) {
         $headers[] = "Content-type: text/html";
     } else {
         if ($postData instanceof FileStream) {
             $isFileUpload = true;
             $headers[] = "Content-type: application/octet-stream";
             $headers[] = "Content-Length: " . $postData->getSize();
         } else {
             if (is_object($postData) or is_array($postData) or is_string($postData)) {
                 $headers[] = "Content-type: application/json";
                 $postData = json_encode(self::object_to_array($postData));
             }
         }
     }
     $url = $apiServer . $resourcePath;
     $timeoutSec = 0;
     $curl = curl_init();
     if ($this->debug) {
         // curl_setopt($curl, CURLOPT_HEADER, true); // Display headers; returns null response
         curl_setopt($curl, CURLOPT_VERBOSE, true);
         // Display communication with server
         curl_setopt($curl, CURLOPT_STDERR, $curl_log = fopen($this->curlLogFilepath, 'a+'));
     }
     curl_setopt($curl, CURLOPT_TIMEOUT, $timeoutSec);
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
     // return the result on success, rather than just TRUE
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
     if (!empty($queryParams)) {
         $url = $url . '?' . http_build_query($queryParams);
     }
     if ($method == self::$POST) {
         if ($isFileUpload) {
             curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
             curl_setopt($curl, CURLOPT_TIMEOUT, 0);
             curl_setopt($curl, CURLOPT_PUT, true);
             curl_setopt($curl, CURLOPT_INFILE, $postData->getInputStream());
             curl_setopt($curl, CURLOPT_INFILESIZE, $postData->getSize());
         } else {
             curl_setopt($curl, CURLOPT_POST, true);
             curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
         }
     } else {
         if ($method == self::$PUT) {
             curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
             curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
         } else {
             if ($method == self::$DELETE) {
                 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                 curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
             }
         }
     }
     $url = self::encodeURI($this->signer->signUrl($url));
     curl_setopt($curl, CURLOPT_URL, $url);
     if ($outFileStream !== null) {
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
         // curl_setopt($curl, CURLOPT_FILE, $outFileStream->getInputStream());
         curl_setopt($curl, CURLOPT_HEADERFUNCTION, array($outFileStream, 'headerCallback'));
         curl_setopt($curl, CURLOPT_WRITEFUNCTION, array($outFileStream, 'bodyCallback'));
     }
     if ($this->debug) {
         $body = "> Request Body: {$this->newline}";
         if ($isFileUpload) {
             fwrite($curl_log, "{$body} >>>stream info: size=" . $postData->getSize() . " content-type=" . $postData->getContentType());
         } else {
             fwrite($curl_log, $body . $postData);
         }
         echo $this->newline;
     }
     // Make the request
     $response = curl_exec($curl);
     $response_info = curl_getinfo($curl);
     // Close curl
     curl_close($curl);
     if ($this->debug) {
         $body = "< Response Body: {$this->newline}";
         if ($outFileStream !== null) {
             fwrite($curl_log, "{$body} <<<stream info: size=" . $outFileStream->getSize() . " content-type=" . $outFileStream->getContentType() . " filename=" . $outFileStream->getFileName());
         } else {
             fwrite($curl_log, $body . $response);
         }
         fwrite($curl_log, $this->newline);
         fclose($curl_log);
     }
     // Handle the response
     if ($response_info['http_code'] == 0) {
         throw new ApiException("TIMEOUT: api call to " . $url . " took more than " . $timeoutSec . "s to return");
     } else {
         if ($response_info['http_code'] == 200 || $response_info['http_code'] == 201 || $response_info['http_code'] == 202) {
             if ($outFileStream !== null) {
                 if (in_array('Transfer-Encoding', $outFileStream->headers) or $outFileStream->getSize() > 0) {
                     fclose($outFileStream->getInputStream());
                     return $outFileStream;
                 } else {
                     return null;
                 }
             } else {
                 return json_decode($response);
             }
         } else {
             if ($response_info['http_code'] == 401) {
                 throw new ApiException("Unauthorized API request to " . $url, 401);
             } else {
                 if ($response_info['http_code'] == 404) {
                     return null;
                 } else {
                     $msg = $response;
                     if ($outFileStream !== null and !empty($outFileStream->jsonError)) {
                         $msg = $outFileStream->jsonError;
                     }
                     $jsonArray = json_decode($msg, true);
                     if (is_array($jsonArray)) {
                         $msg = $jsonArray['error_message'];
                     }
                     throw new ApiException($msg, $response_info['http_code']);
                 }
             }
         }
     }
 }
Beispiel #11
0
 * Faz stream de arquivo para o buffer do navegador.
 *
 * @author   Eriksen Costa Paixão <*****@*****.**>
 * @license  http://creativecommons.org/licenses/GPL/2.0/legalcode.pt  CC GNU GPL
 * @package  Core
 * @since    Arquivo disponível desde a versão 1.1.0
 * @version  $Id$
 */
require_once 'Utils/Mimetype.class.php';
require_once 'Utils/FileStream.class.php';
// Pega o nome do arquivo (caminho completo)
$filename = isset($_GET['filename']) ? $_GET['filename'] : NULL;
// Diretórios públicos (permitidos) para stream de arquivo.
$defaultDirectories = array('tmp', 'pdf');
// Classe Mimetype
$mimetype = new Mimetype();
// Classe FileStream
$fileStream = new FileStream($mimetype, $defaultDirectories);
try {
    $fileStream->setFilepath($filename);
} catch (Exception $e) {
    print $e->getMessage();
    exit;
}
try {
    $fileStream->streamFile();
} catch (Exception $e) {
    print $e->getMessage();
    exit;
}
unlink($filename);
 /**
  * 
  * @param string $path
  * @param array $params
  */
 public function __construct($path, $params = null)
 {
     parent::__construct($path, $params);
 }