TYPO3 CMS  TYPO3_6-2
Download.php
Go to the documentation of this file.
1 <?php
3 
24 class Download implements \SplObserver {
25 
29  protected $filePointer = FALSE;
30 
34  protected $targetFilePath = '';
35 
39  protected $targetDirectory = '';
40 
44  protected $targetFilename = '';
45 
53  public function __construct($directory, $filename = '') {
54  $this->setDirectory($directory);
55  $this->setFilename($filename);
56  }
57 
67  public function update(\SplSubject $request) {
68  $event = $request->getLastEvent();
69  switch ($event['name']) {
70  case 'receivedHeaders':
71  if ($this->targetFilename === '') {
72  $this->determineFilename($request, $event['data']);
73  }
74  $this->openFile();
75  break;
76  case 'receivedBodyPart':
77 
78  case 'receivedEncodedBodyPart':
79  fwrite($this->filePointer, $event['data']);
80  break;
81  case 'receivedBody':
82  $this->closeFile();
83  break;
84  default:
85  // Do nothing
86  }
87  }
88 
96  public function setDirectory($directory) {
97  if (!is_dir($directory)) {
98  throw new \InvalidArgumentException($directory . ' is not a directory', 1312223779);
99  }
100  if (!\TYPO3\CMS\Core\Utility\GeneralUtility::isAllowedAbsPath($directory)) {
101  throw new \InvalidArgumentException($directory . ' is not within the PATH_site' . ' OR within the lockRootPath', 1328734617);
102  }
103  $this->targetDirectory = ($directory = rtrim($directory, DIRECTORY_SEPARATOR));
104  }
105 
114  public function setFilename($filename = '') {
115  $this->targetFilename = basename($filename);
116  }
117 
126  protected function determineFilename(\HTTP_Request2 $request, \HTTP_Request2_Response $response) {
127  $matches = array();
128  $disposition = $response->getHeader('content-disposition');
129  if ($disposition !== NULL && 0 === strpos($disposition, 'attachment') && 1 === preg_match('/filename="([^"]+)"/', $disposition, $matches)) {
130  $filename = basename($matches[1]);
131  } else {
132  $filename = basename($request->getUrl()->getPath());
133  }
134  $this->setFilename($filename);
135  }
136 
147  protected function openFile() {
148  if ($this->targetFilename === '') {
149  throw new \UnexpectedValueException('The file name must not be empty', 1321113658);
150  }
151  $this->targetFilePath = $this->targetDirectory . DIRECTORY_SEPARATOR . $this->targetFilename;
152  $this->filePointer = @fopen($this->targetFilePath, 'wb');
153  if ($this->filePointer === FALSE) {
154  throw new \TYPO3\CMS\Core\Exception('Cannot open target file ' . $this->targetFilePath, 1320833203);
155  }
156  }
157 
163  protected function closeFile() {
164  fclose($this->filePointer);
165  $this->filePointer = FALSE;
167  }
168 
169 }
static fixPermissions($path, $recursive=FALSE)
__construct($directory, $filename='')
Definition: Download.php:53
update(\SplSubject $request)
Definition: Download.php:67
determineFilename(\HTTP_Request2 $request, \HTTP_Request2_Response $response)
Definition: Download.php:126