Initial implementation of "News" DOMFilter for blog-like pages.
[xhtml-compiler.git] / XHTMLCompiler / DOMFilter / News.php
blob57f238d98308bffa5cfe2c7c64ea6d853f848993
1 <?php
3 /**
4 * Mini blog-style filter for globbing contents of another directory
5 * and inserting summaries into a main page.
6 * @note This filter should be run before other "cosmetic" filters, as
7 * it makes major changes to page content.
8 */
9 class XHTMLCompiler_DOMFilter_News extends XHTMLCompiler_DOMFilter
11 protected $name = 'News';
12 protected $prefix = 'news';
13 public function process(DOMDocument $dom, $page, $manager) {
14 $container = $this->query("//html:div[@news:source]")->item(0);
15 if (!$container) return;
16 $source = $this->confiscateAttr($container, $this->ns, 'source');
17 $source = $page->normalizePath($source);
18 // :TODO: add DI for this
19 $fs = new FSTools();
20 $xc = XHTMLCompiler::getInstance();
21 $result = $fs->globr($source, '*.xhtml');
22 rsort($result);
23 $manager = $xc->getFilterManager();
24 // :TODO: Make this limit configurable
25 for ($i = 0, $c = count($result); $i < 5 && $i < $c; $i++) {
26 $entry = $result[$i];
27 $entryFile = new XHTMLCompiler_Page($entry);
28 $subdom = $manager->parse($entryFile->getSource(), $entryFile);
30 $entryNode = $dom->createElement('div');
31 $entryNode->setAttribute('class', 'item');
33 // Generate ID for this entry. The format is
34 // year-month-date-lc-title-with-dashes
35 $entryNode->setAttribute('id', $this->generateId($entryFile->getPathStem()));
37 // Grab the title
38 $node = $subdom->getElementsByTagName('h1')->item(0);
39 $h1 = $dom->importNode($node, true);
40 $h2 = $dom->createElement('h2');
41 $h2->setAttribute('class', 'title');
42 foreach ($h1->childNodes as $h1node) $h2->appendChild($h1node);
43 $entryNode->appendChild($h2);
45 // Grab the content
46 // :WARNING: This code apparently leaves behind an
47 // xmlns statement, although we're not quite sure why.
48 $node = $subdom->getElementById('content');
49 $node = $dom->importNode($node, true);
50 $this->confiscateAttr($node, 'id');
51 $node->setAttribute('class', 'body');
52 $entryNode->appendChild($node);
54 // Make permalink
55 $a = $dom->createElement('a');
56 $a->setAttribute('href', $entryFile->getAbsolutePath());
57 $a->appendChild($dom->createTextNode('Permalink'));
58 $entryNode->appendChild($a);
60 $container->appendChild($entryNode);
64 /**
65 * Generates an ID based on the filename of a blog entry
67 public function generateId($entry) {
68 $parts = array_slice(explode('/', $entry), -2);
69 // A very specific format: year/monthday-entry-name, like 2008/0131-foobar
70 // Arbitrary folders before that is ok.
71 $entry = 'entry-' . $parts[0] .
72 '-' . substr($parts[1], 0, 2) .
73 '-' . substr($parts[1], 2, 2) .
74 '-' . substr($parts[1], 5);
75 return $entry;