* @license PHP License * @package WB * @subpackage content */ /** * Load base class */ WBClass::load('WBContent' ,'WBCache'); /** * Content component: FileDownload * * @version 0.1.2 * @package WB * @subpackage content */ class WBContent_FileDownload extends WBContent { /** * my parameter list * @var array */ protected $config = array( 'tmpl' => 'list', 'dir' => 'download', 'ttl' => 600 ); /** * run * * run component * * @return array parameter list */ public function run() { $path = WBParam::get('wb/dir/base') . '/' . $this->config['dir']; $cache = __CLASS__ . ':path:' . $path; $files = WBCache::get($cache); if (!$files) { $files = $this->scanDir($path); WBCache::set($cache, $files, array('ttl' => $this->config['ttl'])); } // download file $file = $this->req->get('file'); if (!empty($file)) { foreach ($files as $f) { if ($file == $f['name']) { $this->download($f); break; } } } $this->loadTemplates($this->config['tmpl']); $this->tmpl->addRows('list_entry', $files); return $this->config; } /** * receive output * * fetch output of this content component * * @return string */ public function getString() { return $this->tmpl->getParsedTemplate('snippet'); } /** * find all files in download folder * * * @param string $path * @return array $files */ protected function scanDir($path) { $files = array(); $dir = new DirectoryIterator($path); foreach ($dir as $entry) { if (!$entry->isFile()) { continue; } $files[] = array( 'name' => $entry->getFilename(), 'path' => $entry->getPathname(), 'size' => $entry->getSize(), 'changed' => $entry->getMTime(), 'md5' => md5_file($entry->getPathname()), ); } usort($files, array($this, 'compareFile')); return $files; } /** * compare file names * * Callback function for usort * * @see usort() * @param array $a * @param array $b * @return int */ protected function compareFile($a, $b) { if ($a['name'] == $b['name']) { return 0; } if ($a['name'] < $b['name']) { return -1; } return 1; } /** * Download file * * CAUTION: This method usually does not return! * If file exists, it will send file to browser and exit programme! * * @param array $file */ protected function download($file) { if (!file_exists($file['path'])) { return; } // switch off compression - otherwise complete download files are loaded to RAM WBParam::set('wb/response/compress', 0); $res = WBClass::create('WBResponse'); /** @var $res WBResponse */ $res->addStream(fopen($file['path'], 'r'), $file['md5']); $res->addHeader('Content-Type', 'application/octest-stream'); $res->addHeader('Content-Disposition', 'filename="' . $file['name']. '"'); $res->send($this->req); exit(0); } } ?>