function readBody(&$curlInterface, &$content)
{
    $ret = strlen($content);
    echo $content;
    if (connection_status() != 0) {
        curl_close($curlInterface);
        exit;
    }
    flush();
    return $ret;
}
 function smartReadFile($location, $filename, $mimeType = 'application/octet-stream')
 {
     if (!file_exists($location)) {
         header("HTTP/1.0 404 Not Found");
         return;
     }
     $size = filesize($location);
     $time = date('r', filemtime($location));
     $fm = fopen($location, 'r') or die("Couldn't get handle");
     #  ob_start();
     if (!$fm) {
         header("HTTP/1.0 505 Internal server error");
         return;
     }
     $begin = 0;
     $end = $size;
     if (isset($_SERVER['HTTP_RANGE'])) {
         if (preg_match('/bytes=\\h*(\\d+)-(\\d*)[\\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
             $begin = intval($matches[0]);
             if (!empty($matches[1])) {
                 $end = intval($matches[1]);
             }
         }
     }
     if ($begin > 0 || $end < $size) {
         header('HTTP/1.0 206 Partial Content');
     } else {
         header('HTTP/1.0 200 OK');
     }
     header('Content-Type: application/force-download');
     header('Cache-Control: public, must-revalidate, max-age=0');
     header('Pragma: no-cache');
     header('Accept-Ranges: bytes');
     header('Content-Length:' . ($end - $begin));
     header("Content-Range: bytes {$begin}-{$end}/{$size}");
     header("Content-Disposition: attachment; filename={$filename}");
     header('Content-Transfer-Encoding: binary');
     header("Last-Modified: {$time}");
     header('Connection: close');
     // check for IE only headers
     if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) {
         header("Cache-control: private");
         header('Pragma: private');
     } else {
         header('Pragma: public');
     }
     $cur = $begin;
     fseek($fm, $begin, 0);
     while (!feof($fm) && $cur < $end && connection_status() == 0) {
         print fread($fm, min(1024 * 16, $end - $cur));
         $cur += 1024 * 16;
     }
     #  ob_end_flush();
 }
 function server()
 {
     for ($i = 0, $timeout = 10; $i < $timeout; $i++) {
         if (connection_status() != 0) {
             exit;
         }
         $where = array();
         $user_id = $user_id = get_user_id();
         session_write_close();
         $where['user_id'] = $user_id;
         $where['time'] = array('elt', time() - 1);
         $model = M("Push");
         $data = $model->where($where)->find();
         $where['id'] = $data['id'];
         //dump($model);
         if ($data) {
             sleep(1);
             $model->where("id=" . $data['id'])->delete();
             $this->ajaxReturn($data['data'], $data['info'], $data['status']);
         } else {
             sleep(5);
         }
     }
     $this->ajaxReturn(null, "no-data", 0);
 }
Exemple #4
0
 private function compress($data, $level = 0)
 {
     if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
         $encoding = 'gzip';
     }
     if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) {
         $encoding = 'x-gzip';
     }
     if (!isset($encoding)) {
         return $data;
     }
     if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
         return $data;
     }
     if (headers_sent()) {
         return $data;
     }
     if (connection_status()) {
         return $data;
     }
     /*
     *  header('Vary: Accept-Encoding');
      header("cache-control: must-revalidate");
      $offset = 60 * 60;
      $expire = "expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
      header($expire);
     */
     $this->addHeader('Content-Encoding: ' . $encoding);
     $this->addHeader('Vary: Accept-Encoding');
     $output = gzencode($data, (int) $level);
     return $output;
 }
 /**
  * Ensure shutdown hook terminates if connection status is TIMEOUT.
  */
 public function testShutdownHookTimeout()
 {
     connection_status(CONNECTION_TIMEOUT);
     UnlinkUploads::shutdownHook($this->files);
     // Shutdown hook should exist on first loop so all files should exist.
     $this->assertFilesExist();
 }
Exemple #6
0
function send_file($path)
{
    ob_end_clean();
    if (preg_match(':\\.\\.:', $path)) {
        return FALSE;
    }
    if (!preg_match(':^plotcache/:', $path)) {
        return FALSE;
    }
    if (!is_file($path) or connection_status() != 0) {
        return FALSE;
    }
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Content-Type: application/octet-stream");
    header("Content-Length: " . (string) filesize($path));
    header("Content-Disposition: inline; filename=" . basename($path));
    header("Content-Transfer-Encoding: binary\n");
    if ($file = fopen($path, 'rb')) {
        while (!feof($file) and connection_status() == 0) {
            print fread($file, 1024 * 8);
            flush();
            @ob_flush();
        }
        fclose($file);
    }
    return connection_status() == 0 and !connection_aborted();
}
function send_file($name)
{
    $path = $name;
    $path_info = pathinfo($path);
    $basename = $path_info['basename'];
    if (!is_file($path) or connection_status() != 0) {
        return false;
    }
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Expires: " . gmdate("D, d M Y H:i:s", mktime(date("H") + 2, date("i"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Content-Type: application/octet-stream");
    header("Content-Length: " . (string) filesize($path));
    header("Content-Disposition: inline; filename={$basename}");
    header("Content-Transfer-Encoding: binary\n");
    if ($file = fopen($path, 'rb')) {
        while (!feof($file) and connection_status() == 0) {
            print fread($file, 1024 * 8);
            flush();
        }
        fclose($file);
    }
    return connection_status() == 0 and !connection_aborted();
}
function send_file($path)
{
    session_write_close();
    ob_end_clean();
    if (!is_file($path) || connection_status() != 0) {
        return false;
    }
    //to prevent long file from getting cut off from    //max_execution_time
    set_time_limit(0);
    $name = basename($path);
    //filenames in IE containing dots will screw up the
    //filename unless we add this
    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
        $name = preg_replace('/\\./', '%2e', $name, substr_count($name, '.') - 1);
        //required, or it might try to send the serving    //document instead of the file
        $name = str_replace(array("\"", "<", ">", "?", ":"), array('%22', '%3c', '%3e', '%3f', '_'), $name);
    } else {
        $name = str_replace(array("\"", ":"), array("'", "_"), $name);
    }
    header("Cache-Control: ");
    header("Pragma: ");
    header("Content-Type: application/octet-stream");
    header("Content-Length: " . (string) filesize($path));
    header('Content-Disposition: attachment; filename="' . $name . '"');
    header("Content-Transfer-Encoding: binary\n");
    if ($file = fopen($path, 'rb')) {
        while (!feof($file) && connection_status() == 0) {
            print fread($file, 1024 * 8);
            flush();
        }
        fclose($file);
    }
    return connection_status() == 0 and !connection_aborted();
}
	/**
	 *	@interface ResponseService
	**/
	public function processResponse($model){
		set_time_limit(0);
		$filename = $model['file'];
		$asname = $model['asname'];
		$mtype = $model['mime'];
		
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		header("Content-Type: $mtype");
		header("Content-Disposition: attachment; filename=\"$asname\"");
		header("Content-Transfer-Encoding: binary");
		
		$file = @fopen($filename,"rb");
		if ($file) {
			while(!feof($file)) {
				print(fread($file, 1024*8));
				flush();
				if (connection_status()!=0) {
					@fclose($file);
					die();
				}
			}
		@fclose($file);
		}
		
		$model['valid'] = true;
		return json_encode($model);
	}
 public function executeDownload(sfWebRequest $request)
 {
     if (!$request->hasParameter('id')) {
         $this->forward404();
     }
     $item = sfExtranetItemQuery::create()->findOneById($request->getParameter('id'));
     if (!$item || $item->getType() != 'document') {
         $this->forward404();
     }
     $file_name = $item->getFile();
     $data_dir = sfConfig::get('sf_data_dir') . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR;
     $file_real = $data_dir . $file_name;
     $info = pathinfo($file_name);
     $ext = $info['extension'];
     $attachment = $item->getTitle() . '.' . $ext;
     $this->setLayout(false);
     header("Pragma: public");
     header("Expires: 0");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Cache-Control: public", false);
     header("Content-Description: File Transfer");
     header("Content-Type: application/octet-stream");
     header("Accept-Ranges: bytes");
     header("Content-Disposition: attachment; filename=\"" . $attachment . "\";");
     header("Content-Transfer-Encoding: binary");
     header("Content-Length: " . filesize($file_real));
     if ($stream = fopen($file_real, 'rb')) {
         while (!feof($stream) && connection_status() == 0) {
             set_time_limit(0);
             print fread($stream, 1024 * 8);
             flush();
         }
         fclose($stream);
     }
 }
Exemple #11
0
 private function compress($data, $level = 0)
 {
     $this->addHeader('X-Test: blub');
     return $data;
     if (!isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
         return $data;
     }
     if (false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip')) {
         $encoding = 'x-gzip';
     } elseif (false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
         $encoding = 'gzip';
     } else {
         return $data;
     }
     if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
         return $data;
     }
     if (headers_sent()) {
         return $data;
     }
     if (connection_status()) {
         return $data;
     }
     $this->addHeader('Content-Encoding: ' . $encoding);
     return gzencode($data, (int) $level);
 }
Exemple #12
0
 private function compress($data, $level = 0)
 {
     if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
         $encoding = 'gzip';
     }
     if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false) {
         $encoding = 'x-gzip';
     }
     if (!isset($encoding) || ($level < -1 || $level > 9)) {
         return $data;
     }
     if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
         return $data;
     }
     if (headers_sent()) {
         return $data;
     }
     if (connection_status()) {
         return $data;
     }
     if (error_get_last() !== NULL) {
         return $data;
     }
     $this->add_header('Content-Encoding: ' . $encoding);
     return gzencode($data, (int) $level);
 }
 /**
  * event function to download files
  * @param object $evctl
  * The script is using chunk download just to make sure that the large file download works without memory leak
  */
 function eventDownloadFiles(EventControler $evctl)
 {
     if ((int) $evctl->fileid > 0) {
         $this->getId((int) $evctl->fileid);
         $upload_path = $GLOBALS['FILE_UPLOAD_PATH'];
         $file_name = $this->file_name;
         $file_desc = $this->file_description;
         $file_mime = $this->file_mime;
         if ($file_mime == '' || $file_mime == 'unknown') {
             $file_mime = 'application/octet-stream';
         }
         $file_size = $this->file_size;
         $saved_file_name = $file_name . '.' . $this->file_extension;
         $file_download = $upload_path . '/' . $saved_file_name;
         if (is_file($file_download)) {
             ob_end_clean();
             header("Cache-Control:no-store,no-cache,must-revalidate");
             header("Cache-Control:post-check=0,pre-check=0", false);
             header("Pragma:no-cache");
             header("Expires:" . gmdate("D,d M Y H:i:s", mktime(date("H") + 2, date("l"), date("s"), date("m"), date("d"), date("Y"))) . " GMT");
             header("Last-Modified:" . gmdate("D,d M Y H:i:s") . " GMT");
             header("Content-Type:" . $file_mime);
             header("Content-Length:" . $file_size);
             header("Content-Disposition:inline;filename={$file_desc}");
             header("Content-Transfer-Encoding:binary\n");
             if ($file = fopen($file_download, 'rb')) {
                 while (!feof($file) and connection_status() == 0) {
                     print fread($file, 1024 * 8);
                     flush();
                 }
             }
         }
     }
 }
	public function file($filePath) {
		set_time_limit(0);
		if (!is_file($filePath)) {
		  return "File does not exist. Make sure you specified correct file name."; 
		}

		if ($mimeType = $this->getMimeType($filePath) === false) {
			return "Not allowed file type.";
		}
		
		$this->setHeaders($mimeType, basename($filePath));
		
		$file = @fopen($filePath, "rb");
		if ($file) {
  			while(!feof($file)) {
    			print(fread($file, 1024*8));
    			flush();
    			if (connection_status()!=0) {
      				@fclose($file);
      				die();
    			}
  			}
  			@fclose($file);
		}		
		
		$this->log($filePath);
		die();
	}
Exemple #15
0
 /**
  * Compress the data
  *
  * Checks the accept encoding of the browser and compresses the data before
  * sending it to the client.
  *
  * @param   string  $data  Content to compress for output.
  * @return  string  compressed data
  */
 protected function squeeze($data)
 {
     $encoding = $this->acceptEncoding();
     if (!$encoding) {
         return $data;
     }
     if (!extension_loaded('zlib') || ini_get('zlib.output_compression')) {
         return $data;
     }
     if (headers_sent()) {
         return $data;
     }
     if (connection_status() !== 0) {
         return $data;
     }
     // Ideal level
     $level = 4;
     /*
     $size = strlen($data);
     $crc  = crc32($data);
     
     $gzdata  = "\x1f\x8b\x08\x00\x00\x00\x00\x00";
     $gzdata .= gzcompress($data, $level);
     
     $gzdata  = substr($gzdata, 0, strlen($gzdata) - 4);
     $gzdata .= pack("V",$crc) . pack("V", $size);
     */
     $gzdata = gzencode($data, $level);
     $this->headers->set('Content-Encoding', $encoding);
     $this->headers->set('X-Content-Encoded-By', 'HUBzero');
     return $gzdata;
 }
Exemple #16
0
/**
 * Connection time out
 */
function check_conn_timeout()
{
    $status = connection_status();
    if (($status & CONNECTION_TIMEOUT) == CONNECTION_TIMEOUT) {
        echo 'Got timeout';
    }
}
 function file($hash)
 {
     $file = $this->CompanyFile->find("CompanyFile.hash = '" . $hash . "'");
     if ($file['CompanyFile']['public'] == '1') {
         $filePath = dirname(dirname(WWW_ROOT)) . DS . "files" . DS . "uploads" . DS . $file['CompanyFile']['company_id'] . DS . $file['CompanyFile']['file'];
         // Prepare headers
         header("Pragma: public");
         header("Expires: 0");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Cache-Control: public", false);
         header("Content-Description: File Transfer");
         header("Content-Type: " . $file['CompanyFile']['ext']);
         header("Accept-Ranges: bytes");
         header("Content-Disposition: attachment; filename=\"" . $file['CompanyFile']['file'] . "\";");
         header("Content-Transfer-Encoding: binary");
         header("Content-Length: " . filesize($filePath));
         // Send file for download
         if ($stream = fopen($filePath, 'rb')) {
             while (!feof($stream) && connection_status() == 0) {
                 //reset time limit for big files
                 set_time_limit(0);
                 print fread($stream, 1024 * 8);
                 flush();
             }
             fclose($stream);
         }
         exit;
     } else {
         $this->notifyCustomer('Sorry, you don\'t have permission to download this file.', $this->referer(), 'error');
     }
 }
 function getJson($url)
 {
     //echo urlencode($url)."</br>";
     $code = http_response_code();
     //  Initiate curl
     $ch = curl_init();
     // Disable SSL verification
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     // Will return the response, if false it print the response
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     // Set the url
     curl_setopt($ch, CURLOPT_URL, $url);
     // Execute
     $result = curl_exec($ch);
     if (connection_aborted()) {
         echo "erra bae";
     } elseif (connection_status() == CONNECTION_TIMEOUT) {
         echo "<h1>Error caught, stopped from crashing</h1>";
     } else {
         $this->busted = false;
         //  any normal completion actions
     }
     // Closing
     curl_close($ch);
     return json_decode($result, true);
 }
Exemple #19
0
 /**
  * Start a big file download on Laravel Framework 4.0 / 4.1
  * Source (originally for Laravel 3.*) : http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel
  * @param  string $path    Path to the big file
  * @param  string $name    Name of the file (used in Content-disposition header)
  * @param  array  $headers Some extra headers
  */
 public function sendFile($path, $name = null, array $headers = array())
 {
     if (is_null($name)) {
         $name = basename($path);
     }
     $file = new \Symfony\Component\HttpFoundation\File\File($path);
     $mime = $file->getMimeType();
     // Prepare the headers
     $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => $mime, 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => \File::size($path), 'Content-Disposition' => 'attachment; filename=' . $name), $headers);
     $response = new \Symfony\Component\HttpFoundation\Response('', 200, $headers);
     // If there's a session we should save it now
     if (\Config::get('session.driver') !== '') {
         \Session::save();
     }
     session_write_close();
     if (ob_get_length()) {
         ob_end_clean();
     }
     $response->sendHeaders();
     // Read the file
     if ($file = fopen($path, 'rb')) {
         while (!feof($file) and connection_status() == 0) {
             print fread($file, 1024 * 8);
             flush();
         }
         fclose($file);
     }
     // Finish off, like Laravel would
     \Event::fire('laravel.done', array($response));
     $response->send();
 }
 /**
  * @param \swoole_http_request $request
  * @param \swoole_http_response $response
  * @throws \Exception
  */
 public function __invoke($request, $response)
 {
     $this->app->getContainer()['environment'] = $this->app->getContainer()->factory(function () {
         return new Environment($_SERVER);
     });
     $this->app->getContainer()['request'] = $this->app->getContainer()->factory(function ($container) {
         return Request::createFromEnvironment($container['environment']);
     });
     $this->app->getContainer()['response'] = $this->app->getContainer()->factory(function ($container) {
         $headers = new Headers(['Content-Type' => 'text/html']);
         $response = new Response(200, $headers);
         return $response->withProtocolVersion($container->get('settings')['httpVersion']);
     });
     /**
      * @var ResponseInterface $appResponse
      */
     $appResponse = $this->app->run(true);
     // set http header
     foreach ($appResponse->getHeaders() as $key => $value) {
         $filter_header = function ($header) {
             $filtered = str_replace('-', ' ', $header);
             $filtered = ucwords($filtered);
             return str_replace(' ', '-', $filtered);
         };
         $name = $filter_header($key);
         foreach ($value as $v) {
             $response->header($name, $v);
         }
     }
     // set http status
     $response->status($appResponse->getStatusCode());
     // send response to browser
     if (!$this->isEmptyResponse($appResponse)) {
         $body = $appResponse->getBody();
         if ($body->isSeekable()) {
             $body->rewind();
         }
         $settings = $this->app->getContainer()->get('settings');
         $chunkSize = $settings['responseChunkSize'];
         $contentLength = $appResponse->getHeaderLine('Content-Length');
         if (!$contentLength) {
             $contentLength = $body->getSize();
         }
         $totalChunks = ceil($contentLength / $chunkSize);
         $lastChunkSize = $contentLength % $chunkSize;
         $currentChunk = 0;
         while (!$body->eof() && $currentChunk < $totalChunks) {
             if (++$currentChunk == $totalChunks && $lastChunkSize > 0) {
                 $chunkSize = $lastChunkSize;
             }
             $response->write($body->read($chunkSize));
             if (connection_status() != CONNECTION_NORMAL) {
                 break;
             }
         }
         $response->end();
     }
 }
 public function action_index($attachmentId = false)
 {
     $attachmentId = explode("_", $attachmentId);
     $attachmentId = $attachmentId[0];
     if (!($attachment = $this->getAttachment($attachmentId))) {
         return;
     }
     $model = ET::getInstance("attachmentModel");
     // Serve up the file.
     $path = $model->path() . $attachmentId . $attachment["secret"];
     $file = @fopen($path, 'rb');
     $speed = 1024;
     if (is_resource($file) === true) {
         $size = sprintf('%u', filesize($path));
         set_time_limit(0);
         // Close the session so the user can still make other requests while this is happening.
         if (strlen(session_id()) > 0) {
             session_write_close();
         }
         $range = array(0, $size - 1);
         // Don't really understand how this code works, tbh.
         // From: http://stackoverflow.com/a/7591130
         if (array_key_exists('HTTP_RANGE', $_SERVER) === true) {
             $range = array_map('intval', explode('-', preg_replace('~.*=([^,]*).*~', '$1', $_SERVER['HTTP_RANGE'])));
             if (empty($range[1]) === true) {
                 $range[1] = $size - 1;
             }
             foreach ($range as $key => $value) {
                 $range[$key] = max(0, min($value, $size - 1));
             }
             if ($range[0] > 0 || $range[1] < $size - 1) {
                 header(sprintf('%s %03u %s', 'HTTP/1.1', 206, 'Partial Content'), true, 206);
             }
         }
         header('Accept-Ranges: bytes');
         header('Content-Range: bytes ' . sprintf('%u-%u/%u', $range[0], $range[1], $size));
         header('Pragma: public');
         header('Cache-Control: public, no-cache');
         header('Content-Type: ' . $model->mime($attachment["filename"]));
         header('Content-Length: ' . sprintf('%u', $range[1] - $range[0] + 1));
         header('Content-Disposition: inline; filename="' . basename($attachment["filename"]) . '"');
         header('Content-Transfer-Encoding: binary');
         if ($range[0] > 0) {
             fseek($file, $range[0]);
         }
         while (feof($file) !== true && connection_status() === CONNECTION_NORMAL) {
             echo fread($file, round($speed * 1024));
         }
         flush();
         fclose($file);
         exit;
     } else {
         $this->render404(T("message.attachmentNotFound"), true);
         return false;
     }
 }
Exemple #22
0
function my_shutdown()
{
    global $tables;
    print 'Script status: ' . connection_status();
    # unfortunately buggy in 4.2.1
    $res = Sql_query("select count(*) from {$tables['user']}");
    $row = Sql_fetch_row($res);
    print '<script language="Javascript" type="text/javascript"> document.forms[0].output.value="Done. Now there are ' . $row[0] . ' users in the database";</script>' . "\n";
    # register_shutdown_function("");
    exit;
}
Exemple #23
0
 /**
  * Check the status of the users connection 
  */
 function checkConnection()
 {
     $status = connection_status();
     if ($status != 0) {
         $this->connection = FALSE;
         return FALSE;
     } else {
         $this->connection = TRUE;
         return TRUE;
     }
 }
 /**
  * Method to check users connection status
  * @param void
  * @return property $connStatus bool FALSE on user abort
  */
 public function isUserConn()
 {
     //is the user still connected?
     if (connection_status() != 0) {
         //set a property saying that the user is dead
         $this->connStatus = FALSE;
         return FALSE;
     } else {
         $this->connStatus = TRUE;
         return TRUE;
     }
 }
Exemple #25
0
 public function download($file)
 {
     ob_implicit_flush(true);
     ob_get_flush();
     @ob_get_clean();
     if (file_exists($file) && !is_dir($file)) {
         $fd = fopen($file, 'rb');
         $default = 'application/octet-stream';
         $types = array('txt' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', 'php' => 'text/html', 'css' => 'text/css', 'js' => 'application/javascript', 'json' => 'application/json', 'xml' => 'application/xml', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/x-flv', 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'ico' => 'image/vnd.microsoft.icon', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', 'cab' => 'application/vnd.ms-cab-compressed', 'mp3' => 'audio/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'pdf' => 'application/pdf', 'psd' => 'image/vnd.adobe.photoshop', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'doc' => 'application/msword', 'rtf' => 'application/rtf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet');
         if ($fd) {
             if (ini_get('zlib.output_compression')) {
                 ini_set('zlib.output_compression', 'Off');
             }
             // fix for IE7/8, ticket #183
             if (function_exists('apache_setenv')) {
                 $func = 'apache_setenv';
                 $func('no-gzip', '1');
             }
             $fsize = filesize($file);
             $path_parts = pathinfo($file);
             $ext = strtolower($path_parts['extension']);
             header('Pragma: public');
             header('Expires: -1');
             header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
             header('Content-Disposition: attachment; filename="' . $path_parts['basename'] . '"');
             header('Content-Type: ' . (isset($types[$ext]) ? $types[$ext] : $default));
             header('Content-length: ' . $fsize);
             header('Accept-Ranges: bytes');
             header("Content-Encoding:");
             error_reporting(E_ALL);
             set_time_limit(0);
             while (!feof($fd)) {
                 echo fread($fd, 1 * (1024 * 1024));
                 @ob_flush();
                 flush();
                 if (connection_status() != 0) {
                     @fclose($fd);
                     exit(0);
                 }
             }
             @fclose($fd);
             exit(0);
         } else {
             // file couldn't be opened
             header('HTTP/1.0 500 Internal Server Error');
             exit(0);
         }
     } else {
         // file does not exist
         header('HTTP/1.0 404 Not Found');
         exit(0);
     }
 }
function marketorders_file_download($filename, $mimetype = 'application/octet-stream')
{
    if (!file_exists($filename)) {
        die('Файл не найден');
    }
    $from = $to = 0;
    $cr = NULL;
    if (isset($_SERVER['HTTP_RANGE'])) {
        $range = substr($_SERVER['HTTP_RANGE'], strpos($_SERVER['HTTP_RANGE'], '=') + 1);
        $from = strtok($range, '-');
        $to = strtok('/');
        if ($to > 0) {
            $to++;
        }
        if ($to) {
            $to -= $from;
        }
        header('HTTP/1.1 206 Partial Content');
        $cr = 'Content-Range: bytes ' . $from . '-' . ($to ? $to . '/' . $to + 1 : filesize($filename));
    } else {
        header('HTTP/1.1 200 Ok');
    }
    $etag = md5($filename);
    $etag = substr($etag, 0, 8) . '-' . substr($etag, 8, 7) . '-' . substr($etag, 15, 8);
    header('ETag: "' . $etag . '"');
    header('Accept-Ranges: bytes');
    header('Content-Length: ' . (filesize($filename) - $to + $from));
    if ($cr) {
        header($cr);
    }
    header('Connection: close');
    header('Content-Type: ' . $mimetype);
    header('Last-Modified: ' . gmdate('r', filemtime($filename)));
    $f = fopen($filename, 'r');
    header('Content-Disposition: attachment; filename="' . basename($filename) . '";');
    if ($from) {
        fseek($f, $from, SEEK_SET);
    }
    if (!isset($to) or empty($to)) {
        $size = filesize($filename) - $from;
    } else {
        $size = $to;
    }
    $downloaded = 0;
    while (!feof($f) and !connection_status() and $downloaded < $size) {
        echo fread($f, 512000);
        $downloaded += 512000;
        ob_flush();
        flush();
    }
    fclose($f);
}
function dl_file_resume($file = '', $fileinfo = array(), $onsuccess = false)
{
    // function based on this one here:
    // http://www.php.net/manual/de/function.fread.php#63893
    //First, see if the file exists
    if (!is_file($file) && connection_status()) {
        return false;
    }
    //Gather relevent info about file
    $filename = empty($fileinfo['realfname']) ? basename($file) : $fileinfo['realfname'];
    $disposition = empty($fileinfo['method']) ? 'attachment' : $fileinfo['method'];
    if ($disposition == 'attachment') {
        $fileinfo['mimetype'] = "application/force-download";
    }
    if (empty($fileinfo['mimetype']) && empty($fileinfo['extension'])) {
        $file_extension = strtolower(substr(strrchr($filename, "."), 1));
        $ctype = isset($GLOBALS['phpwcms']['mime_types'][$file_extension]) ? $GLOBALS['phpwcms']['mime_types'][$file_extension] : 'application/force-download';
    } else {
        $ctype = $fileinfo['mimetype'];
        $file_extension = $fileinfo['extension'];
    }
    //Begin writing headers
    header('Cache-Control: ');
    header('Cache-Control: public');
    header('Pragma: ');
    //Use the switch-generated Content-Type
    header('Content-Type: ' . $ctype);
    if (isset($_SERVER['HTTP_USER_AGENT']) && strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
        // workaround for IE filename bug with multiple periods / multiple dots in filename
        // that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
        $filename = preg_replace('/\\./', '%2e', $filename, substr_count($filename, '.') - 1);
    }
    //header('Accept-Ranges: bytes');
    $size = filesize($file);
    header('Content-Length: ' . $size);
    header('Content-Transfer-Encoding: binary' . LF);
    header('Content-Disposition: ' . $disposition . '; filename="' . $filename . '"');
    //reset time limit for big files
    @set_time_limit(0);
    //open the file
    $fp = fopen($file, 'rb');
    //seek to start of missing part
    //fseek($fp, $range);
    //start buffered download
    while (!feof($fp) && !connection_status()) {
        print fread($fp, 1024 * 8);
        flush();
        //ob_flush();
    }
    fclose($fp);
    return $onsuccess && !connection_status() && !connection_aborted() ? true : false;
}
Exemple #28
0
function shutdown()
{
    if (connection_aborted()) {
        die;
    } else {
        if (connection_status() == CONNECTION_TIMEOUT) {
            http_response_code(500);
            $error = '{"statuscode":500,"message":"This query took to long, maybe there was an internal error"}';
            die($error);
        } else {
        }
    }
}
Exemple #29
0
 static function stream($filename)
 {
     $fullpath = Video::fullpath('stream', $filename);
     if ($fullpath === false) {
         return false;
     }
     if (connection_status() != 0) {
         return false;
     }
     header('Content-Type: video/quicktime');
     readfile($fullpath);
     return connection_status() == 0 and !connection_aborted();
 }
Exemple #30
0
 /**
  * Remove any left over uploads.
  *
  * @param array $files
  *   Associative array of uploaded files ($_FILES).
  */
 public static function shutdownHook(array $files)
 {
     foreach ($files as $file) {
         // Break and allow a response if the timeout has been reached.
         if ((connection_status() & CONNECTION_TIMEOUT) == CONNECTION_TIMEOUT) {
             break;
         }
         // When files are moved using move_uploaded_file() they are removed from
         // is_uploaded_file() so this should avoid needless unlink() calls.
         if (isset($file['tmp_name']) && is_uploaded_file($file['tmp_name'])) {
             unlink($file['tmp_name']);
         }
     }
 }