Download.php 2.47 KB
Newer Older
Ketan's avatar
Ketan committed
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
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Downloadable\Controller;

use Magento\Downloadable\Helper\Download as DownloadHelper;
use Magento\Framework\App\Response\Http as HttpResponse;

/**
 * Download controller
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
abstract class Download extends \Magento\Framework\App\Action\Action
{
    /**
     * @var array
     */
    private $disallowedContentTypes = [
        'text/html',
    ];

    /**
     * Prepare response to output resource contents
     *
     * @param string $path         Path to resource
     * @param string $resourceType Type of resource (see Magento\Downloadable\Helper\Download::LINK_TYPE_* constants)
     * @return void
     */
    protected function _processDownload($path, $resourceType)
    {
        /* @var $helper DownloadHelper */
        $helper = $this->_objectManager->get(\Magento\Downloadable\Helper\Download::class);

        $helper->setResource($path, $resourceType);
        $fileName = $helper->getFilename();

        $contentType = $helper->getContentType();

        /** @var HttpResponse $response */
        $response = $this->getResponse();
        $response->setHttpResponseCode(
            200
        )->setHeader(
            'Pragma',
            'public',
            true
        )->setHeader(
            'Cache-Control',
            'must-revalidate, post-check=0, pre-check=0',
            true
        )->setHeader(
            'Content-type',
            $contentType,
            true
        );

        if ($fileSize = $helper->getFileSize()) {
            $response->setHeader('Content-Length', $fileSize);
        }

        $contentDisposition = $helper->getContentDisposition();
        if (!$contentDisposition || in_array($contentType, $this->disallowedContentTypes)) {
            // For security reasons we force browsers to download the file instead of opening it.
            $contentDisposition = \Magento\Framework\HTTP\Mime::DISPOSITION_ATTACHMENT;
        }

        $response->setHeader('Content-Disposition', $contentDisposition  . '; filename=' . $fileName);
        //Rendering
        $response->clearBody();
        $response->sendHeaders();

        $helper->output();
    }

    /**
     * Get link model
     *
     * @return \Magento\Downloadable\Model\Link
     */
    protected function _getLink()
    {
        return $this->_objectManager->get(\Magento\Downloadable\Model\Link::class);
    }
}