Skip to content

Instantly share code, notes, and snippets.

@emcniece
Created December 1, 2015 05:56
Show Gist options
  • Save emcniece/bcf3d902e5469613fb1c to your computer and use it in GitHub Desktop.
Save emcniece/bcf3d902e5469613fb1c to your computer and use it in GitHub Desktop.
<?php
// should be at /craft/plugins/dlfile/dlfilePlugin.php
namespace Craft;
class dlfilePlugin extends BasePlugin
{
public function getName()
{
return Craft::t('DL File');
}
public function getDescription()
{
return TemplateHelper::getRaw("Allows a file to be accessed at a given route");
}
public function getVersion()
{
return '0.1';
}
public function getDeveloper()
{
return 'Eric McNiece';
}
public function getDeveloperUrl()
{
return 'http://emc2innovation.com';
}
public function addTwigExtension()
{
require_once __DIR__."/extensions/dlfileTwigExtension.php";
return new dlfileTwigExtension();
}
}
<?php
// should be at /craft/plugins/dlfile/extensions/dlfileTwigExtension.php
namespace Craft;
class dlfileTwigExtension extends \Twig_Extension
{
protected $env;
public function getName()
{
return 'dlfile';
}
public function getFilters()
{
return array(
'dlfile' => new \Twig_Filter_Method($this, 'dlfile', array('is_safe' => array('html')))
);
}
public function getFunctions()
{
return array(
'dlfile' => new \Twig_Function_Method($this, 'dlfile', array('is_safe' => array('html')))
);
}
public function dlfile($id=null)
{
// Access the url with ?debug=true to see a dump
$debug = craft()->request->getParam('debug', false);
try {
$file = craft()->assets->getFileById($id);
if ( ! $file) {
return false;
}
$source = $file->getSource();
$sourcePath = $source->settings['path'];
$folderPath = $file->getFolder()->path;
$assetFilePath = $sourcePath.$folderPath.$file->filename;
$contents = file_get_contents($assetFilePath);
if(!$debug){
craft()->request->sendFile($assetFilePath, $contents, array(
'forceDownload' => false,
'mimeType' => 'application/pdf'
));
} else{
$output = $assetFilePath;
}
}
catch(Exception $e) {
$output = false;
}
return $output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment