Split out download page (text was heavily augmented). Also:
[xhtml-compiler.git] / XHTMLCompiler / Page.php
blobf3348014e3c42bc3f58a089b993fe32dfb022d22
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 /** Instance of XHTMLCompiler_Directory for all of the above files*/
31 protected $dir;
33 /**
34 * Constructs a page object, validates filename for correctness
35 * @param $path String path filename, can be from untrusted source
36 * @param $mute Whether or not to stop the class from complaining when
37 * the source file doesn't exist. This is a stopgap measure,
38 * please replace with better exception handling.
39 * @todo Cleanup into subroutines
40 * @todo Factor out allowed_directories realpath'ing to config class
42 public function __construct($path, $mute = false) {
44 $xc = XHTMLCompiler::getInstance();
45 $php = XHTMLCompiler::getPHPWrapper();
47 // test file extension
48 $info = pathinfo($path);
49 if (
50 $info['extension'] !== $this->sourceExt &&
51 $info['extension'] !== $this->cacheExt
52 ) {
53 throw new XHTMLCompiler_Exception(403);
56 // test for directory's existence and resolve to real path
57 $dir = $info['dirname'];
58 $dir = $php->realpath($dir);
59 if ($dir === false) throw new XHTMLCompiler_Exception(403);
61 $allowed_dirs = $xc->getConf('allowed_dirs');
62 $ok = false;
64 foreach ($allowed_dirs as $allowed_dir => $recursive) {
65 $allowed_dir = $php->realpath($allowed_dir); // factor out!
66 if (!is_string($allowed_dir)) continue;
67 if ($dir === $allowed_dir) {
68 $ok = true;
69 break;
70 // slash is required to prevent $allowed_dir = 'subdir' from
71 // matching $dir = 'subdirectory', thanks Mordred!
72 } elseif (strpos($dir, $allowed_dir . '/') === 0 && $recursive) {
73 $ok = true;
74 break;
78 if (!$ok) throw new XHTMLCompiler_Exception(403);
80 // cannot use pathinfo, since PATHINFO_FILENAME is PHP 5.2.0
81 $this->pathStem = substr($path, 0, strrpos($path, '.'));
83 // setup the files
84 $this->source = new XHTMLCompiler_File($this->pathStem . '.' . $this->sourceExt);
85 $this->cache = new XHTMLCompiler_File($this->pathStem . '.' . $this->cacheExt);
86 $this->deps = new XHTMLCompiler_File($this->pathStem . '.' . $this->depsExt);
88 $this->dir = new XHTMLCompiler_Directory(dirname($this->pathStem));
90 if (!$mute && !$this->source->exists()) {
91 // Apache may have redirected to an ErrorDocument which got directed
92 // via mod_rewrite to us, in that case, output the corresponding
93 // status code. Otherwise, we can give the regular 404.
94 $code = $php->getRedirectStatus();
95 if (!$code || $code == 200) $code = 404;
96 throw new XHTMLCompiler_Exception($code);
100 // Note: Do not use this functions internally inside the class
102 /** Returns path stem, full filename without file extension */
103 public function getPathStem() { return $this->pathStem; }
104 /** Returns relative path to cache */
105 public function getCachePath() { return $this->cache->getName(); }
106 /** Returns relative path to source */
107 public function getSourcePath() { return $this->source->getName(); }
108 /** Returns XHTMLCompiler_Directory representation of directory */
109 public function getDir() { return $this->dir; }
110 /** Returns directory of the files without trailing slash */
111 public function getDirName() { return $this->dir->getName(); }
112 /** Returns directory of the files with trailing slash (unless there is none) */
113 public function getDirSName() { return $this->dir->getSName(); }
114 /** Returns how deep from the root the file is */
115 public function getDepth() { return substr_count($this->getSourcePath(), '/'); }
117 /** Normalizes a relative path as if it were from this page's directory */
118 public function normalizePath($path) {
119 return $this->getDirName() . '/' . $path;
123 * Returns a fully formed web path to the file
125 public function getWebPath() {
126 $xc = XHTMLCompiler::getInstance();
127 $domain = $xc->getConf('web_domain');
128 if (!$domain) {
129 throw new Exception('Configuration value web_domain must be set for command line');
131 return 'http://' . $domain .
132 $xc->getConf('web_path') . '/' . $this->cache->getName();
135 /** Returns contents of the cache/served file */
136 public function getCache() { return $this->cache->get(); }
137 /** Returns contents of the source file */
138 public function getSource() { return $this->source->get(); }
140 /** Reports whether or not cache file exists and is a file */
141 public function isCacheExistent() { return $this->cache->exists(); }
142 /** Reports whether or not source file exists and is a file */
143 public function isSourceExistent() { return $this->source->exists(); }
146 * Reports whether or not the cache is stale by comparing the file
147 * modification times between the source file and the cache file.
148 * @warning You must not call this function until you've also called
149 * isCacheExistent().
151 public function isCacheStale() {
152 if (!$this->cache->exists()) {
153 throw new Exception('Cannot check for stale cache when cache
154 does not exist, please call isCacheExistent and take
155 appropriate action with the result');
157 if ($this->source->getMTime() > $this->cache->getMTime()) return true;
158 // check dependencies
159 if (!$this->deps->exists()) return true; // we need a dependency file!
160 $deps = unserialize($this->deps->get());
161 foreach ($deps as $filename => $time) {
162 if ($time < filemtime($filename)) return true;
164 return false;
168 * Writes text to the cache file, overwriting any previous contents
169 * and creating the cache file if it doesn't exist.
170 * @param $contents String contents to write to cache
172 public function writeCache($contents) {$this->cache->write($contents);}
175 * Attempts to display contents from the cache, otherwise returns false
176 * @return True if successful, false if not.
177 * @todo Purge check needs to be factored into XHTMLCompiler
179 public function tryCache() {
180 if (
181 !isset($_GET['purge']) &&
182 $this->cache->exists() &&
183 !$this->isCacheStale()
185 // cached version is fresh, serve it. This shouldn't happen normally
186 set_response_code(200); // if we used ErrorDocument, override
187 readfile($this->getCachePath());
188 return true;
190 return false;
194 * Generates the final version of a page from the source file and writes
195 * it to the cache.
196 * @note This function needs to be extended greatly
197 * @return Generated contents from source
199 public function generate() {
200 $source = $this->source->get();
201 $xc = XHTMLCompiler::getInstance();
202 $filters = $xc->getFilterManager();
203 $contents = $filters->process($source, $this);
204 $deps = $filters->getDeps();
205 if (empty($contents)) return ''; // don't write, probably an error
206 $contents .= '<!-- generated by XHTML Compiler -->';
207 $this->cache->write($contents);
208 $this->cache->chmod(0664);
209 $this->deps->write(serialize($deps));
210 return $contents;
214 * Displays the page, either from cache or fresh regeneration.
216 public function display() {
217 if($this->tryCache()) return;
218 echo $this->generate();
221 // Subversion related functions
223 protected $svnDate, $svnRevision, $svnAuthor, $svnHeadURL, $svnHeadURLMunged;
225 public function registerSVNKeywords(
226 $date, $revision, $author, $head_url
228 $this->svnDate = $date;
229 $this->svnRevision = (int) $revision;
230 $this->svnAuthor = $author;
231 $this->svnHeadURL = $head_url;
233 protected function loadSVNKeywords() {
234 // this is an expensive function
235 // we should log calls to it
236 $raw_status = shell_exec('svn info "'.$this->getSourcePath().'"');
237 if (!$raw_status) {
238 throw new Exception('Attempt to grab SVN info for non-versioned file ' . $this->getCachePath());
240 $raw_status = str_replace("\r", '', $raw_status);
241 $raw_status = explode("\n", $raw_status);
242 $status = array();
243 foreach ($raw_status as $i => $keyval) {
244 if (empty($keyval)) continue;
245 if (!strpos($keyval, ':')) continue;
246 list($key, $value) = explode(': ', $keyval, 2);
247 $status[$key] = $value;
249 $this->svnDate = $status['Last Changed Date'];
250 $this->svnRevision = $status['Last Changed Rev'];
251 $this->svnAuthor = $status['Last Changed Author'];
252 $this->svnHeadURL = $status['URL'];
254 public function getSVNDate() {
255 if (empty($this->svnDate)) $this->loadSVNKeywords();
256 return $this->svnDate;
258 public function getSVNRevision() {
259 if (empty($this->svnRevision)) $this->loadSVNKeywords();
260 return $this->svnRevision;
262 public function getSVNAuthor() {
263 if (empty($this->svnAuthor)) $this->loadSVNKeywords();
264 return $this->svnAuthor;
267 * @warning The Head URL may not be publically accessible if
268 * svn+ssh:// or file:// protocols were used in the
269 * working copy.
271 public function getSVNHeadURL() {
272 if (empty($this->svnHeadURL)) $this->loadSVNKeywords();
273 return $this->svnHeadURL;
277 * Returns the Head URL, but munged with svn_headurl_replace to
278 * an accessible representation (see config.default.php for details)
280 public function getSVNHeadURLMunged() {
281 if (!empty($this->svnHeadURLMunged)) return $this->svnHeadURLMunged;
282 $head_url = $this->getSVNHeadURL();
283 $xc = XHTMLCompiler::getInstance();
284 $pairs = $xc->getConf('svn_headurl_munge');
285 foreach ($pairs as $pair) {
286 if (!(strpos($head_url, $pair[0]) === 0)) continue;
287 $head_url = substr_replace($head_url, $pair[1], 0, strlen($pair[0]));
288 break;
290 return $this->svnHeadURLMunged = $head_url;