foldershare-8.x-1.2/src/Controller/FolderShareDownload.php

src/Controller/FolderShareDownload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
<?php
 
namespace Drupal\foldershare\Controller;
 
use Drupal\Core\Controller\ControllerBase;
use Drupal\Component\Utility\Unicode;
 
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
 
use Drupal\foldershare\ManageLog;
use Drupal\foldershare\Settings;
use Drupal\foldershare\Utilities\FileUtilities;
use Drupal\foldershare\Entity\FolderShare;
use Drupal\foldershare\Entity\Exception\LockException;
use Drupal\foldershare\Entity\Exception\SystemException;
 
/**
 * Defines a class to handle downloading one or more FolderShare entities.
 *
 * <B>Warning:</B> This class is strictly internal to the FolderShare
 * module. The class's existance, name, and content may change from
 * release to release without any promise of backwards compatability.
 *
 * This class handles translating stored FolderShare content into a byte
 * stream to download to a browser via HTTP. It handles two cases:
 *
 * - Download a single FolderShare entity for a file.
 *
 * - Download one or more FolderShare entities for files and folders.
 *
 * In both cases, FolderShare entities for files wrap File entities, which
 * in turn reference stored files. For security reasons, those files are
 * stored with numeric file names and no extensions. To send them to a browser,
 * these files have to be processed to send their human-readable names,
 * file extensions, and MIME types so that a browser or client OS knows what
 * to do with them.
 *
 * When downloading a single FolderShare entity for a file, the file's data
 * is retrieved and sent to the browser as a file attachment.
 *
 * When downloading a single FolderShare entity for a folder, or multiple
 * FolderShare entities, the entities are compressed into a temporary ZIP
 * archive, and that archive's data sent to the browser as a file
 * attachment.
 *
 * @ingroup foldershare
 */
class FolderShareDownload extends ControllerBase {
 
  /*--------------------------------------------------------------------
   *
   * Constants.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * The name of the ZIP archive downloaded for groups of entities.
   *
   * @var string
   */
  const DOWNLOAD_NAME = 'Download.zip';
 
  /*--------------------------------------------------------------------
   *
   * Fields.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * The MIME type guesser.
   *
   * @var \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface
   */
  private $mimeTypeGuesser;
 
  /*--------------------------------------------------------------------
   *
   * Construction.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * Constructs a new form.
   *
   * @param \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface $mimeTypeGuesser
   *   The MIME type guesser.
   */
  public function __construct(
    MimeTypeGuesserInterface $mimeTypeGuesser) {
    $this->mimeTypeGuesser = $mimeTypeGuesser;
  }
 
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('file.mime_type.guesser')
    );
  }
 
  /*--------------------------------------------------------------------
   *
   * Download.
   *
   *--------------------------------------------------------------------*/
 
  /**
   * Downloads the file by transfering the file in binary.
   *
   * The file is sent with a custom HTTP header that includes the full
   * human-readable name of the file and its MIME type. If the $style argument
   * is "show", the file is sent so that a browser may display the file
   * directly. If the $style argument is "download" (the default), the file
   * is sent with a special HTTP header to encourage the browser to save
   * the file instead of displaying it.
   *
   * <B>Post-operation hooks</B>
   * This method calls the "hook_foldershare_post_operation_download" hook
   * for each item downloaded.
   *
   * <B>Activity log</B>
   * If the site hs enabled logging of operations, this method posts a
   * log message for each item downloaded.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object that contains the entity ID of the
   *   file being requested. The entity ID is included in the URL
   *   for links to the file.
   * @param string $encoded
   *   A string containing a comma-separated list of entity IDs.
   *   NOTE: Because this function is the target of a route with a string
   *   argument, the name of the function argument here *must be* named
   *   after the argument name: 'encoded'.
   *
   * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
   *   A binary transfer response is returned to send the file to the
   *   user's browser.
   *
   * @throws \Symfony\Component\HttpKernel\Exxception\AccessDeniedHttpException
   *   Thrown when the user does not have access to the entities.
   *
   * @throws \Symfony\Component\HttpKernel\Exxception\NotFoundHttpException
   *   Thrown if the URL argument is empty or malformed, if any entity ID
   *   in that encoded argument is invalid, if the entities don't all have
   *   the same parent, if the file's those entities refer to cannot be
   *   found, or if a ZIP archive of those entities could not be created.
   *
   * @todo Support media entity download.
   *
   * @todo Support large ZIP files that may take longer to create than the
   * PHP or web server time limits allow.
   */
  public function download(
    Request $request,
    string $encoded = NULL) {
 
    //
    // Validate arguments
    // ------------------
    // Decode the argument an array of FolderShare entity IDs.
    if (empty($encoded) === TRUE) {
      throw new BadRequestHttpException($this->t(
        "Malformed request. Nothing selected to download."));
    }
 
    $entityIds = explode(',', $encoded);
 
    if (empty($entityIds) === TRUE) {
      throw new BadRequestHttpException($this->t(
        "Malformed request. Nothing selected to download."));
    }
 
    // Load all of those entities and make sure the user has access
    // permission.
    $entities = FolderShare::loadMultiple($entityIds);
    foreach ($entities as $entityId => $entity) {
      if ($entity === NULL) {
        throw new NotFoundHttpException($this->t(
          "The entity with ID @id could not be found to download.",
          [
            '@id' => $entityId,
          ]));
      }
 
      if ($entity->isSystemHidden() === TRUE) {
        // Hidden items do not exist.
        throw new NotFoundHttpException(
          FolderShare::getStandardHiddenMessage($entity->getName()));
      }
 
      if ($entity->isSystemDisabled() === TRUE) {
        // Disabled items cannot be edited.
        throw new ConflictHttpException(
          FolderShare::getStandardDisabledMessage('downloaded', $entity->getName()));
      }
 
      if ($entity->access('view') === FALSE) {
        throw new AccessDeniedHttpException($this->t(
          "You do not have permission to download '@name'.",
          [
            '@name' => $entity->getName(),
          ]));
      }
    }
 
    //
    // Prepare to download
    // -------------------
    // Get the file to download.
    //
    // Note that downloading Media objects is not supported.
    $entity = reset($entities);
    $zipFirst = FALSE;
 
    if (count($entities) !== 1 || $entity->isFolder() === TRUE) {
      // There is more than one entity to download, or there is just one
      // entity but it is a folder. ZIP them together.
      $zipFirst = TRUE;
    }
    elseif (count($entities) === 1) {
      // There is just one entity to download. If it is a file or image,
      // we can download it directly.
      if ($entity->isFile() === TRUE || $entity->isImage() === TRUE) {
        // Download a single file.
        //
        // Get the file's URI, human-readable name, MIME type, and size.
        if ($entity->isFile() === TRUE) {
          $file = $entity->getFile();
        }
        else {
          $file = $entity->getImage();
        }
 
        $uri      = $file->getFileUri();
        $filename = $file->getFilename();
        $mimeType = Unicode::mimeHeaderEncode($file->getMimeType());
        $realPath = FileUtilities::realpath($uri);
 
        if ($realPath === FALSE || file_exists($realPath) === FALSE) {
          throw new NotFoundHttpException($this->t(
            "The file '@name' (ID '@id') could not be found to download.",
            [
              '@name' => $file->getFilename(),
              '@id'   => $file->id(),
            ]));
        }
 
        $filesize = FileUtilities::filesize($realPath);
      }
      elseif ($entity->isMedia() === TRUE) {
        // Media entities are currently not supported for download.
        //
        // @todo  Support media entity download.
        throw UnsupportedMediaTypeHttpException($this->t(
          "The media item '@name' currently does not support downloading.",
          [
            '@name' => $entity->getName(),
          ]));
      }
      else {
        // The entity is of an unknown type.
        throw UnsupportedMediaTypeHttpException($this->t(
          "The item '@name' does not support downloading.",
          [
            '@name' => $entity->getName(),
          ]));
      }
    }
 
    if ($zipFirst === TRUE) {
      // Download multiple files and/or folders. Create a ZIP archive.
      try {
        // ZIP the entities.
        //
        // @todo Support (somehow) large ZIP archives that either have a lot
        // of entries, or the entries are big. When ZIPs are large, this can
        // take a long time and get interrupted by a PHP or web server timeout.
        $uri = FolderShare::createZipArchive($entities);
 
        // Use a generic name for the download ZIP.
        $filename = self::DOWNLOAD_NAME;
        $filesize = FileUtilities::filesize($uri);
        $mimeType = Unicode::mimeHeaderEncode(
          $this->mimeTypeGuesser->guess($filename));
      }
      catch (LockException $e) {
        throw new ConflictHttpException($e->getMessage());
      }
      catch (SystemException $e) {
        throw new HttpException(
          Response::HTTP_INTERNAL_SERVER_ERROR,
          $e->getMessage());
      }
      catch (\Exception $e) {
        throw new NotFoundHttpException($this->t(
          "The items could not be download."));
      }
    }
 
    //
    // Build header
    // ------------
    // Build an HTTP header for the file by getting the user-visible
    // file name and MIME type. Both of these are essential in the HTTP
    // header since they tell the browser what type of file it is getting,
    // and the name of the file if the user wants to save it their disk.
    $headers = [
      // Use the File object's MIME type.
      'Content-Type'        => $mimeType,
 
      // Use the human-visible file name.
      'Content-Disposition' => 'attachment; filename="' . $filename . '"',
 
      // Use the saved file size, in bytes.
      'Content-Length'      => $filesize,
 
      // Don't cache the file because permissions and content may
      // change.
      'Pragma'              => 'no-cache',
      'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0',
      'Expires'             => '0',
      'Accept-Ranges'       => 'bytes',
    ];
 
    $scheme = Settings::getFileScheme();
    $isPrivate = ($scheme === 'private');
    $requestingUid = (int) $this->currentUser()->id();
 
    foreach ($entities as $entity) {
      FolderShare::postOperationHook(
        'download',
        [
          $entity,
          $requestingUid,
        ]);
      ManageLog::activity(
        "Downloaded @kind '@name' (# @id).",
        [
          '@id'      => $entity->id(),
          '@kind'    => $entity->getKind(),
          '@name'    => $entity->getName(),
          'entity'   => $entity,
          'uid'      => $requestingUid,
        ]);
    }
 
    //
    // Respond
    // -------
    // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
    // sets response as not cacheable if the Cache-Control header is not
    // already modified. We pass in FALSE for non-private schemes for the
    // $public parameter to make sure we don't change the headers.
    return new BinaryFileResponse($uri, 200, $headers, !$isPrivate);
  }
 
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc