FRED™  3.0
FRED™: Framework for Rapid and Easy Development
Proxy.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Rsi\Fred;
4 
5 /**
6  * Proxy for files that are outside of the public document root.
7  */
8 class Proxy extends Component{
9 
10  public $controllerName = 'Proxy'; //!< Controller for the proxy. Has param 'alias'.
11 
12  protected $_files = null;
13 
14  /**
15  * Create a URL for an alias.
16  * @param string $alias Alias for the file.
17  * @return string URL for the proxy call.
18  */
19  public function url($alias){
20  return $this->component('router')->reverse($this->controllerName,\Rsi\File::ext($this->files[$alias]),['alias' => $alias]);
21  }
22  /**
23  * Create a unique alias for a filename.
24  * @param string $filename
25  * @return string The generated alias.
26  */
27  public function alias($filename){
28  if(
29  array_key_exists($alias = preg_replace('/\\.\w*$/','',basename($filename)),$this->files) &&
30  ($this->files[$alias] != $filename)
31  ) $alias = md5($filename) . '-' . $alias;
32  return $alias;
33  }
34  /**
35  * Add a file to the list.
36  * @param string $filename
37  * @param string $alias Alias for the file (a unique alias will be created when empty).
38  * @return string URL for the file.
39  */
40  public function add($filename,$alias = null){
41  if(!$alias) $alias = $this->alias($filename);
42  $this->session->files = $this->_files = [$alias => $filename] + $this->files;
43  return $this->url($alias);
44  }
45  /**
46  * Serve a file.
47  * @param string $alias Alias for the file.
48  */
49  public function serve($alias){
50  if(!array_key_exists($alias,$this->files)) $this->_fred->externalError("Invalid proxy alias '$alias'");
51  header('Content-Type: ' . \Rsi\File::mime($filename = $this->files[$alias]));
52  readfile($filename);
53  $this->_fred->halt();
54  }
55 
56  protected function getFiles(){
57  if($this->_files === null) $this->_files = $this->session->files ?: $this->config('files',[]);
58  return $this->_files;
59  }
60 
61 }
alias($filename)
Create a unique alias for a filename.
Definition: Proxy.php:27
config($key, $default=null)
Retrieve a config value.
Definition: Component.php:53
add($filename, $alias=null)
Add a file to the list.
Definition: Proxy.php:40
url($alias)
Create a URL for an alias.
Definition: Proxy.php:19
Proxy for files that are outside of the public document root.
Definition: Proxy.php:8
serve($alias)
Serve a file.
Definition: Proxy.php:49
Basic component class.
Definition: Component.php:8
component($name)
Get a component (local or default).
Definition: Component.php:80
$controllerName
Controller for the proxy. Has param &#39;alias&#39;.
Definition: Proxy.php:10