Sitemap.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_View
  17. * @subpackage Helper
  18. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_View_Helper_Navigation_HelperAbstract
  24. */
  25. require_once 'Zend/View/Helper/Navigation/HelperAbstract.php';
  26. /**
  27. * Helper for printing sitemaps
  28. *
  29. * @link http://www.sitemaps.org/protocol.php
  30. *
  31. * @category Zend
  32. * @package Zend_View
  33. * @subpackage Helper
  34. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  35. * @license http://framework.zend.com/license/new-bsd New BSD License
  36. */
  37. class Zend_View_Helper_Navigation_Sitemap
  38. extends Zend_View_Helper_Navigation_HelperAbstract
  39. {
  40. /**
  41. * Namespace for the <urlset> tag
  42. *
  43. * @var string
  44. */
  45. const SITEMAP_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9';
  46. /**
  47. * Schema URL
  48. *
  49. * @var string
  50. */
  51. const SITEMAP_XSD = 'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd';
  52. /**
  53. * Whether XML output should be formatted
  54. *
  55. * @var bool
  56. */
  57. protected $_formatOutput = false;
  58. /**
  59. * Whether the XML declaration should be included in XML output
  60. *
  61. * @var bool
  62. */
  63. protected $_useXmlDeclaration = true;
  64. /**
  65. * Whether sitemap should be validated using Zend_Validate_Sitemap_*
  66. *
  67. * @var bool
  68. */
  69. protected $_useSitemapValidators = true;
  70. /**
  71. * Whether sitemap should be schema validated when generated
  72. *
  73. * @var bool
  74. */
  75. protected $_useSchemaValidation = false;
  76. /**
  77. * Server url
  78. *
  79. * @var string
  80. */
  81. protected $_serverUrl;
  82. /**
  83. * View helper entry point:
  84. * Retrieves helper and optionally sets container to operate on
  85. *
  86. * @param Zend_Navigation_Container $container [optional] container to
  87. * operate on
  88. * @return Zend_View_Helper_Navigation_Sitemap fluent interface, returns
  89. * self
  90. */
  91. public function sitemap(Zend_Navigation_Container $container = null)
  92. {
  93. if (null !== $container) {
  94. $this->setContainer($container);
  95. }
  96. return $this;
  97. }
  98. // Accessors:
  99. /**
  100. * Sets whether XML output should be formatted
  101. *
  102. * @param bool $formatOutput [optional] whether output
  103. * should be formatted. Default
  104. * is true.
  105. * @return Zend_View_Helper_Navigation_Sitemap fluent interface, returns
  106. * self
  107. */
  108. public function setFormatOutput($formatOutput = true)
  109. {
  110. $this->_formatOutput = (bool) $formatOutput;
  111. return $this;
  112. }
  113. /**
  114. * Returns whether XML output should be formatted
  115. *
  116. * @return bool whether XML output should be formatted
  117. */
  118. public function getFormatOutput()
  119. {
  120. return $this->_formatOutput;
  121. }
  122. /**
  123. * Sets whether the XML declaration should be used in output
  124. *
  125. * @param bool $useXmlDecl whether XML delcaration
  126. * should be rendered
  127. * @return Zend_View_Helper_Navigation_Sitemap fluent interface, returns
  128. * self
  129. */
  130. public function setUseXmlDeclaration($useXmlDecl)
  131. {
  132. $this->_useXmlDeclaration = (bool) $useXmlDecl;
  133. return $this;
  134. }
  135. /**
  136. * Returns whether the XML declaration should be used in output
  137. *
  138. * @return bool whether the XML declaration should be used in output
  139. */
  140. public function getUseXmlDeclaration()
  141. {
  142. return $this->_useXmlDeclaration;
  143. }
  144. /**
  145. * Sets whether sitemap should be validated using Zend_Validate_Sitemap_*
  146. *
  147. * @param bool $useSitemapValidators whether sitemap validators
  148. * should be used
  149. * @return Zend_View_Helper_Navigation_Sitemap fluent interface, returns
  150. * self
  151. */
  152. public function setUseSitemapValidators($useSitemapValidators)
  153. {
  154. $this->_useSitemapValidators = (bool) $useSitemapValidators;
  155. return $this;
  156. }
  157. /**
  158. * Returns whether sitemap should be validated using Zend_Validate_Sitemap_*
  159. *
  160. * @return bool whether sitemap should be validated using validators
  161. */
  162. public function getUseSitemapValidators()
  163. {
  164. return $this->_useSitemapValidators;
  165. }
  166. /**
  167. * Sets whether sitemap should be schema validated when generated
  168. *
  169. * @param bool $schemaValidation whether sitemap should
  170. * validated using XSD Schema
  171. * @return Zend_View_Helper_Navigation_Sitemap fluent interface, returns
  172. * self
  173. */
  174. public function setUseSchemaValidation($schemaValidation)
  175. {
  176. $this->_useSchemaValidation = (bool) $schemaValidation;
  177. return $this;
  178. }
  179. /**
  180. * Returns true if sitemap should be schema validated when generated
  181. *
  182. * @return bool
  183. */
  184. public function getUseSchemaValidation()
  185. {
  186. return $this->_useSchemaValidation;
  187. }
  188. /**
  189. * Sets server url (scheme and host-related stuff without request URI)
  190. *
  191. * E.g. http://www.example.com
  192. *
  193. * @param string $serverUrl server URL to set (only
  194. * scheme and host)
  195. * @throws Zend_Uri_Exception if invalid server URL
  196. * @return Zend_View_Helper_Navigation_Sitemap fluent interface, returns
  197. * self
  198. */
  199. public function setServerUrl($serverUrl)
  200. {
  201. require_once 'Zend/Uri.php';
  202. $uri = Zend_Uri::factory($serverUrl);
  203. $uri->setFragment('');
  204. $uri->setPath('');
  205. $uri->setQuery('');
  206. if ($uri->valid()) {
  207. $this->_serverUrl = $uri->getUri();
  208. } else {
  209. require_once 'Zend/Uri/Exception.php';
  210. $e = new Zend_Uri_Exception(sprintf(
  211. 'Invalid server URL: "%s"',
  212. $serverUrl));
  213. $e->setView($this->view);
  214. throw $e;
  215. }
  216. return $this;
  217. }
  218. /**
  219. * Returns server URL
  220. *
  221. * @return string server URL
  222. */
  223. public function getServerUrl()
  224. {
  225. if (!isset($this->_serverUrl)) {
  226. $this->_serverUrl = $this->view->serverUrl();
  227. }
  228. return $this->_serverUrl;
  229. }
  230. // Helper methods:
  231. /**
  232. * Escapes string for XML usage
  233. *
  234. * @param string $string string to escape
  235. * @return string escaped string
  236. */
  237. protected function _xmlEscape($string)
  238. {
  239. $enc = 'UTF-8';
  240. if ($this->view instanceof Zend_View_Interface
  241. && method_exists($this->view, 'getEncoding')
  242. ) {
  243. $enc = $this->view->getEncoding();
  244. }
  245. // TODO: remove check when minimum PHP version is >= 5.2.3
  246. if (version_compare(PHP_VERSION, '5.2.3', '>=')) {
  247. // do not encode existing HTML entities
  248. return htmlspecialchars($string, ENT_QUOTES, $enc, false);
  249. } else {
  250. $string = preg_replace('/&(?!(?:#\d++|[a-z]++);)/ui', '&amp;', $string);
  251. $string = str_replace(array('<', '>', '\'', '"'), array('&lt;', '&gt;', '&#39;', '&quot;'), $string);
  252. return $string;
  253. }
  254. }
  255. // Public methods:
  256. /**
  257. * Returns an escaped absolute URL for the given page
  258. *
  259. * @param Zend_Navigation_Page $page page to get URL from
  260. * @return string
  261. */
  262. public function url(Zend_Navigation_Page $page)
  263. {
  264. $href = $page->getHref();
  265. if (!isset($href{0})) {
  266. // no href
  267. return '';
  268. } elseif ($href{0} == '/') {
  269. // href is relative to root; use serverUrl helper
  270. $url = $this->getServerUrl() . $href;
  271. } elseif (preg_match('/^[a-z]+:/im', (string) $href)) {
  272. // scheme is given in href; assume absolute URL already
  273. $url = (string) $href;
  274. } else {
  275. // href is relative to current document; use url helpers
  276. $url = $this->getServerUrl()
  277. . rtrim($this->view->url(), '/') . '/'
  278. . $href;
  279. }
  280. return $this->_xmlEscape($url);
  281. }
  282. /**
  283. * Returns a DOMDocument containing the Sitemap XML for the given container
  284. *
  285. * @param Zend_Navigation_Container $container [optional] container to get
  286. * breadcrumbs from, defaults
  287. * to what is registered in the
  288. * helper
  289. * @return DOMDocument DOM representation of the
  290. * container
  291. * @throws Zend_View_Exception if schema validation is on
  292. * and the sitemap is invalid
  293. * according to the sitemap
  294. * schema, or if sitemap
  295. * validators are used and the
  296. * loc element fails validation
  297. */
  298. public function getDomSitemap(Zend_Navigation_Container $container = null)
  299. {
  300. if (null === $container) {
  301. $container = $this->getContainer();
  302. }
  303. // check if we should validate using our own validators
  304. if ($this->getUseSitemapValidators()) {
  305. require_once 'Zend/Validate/Sitemap/Changefreq.php';
  306. require_once 'Zend/Validate/Sitemap/Lastmod.php';
  307. require_once 'Zend/Validate/Sitemap/Loc.php';
  308. require_once 'Zend/Validate/Sitemap/Priority.php';
  309. // create validators
  310. $locValidator = new Zend_Validate_Sitemap_Loc();
  311. $lastmodValidator = new Zend_Validate_Sitemap_Lastmod();
  312. $changefreqValidator = new Zend_Validate_Sitemap_Changefreq();
  313. $priorityValidator = new Zend_Validate_Sitemap_Priority();
  314. }
  315. // create document
  316. $dom = new DOMDocument('1.0', 'UTF-8');
  317. $dom->formatOutput = $this->getFormatOutput();
  318. // ...and urlset (root) element
  319. $urlSet = $dom->createElementNS(self::SITEMAP_NS, 'urlset');
  320. $dom->appendChild($urlSet);
  321. // create iterator
  322. $iterator = new RecursiveIteratorIterator($container,
  323. RecursiveIteratorIterator::SELF_FIRST);
  324. $maxDepth = $this->getMaxDepth();
  325. if (is_int($maxDepth)) {
  326. $iterator->setMaxDepth($maxDepth);
  327. }
  328. $minDepth = $this->getMinDepth();
  329. if (!is_int($minDepth) || $minDepth < 0) {
  330. $minDepth = 0;
  331. }
  332. // iterate container
  333. foreach ($iterator as $page) {
  334. if ($iterator->getDepth() < $minDepth || !$this->accept($page)) {
  335. // page should not be included
  336. continue;
  337. }
  338. // get absolute url from page
  339. if (!$url = $this->url($page)) {
  340. // skip page if it has no url (rare case)
  341. continue;
  342. }
  343. // create url node for this page
  344. $urlNode = $dom->createElementNS(self::SITEMAP_NS, 'url');
  345. $urlSet->appendChild($urlNode);
  346. if ($this->getUseSitemapValidators() &&
  347. !$locValidator->isValid($url)) {
  348. require_once 'Zend/View/Exception.php';
  349. $e = new Zend_View_Exception(sprintf(
  350. 'Encountered an invalid URL for Sitemap XML: "%s"',
  351. $url));
  352. $e->setView($this->view);
  353. throw $e;
  354. }
  355. // put url in 'loc' element
  356. $urlNode->appendChild($dom->createElementNS(self::SITEMAP_NS,
  357. 'loc', $url));
  358. // add 'lastmod' element if a valid lastmod is set in page
  359. if (isset($page->lastmod)) {
  360. $lastmod = strtotime((string) $page->lastmod);
  361. // prevent 1970-01-01...
  362. if ($lastmod !== false) {
  363. $lastmod = date('c', $lastmod);
  364. }
  365. if (!$this->getUseSitemapValidators() ||
  366. $lastmodValidator->isValid($lastmod)) {
  367. $urlNode->appendChild(
  368. $dom->createElementNS(self::SITEMAP_NS, 'lastmod',
  369. $lastmod)
  370. );
  371. }
  372. }
  373. // add 'changefreq' element if a valid changefreq is set in page
  374. if (isset($page->changefreq)) {
  375. $changefreq = $page->changefreq;
  376. if (!$this->getUseSitemapValidators() ||
  377. $changefreqValidator->isValid($changefreq)) {
  378. $urlNode->appendChild(
  379. $dom->createElementNS(self::SITEMAP_NS, 'changefreq',
  380. $changefreq)
  381. );
  382. }
  383. }
  384. // add 'priority' element if a valid priority is set in page
  385. if (isset($page->priority)) {
  386. $priority = $page->priority;
  387. if (!$this->getUseSitemapValidators() ||
  388. $priorityValidator->isValid($priority)) {
  389. $urlNode->appendChild(
  390. $dom->createElementNS(self::SITEMAP_NS, 'priority',
  391. $priority)
  392. );
  393. }
  394. }
  395. }
  396. // validate using schema if specified
  397. if ($this->getUseSchemaValidation()) {
  398. if (!@$dom->schemaValidate(self::SITEMAP_XSD)) {
  399. require_once 'Zend/View/Exception.php';
  400. $e = new Zend_View_Exception(sprintf(
  401. 'Sitemap is invalid according to XML Schema at "%s"',
  402. self::SITEMAP_XSD));
  403. $e->setView($this->view);
  404. throw $e;
  405. }
  406. }
  407. return $dom;
  408. }
  409. // Zend_View_Helper_Navigation_Helper:
  410. /**
  411. * Renders helper
  412. *
  413. * Implements {@link Zend_View_Helper_Navigation_Helper::render()}.
  414. *
  415. * @param Zend_Navigation_Container $container [optional] container to
  416. * render. Default is to
  417. * render the container
  418. * registered in the helper.
  419. * @return string helper output
  420. */
  421. public function render(Zend_Navigation_Container $container = null)
  422. {
  423. $dom = $this->getDomSitemap($container);
  424. $xml = $this->getUseXmlDeclaration() ?
  425. $dom->saveXML() :
  426. $dom->saveXML($dom->documentElement);
  427. return rtrim($xml, PHP_EOL);
  428. }
  429. }