Migrate index.xhtml and comparison.xhtml to use centralized entities for current...
[xhtml-compiler.git] / XHTMLCompiler / Page.php
blob94c1badd947a24791ea1e1bd403e9d0360b3a6ad
1 <?php
3 /**
4 * Represents a page in our content management system. This is loosely
5 * bound to the filesystem, although it doesn't actually refer to a
6 * specific file, just a class of files.
7 */
8 class XHTMLCompiler_Page
11 /**
12 * Filename identifier of this page without extension
14 protected $pathStem;
16 /** File extension of source files (no period) */
17 protected $sourceExt = 'xhtml';
18 /** File extension of cache/served files */
19 protected $cacheExt = 'html';
20 /** File extension of dependency files */
21 protected $depsExt = 'xc-deps';
23 /** Instance of XHTMLCompiler_File for source file */
24 protected $source;
25 /** Instance of XHTMLCompiler_File for cache file */
26 protected $cache;
27 /** Instance of XHTMLCompiler_File for dependency file */
28 protected $deps;
30 /**
31 * Constructs a page object, validates filename for correctness
32 * @param $path String path filename, can be from untrusted source
33 * @param $mute Whether or not to stop the class from complaining when
34 * the source file doesn't exist. This is a stopgap measure,
35 * please replace with better exception handling.
36 * @todo Cleanup into subroutines
37 * @todo Factor out allowed_directories realpath'ing to config class
39 public function __construct($path, $mute = false) {
41 $xc = XHTMLCompiler::getInstance();
42 $php = XHTMLCompiler::getPHPWrapper();
44 // test file extension
45 $info = pathinfo($path);
46 if (
47 $info['extension'] !== $this->sourceExt &&
48 $info['extension'] !== $this->cacheExt
49 ) {
50 throw new XHTMLCompiler_Exception(403);
53 // test for directory's existence and resolve to real path
54 $dir = $info['dirname'];
55 $dir = $php->realpath($dir);
56 if ($dir === false) throw new XHTMLCompiler_Exception(403);
58 $allowed_dirs = $xc->getConf('allowed_dirs');
59 $ok = false;
61 foreach ($allowed_dirs as $allowed_dir => $recursive) {
62 $allowed_dir = $php->realpath($allowed_dir); // factor out!
63 if (!is_string($allowed_dir)) continue;
64 if ($dir === $allowed_dir) {
65 $ok = true;
66 break;
67 // slash is required to prevent $allowed_dir = 'subdir' from
68 // matching $dir = 'subdirectory', thanks Mordred!
69 } elseif (strpos($dir, $allowed_dir . '/') === 0 && $recursive) {
70 $ok = true;
71 break;
75 if (!$ok) throw new XHTMLCompiler_Exception(403);
77 // cannot use pathinfo, since PATHINFO_FILENAME is PHP 5.2.0
78 $this->pathStem = substr($path, 0, strrpos($path, '.'));
80 // setup the files
81 $this->source = new XHTMLCompiler_File($this->pathStem . '.' . $this->sourceExt);
82 $this->cache = new XHTMLCompiler_File($this->pathStem . '.' . $this->cacheExt);
83 $this->deps = new XHTMLCompiler_File($this->pathStem . '.' . $this->depsExt);
85 if (!$mute && !$this->source->exists()) {
86 // Apache may have redirected to an ErrorDocument which got directed
87 // via mod_rewrite to us, in that case, output the corresponding
88 // status code. Otherwise, we can give the regular 404.
89 $code = $php->getRedirectStatus();
90 if (!$code || $code == 200) $code = 404;
91 throw new XHTMLCompiler_Exception($code);
95 // Note: Do not use this functions internally inside the class
97 /** Returns path stem, full filename without file extension */
98 public function getPathStem() { return $this->pathStem; }
99 /** Returns relative path to cache */
100 public function getCachePath() { return $this->cache->getName(); }
101 /** Returns relative path to source */
102 public function getSourcePath() { return $this->source->getName(); }
103 /** Returns directory of the files */
104 public function getDirectory() { return $this->source->getDirectory(); }
105 /** Returns how deep from the root the file is */
106 public function getDepth() { return substr_count($this->getSourcePath(), '/'); }
108 /** Normalizes a relative path as if it were from this page's directory */
109 public function normalizePath($path) {
110 return $this->getDirectory() . '/' . $path;
114 * Returns a fully formed web path to the file
116 public function getWebPath() {
117 $xc = XHTMLCompiler::getInstance();
118 $domain = $xc->getConf('web_domain');
119 if (!$domain) {
120 throw new Exception('Configuration value web_domain must be set for command line');
122 return 'http://' . $domain .
123 $xc->getConf('web_path') . '/' . $this->cache->getName();
126 /** Returns contents of the cache/served file */
127 public function getCache() { return $this->cache->get(); }
128 /** Returns contents of the source file */
129 public function getSource() { return $this->source->get(); }
131 /** Reports whether or not cache file exists and is a file */
132 public function isCacheExistent() { return $this->cache->exists(); }
133 /** Reports whether or not source file exists and is a file */
134 public function isSourceExistent() { return $this->source->exists(); }
137 * Reports whether or not the cache is stale by comparing the file
138 * modification times between the source file and the cache file.
139 * @warning You must not call this function until you've also called
140 * isCacheExistent().
142 public function isCacheStale() {
143 if (!$this->cache->exists()) {
144 throw new Exception('Cannot check for stale cache when cache
145 does not exist, please call isCacheExistent and take
146 appropriate action with the result');
148 if ($this->source->getMTime() > $this->cache->getMTime()) return true;
149 // check dependencies
150 if (!$this->deps->exists()) return true; // we need a dependency file!
151 $deps = unserialize($this->deps->get());
152 foreach ($deps as $filename => $time) {
153 if ($time < filemtime($filename)) return true;
155 return false;
159 * Writes text to the cache file, overwriting any previous contents
160 * and creating the cache file if it doesn't exist.
161 * @param $contents String contents to write to cache
163 public function writeCache($contents) {$this->cache->write($contents);}
166 * Attempts to display contents from the cache, otherwise returns false
167 * @return True if successful, false if not.
168 * @todo Purge check needs to be factored into XHTMLCompiler
170 public function tryCache() {
171 if (
172 !isset($_GET['purge']) &&
173 $this->cache->exists() &&
174 !$this->isCacheStale()
176 // cached version is fresh, serve it. This shouldn't happen normally
177 set_response_code(200); // if we used ErrorDocument, override
178 readfile($this->getCachePath());
179 return true;
181 return false;
185 * Generates the final version of a page from the source file and writes
186 * it to the cache.
187 * @note This function needs to be extended greatly
188 * @return Generated contents from source
190 public function generate() {
191 $source = $this->source->get();
192 $xc = XHTMLCompiler::getInstance();
193 $filters = $xc->getFilterManager();
194 $contents = $filters->process($source, $this);
195 $deps = $filters->getDeps();
196 if (empty($contents)) return ''; // don't write, probably an error
197 $contents .= '<!-- generated by XHTML Compiler -->';
198 $this->cache->write($contents);
199 $this->cache->chmod(0664);
200 $this->deps->write(serialize($deps));
201 return $contents;
205 * Displays the page, either from cache or fresh regeneration.
207 public function display() {
208 if($this->tryCache()) return;
209 echo $this->generate();
212 // Subversion related functions
214 protected $svnDate, $svnRevision, $svnAuthor, $svnHeadURL, $svnHeadURLMunged;
216 public function registerSVNKeywords(
217 $date, $revision, $author, $head_url
219 $this->svnDate = $date;
220 $this->svnRevision = (int) $revision;
221 $this->svnAuthor = $author;
222 $this->svnHeadURL = $head_url;
224 protected function loadSVNKeywords() {
225 // this is an expensive function
226 // we should log calls to it
227 $raw_status = shell_exec('svn info "'.$this->getSourcePath().'"');
228 if (!$raw_status) {
229 throw new Exception('Attempt to grab SVN info for non-versioned file ' . $this->getCachePath());
231 $raw_status = str_replace("\r", '', $raw_status);
232 $raw_status = explode("\n", $raw_status);
233 $status = array();
234 foreach ($raw_status as $i => $keyval) {
235 if (empty($keyval)) continue;
236 if (!strpos($keyval, ':')) continue;
237 list($key, $value) = explode(': ', $keyval, 2);
238 $status[$key] = $value;
240 $this->svnDate = $status['Last Changed Date'];
241 $this->svnRevision = $status['Last Changed Rev'];
242 $this->svnAuthor = $status['Last Changed Author'];
243 $this->svnHeadURL = $status['URL'];
245 public function getSVNDate() {
246 if (empty($this->svnDate)) $this->loadSVNKeywords();
247 return $this->svnDate;
249 public function getSVNRevision() {
250 if (empty($this->svnRevision)) $this->loadSVNKeywords();
251 return $this->svnRevision;
253 public function getSVNAuthor() {
254 if (empty($this->svnAuthor)) $this->loadSVNKeywords();
255 return $this->svnAuthor;
258 * @warning The Head URL may not be publically accessible if
259 * svn+ssh:// or file:// protocols were used in the
260 * working copy.
262 public function getSVNHeadURL() {
263 if (empty($this->svnHeadURL)) $this->loadSVNKeywords();
264 return $this->svnHeadURL;
268 * Returns the Head URL, but munged with svn_headurl_replace to
269 * an accessible representation (see config.default.php for details)
271 public function getSVNHeadURLMunged() {
272 if (!empty($this->svnHeadURLMunged)) return $this->svnHeadURLMunged;
273 $head_url = $this->getSVNHeadURL();
274 $xc = XHTMLCompiler::getInstance();
275 $pairs = $xc->getConf('svn_headurl_munge');
276 foreach ($pairs as $pair) {
277 if (!(strpos($head_url, $pair[0]) === 0)) continue;
278 $head_url = substr_replace($head_url, $pair[1], 0, strlen($pair[0]));
279 break;
281 return $this->svnHeadURLMunged = $head_url;