3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\View\Helper\Navigation
;
13 use RecursiveIteratorIterator
;
14 use Zend\Navigation\AbstractContainer
;
15 use Zend\Navigation\Page\AbstractPage
;
16 use Zend\Stdlib\ErrorHandler
;
19 use Zend\View\Exception
;
22 * Helper for printing sitemaps
24 * @link http://www.sitemaps.org/protocol.php
26 class Sitemap
extends AbstractHelper
29 * Namespace for the <urlset> tag
33 const SITEMAP_NS
= 'http://www.sitemaps.org/schemas/sitemap/0.9';
40 const SITEMAP_XSD
= 'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd';
43 * Whether XML output should be formatted
47 protected $formatOutput = false;
57 * List of urls in the sitemap
61 protected $urls = array();
64 * Whether sitemap should be validated using Zend\Validate\Sitemap\*
68 protected $useSitemapValidators = true;
71 * Whether sitemap should be schema validated when generated
75 protected $useSchemaValidation = false;
78 * Whether the XML declaration should be included in XML output
82 protected $useXmlDeclaration = true;
87 * @param string|AbstractContainer $container container to operate on
90 public function __invoke($container = null)
92 if (null !== $container) {
93 $this->setContainer($container);
102 * Implements {@link HelperInterface::render()}.
104 * @param AbstractContainer $container [optional] container to render. Default is
105 * to render the container registered in the helper.
108 public function render($container = null)
110 $dom = $this->getDomSitemap($container);
111 $xml = $this->getUseXmlDeclaration() ?
113 $dom->saveXML($dom->documentElement
);
115 return rtrim($xml, PHP_EOL
);
119 * Returns a DOMDocument containing the Sitemap XML for the given container
121 * @param AbstractContainer $container [optional] container to get
122 * breadcrumbs from, defaults
123 * to what is registered in the
125 * @return DOMDocument DOM representation of the
127 * @throws Exception\RuntimeException if schema validation is on
128 * and the sitemap is invalid
129 * according to the sitemap
130 * schema, or if sitemap
131 * validators are used and the
132 * loc element fails validation
134 public function getDomSitemap(AbstractContainer
$container = null)
137 $this->urls
= array();
139 if (null === $container) {
140 $container = $this->getContainer();
143 // check if we should validate using our own validators
144 if ($this->getUseSitemapValidators()) {
146 $locValidator = new \Zend\Validator\Sitemap\
Loc();
147 $lastmodValidator = new \Zend\Validator\Sitemap\
Lastmod();
148 $changefreqValidator = new \Zend\Validator\Sitemap\
Changefreq();
149 $priorityValidator = new \Zend\Validator\Sitemap\
Priority();
153 $dom = new DOMDocument('1.0', 'UTF-8');
154 $dom->formatOutput
= $this->getFormatOutput();
156 // ...and urlset (root) element
157 $urlSet = $dom->createElementNS(self
::SITEMAP_NS
, 'urlset');
158 $dom->appendChild($urlSet);
161 $iterator = new RecursiveIteratorIterator($container,
162 RecursiveIteratorIterator
::SELF_FIRST
);
164 $maxDepth = $this->getMaxDepth();
165 if (is_int($maxDepth)) {
166 $iterator->setMaxDepth($maxDepth);
168 $minDepth = $this->getMinDepth();
169 if (!is_int($minDepth) ||
$minDepth < 0) {
174 foreach ($iterator as $page) {
175 if ($iterator->getDepth() < $minDepth ||
!$this->accept($page)) {
176 // page should not be included
180 // get absolute url from page
181 if (!$url = $this->url($page)) {
182 // skip page if it has no url (rare case)
183 // or already is in the sitemap
187 // create url node for this page
188 $urlNode = $dom->createElementNS(self
::SITEMAP_NS
, 'url');
189 $urlSet->appendChild($urlNode);
191 if ($this->getUseSitemapValidators()
192 && !$locValidator->isValid($url)
194 throw new Exception\
RuntimeException(sprintf(
195 'Encountered an invalid URL for Sitemap XML: "%s"',
200 // put url in 'loc' element
201 $urlNode->appendChild($dom->createElementNS(self
::SITEMAP_NS
,
204 // add 'lastmod' element if a valid lastmod is set in page
205 if (isset($page->lastmod
)) {
206 $lastmod = strtotime((string) $page->lastmod
);
208 // prevent 1970-01-01...
209 if ($lastmod !== false) {
210 $lastmod = date('c', $lastmod);
213 if (!$this->getUseSitemapValidators() ||
214 $lastmodValidator->isValid($lastmod)) {
215 $urlNode->appendChild(
216 $dom->createElementNS(self
::SITEMAP_NS
, 'lastmod',
222 // add 'changefreq' element if a valid changefreq is set in page
223 if (isset($page->changefreq
)) {
224 $changefreq = $page->changefreq
;
225 if (!$this->getUseSitemapValidators() ||
226 $changefreqValidator->isValid($changefreq)) {
227 $urlNode->appendChild(
228 $dom->createElementNS(self
::SITEMAP_NS
, 'changefreq',
234 // add 'priority' element if a valid priority is set in page
235 if (isset($page->priority
)) {
236 $priority = $page->priority
;
237 if (!$this->getUseSitemapValidators() ||
238 $priorityValidator->isValid($priority)) {
239 $urlNode->appendChild(
240 $dom->createElementNS(self
::SITEMAP_NS
, 'priority',
247 // validate using schema if specified
248 if ($this->getUseSchemaValidation()) {
249 ErrorHandler
::start();
250 $test = $dom->schemaValidate(self
::SITEMAP_XSD
);
251 $error = ErrorHandler
::stop();
253 throw new Exception\
RuntimeException(sprintf(
254 'Sitemap is invalid according to XML Schema at "%s"',
264 * Returns an escaped absolute URL for the given page
266 * @param AbstractPage $page
269 public function url(AbstractPage
$page)
271 $href = $page->getHref();
273 if (!isset($href{0})) {
276 } elseif ($href{0} == '/') {
277 // href is relative to root; use serverUrl helper
278 $url = $this->getServerUrl() . $href;
279 } elseif (preg_match('/^[a-z]+:/im', (string) $href)) {
280 // scheme is given in href; assume absolute URL already
281 $url = (string) $href;
283 // href is relative to current document; use url helpers
284 $basePathHelper = $this->getView()->plugin('basepath');
285 $curDoc = $basePathHelper();
286 $curDoc = ('/' == $curDoc) ?
'' : trim($curDoc, '/');
287 $url = rtrim($this->getServerUrl(), '/') . '/'
289 . (empty($curDoc) ?
'' : '/') . $href;
292 if (! in_array($url, $this->urls
)) {
294 $this->urls
[] = $url;
295 return $this->xmlEscape($url);
302 * Escapes string for XML usage
304 * @param string $string
307 protected function xmlEscape($string)
309 $escaper = $this->view
->plugin('escapeHtml');
310 return $escaper($string);
314 * Sets whether XML output should be formatted
316 * @param bool $formatOutput
319 public function setFormatOutput($formatOutput = true)
321 $this->formatOutput
= (bool) $formatOutput;
326 * Returns whether XML output should be formatted
330 public function getFormatOutput()
332 return $this->formatOutput
;
336 * Sets server url (scheme and host-related stuff without request URI)
338 * E.g. http://www.example.com
340 * @param string $serverUrl
342 * @throws Exception\InvalidArgumentException
344 public function setServerUrl($serverUrl)
346 $uri = Uri\UriFactory
::factory($serverUrl);
347 $uri->setFragment('');
351 if ($uri->isValid()) {
352 $this->serverUrl
= $uri->toString();
354 throw new Exception\
InvalidArgumentException(sprintf(
355 'Invalid server URL: "%s"',
368 public function getServerUrl()
370 if (!isset($this->serverUrl
)) {
371 $serverUrlHelper = $this->getView()->plugin('serverUrl');
372 $this->serverUrl
= $serverUrlHelper();
375 return $this->serverUrl
;
379 * Sets whether sitemap should be validated using Zend\Validate\Sitemap_*
381 * @param bool $useSitemapValidators
384 public function setUseSitemapValidators($useSitemapValidators)
386 $this->useSitemapValidators
= (bool) $useSitemapValidators;
391 * Returns whether sitemap should be validated using Zend\Validate\Sitemap_*
395 public function getUseSitemapValidators()
397 return $this->useSitemapValidators
;
401 * Sets whether sitemap should be schema validated when generated
403 * @param bool $schemaValidation
406 public function setUseSchemaValidation($schemaValidation)
408 $this->useSchemaValidation
= (bool) $schemaValidation;
413 * Returns true if sitemap should be schema validated when generated
417 public function getUseSchemaValidation()
419 return $this->useSchemaValidation
;
423 * Sets whether the XML declaration should be used in output
425 * @param bool $useXmlDecl
428 public function setUseXmlDeclaration($useXmlDecl)
430 $this->useXmlDeclaration
= (bool) $useXmlDecl;
435 * Returns whether the XML declaration should be used in output
439 public function getUseXmlDeclaration()
441 return $this->useXmlDeclaration
;