summaryrefslogtreecommitdiff
path: root/src/lib/Controller.class.php
blob: 592ea2c9843697818428dde6e44368cb40ba95ba (plain)
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
<?php

class Controller {
	/**
	 * Find the best view file to include based on file extension and HTTP
	 * 'Accept' headers.
	 */
	private function _resolveView($view) {
		require_once('Mime.class.php');
		require_once('HTTP_Accept.class.php');
				
		// Make a list of candidate views
		$glob_string = VIEWPATH.'/pages/'.$view.'.*.php'; 
		$files = glob($glob_string);

		// Return false if there were no candidate views.
		if (count($files) < 1) return false;

		// $prefs is a associative array where the key is the file
		// extension, and the value is how much we like that extension.
		// Higher numbers are better.
		$prefs = array();
		
		// $accept will tell us how much we like a given mime type,
		// based on the ACCEPT constant.
		$accept = new HTTP_Accept(ACCEPT);

		// Loop through the candidate views, and record how much we
		// like each.
		foreach ($files as $file) {
			$ext = preg_replace('@[^.]*\.(.*)\.php$@','$1', $file);
			$mimes = Mime::ext2mime($ext);
			foreach ($mimes as $mime) {
				$quality = $accept->getQuality($mime);
				if (isset($final[$ext])) {
					$quality = max($final[$ext], $quality);
				}
				$prefs[$ext] = $quality;
			}
		}
		
		// Sort $prefs such that the entry with the highest value will
		// appear first.
		arsort($prefs);
		
		// Return the first entry in $prefs.
		foreach ($prefs as $ext => $quality) {
			return VIEWPATH."/pages/$view.$ext.php";
		}
	}
	
	/**
	 * Show a $view, in the most appropriate format (according to file
	 * extension and HTTP Accept header).  Pass the array $vars to the view.
	 */
	protected function showView($view, $vars=null) {
		global $VARS, $mm;
		if ($vars===null) { $vars = array(); }
		$VARS = $vars;
		$VARS['template'] = $mm->template();
		include($this->_resolveView($view));
		unset($VARS);
	}
	
	// Here be default handlers ////////////////////////////////////////////
	
	public function index($routed, $remainder) {
		header('Content-type: text/plain');
		echo " == Generic Controller Index == \n\n";
		$routed_str = implode('/', $routed);
		$remainder_str = implode('/', $remainder);
		echo "Full path: $routed_str/$remainder_str\n";
		echo "Controller path: $routed_str\n";
		echo "Remainder path: $remainder_str\n";
	}
	public function http404($routed, $remainder) {
		$this->showView('http404', array('routed'=>$routed,
		                                 'remainder'=>$remainder));
	}
}