Mereged updates from DokuWiki 38
[sudaraka-org:dokuwiki-mods.git] / inc / Sitemapper.php
1 <?php
2 /**
3  * Sitemap handling functions
4  *
5  * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6  * @author     Michael Hamann <michael@content-space.de>
7  */
8
9 if(!defined('DOKU_INC')) die('meh.');
10
11 /**
12  * A class for building sitemaps and pinging search engines with the sitemap URL.
13  *
14  * @author Michael Hamann
15  */
16 class Sitemapper {
17     /**
18      * Builds a Google Sitemap of all public pages known to the indexer
19      *
20      * The map is placed in the cache directory named sitemap.xml.gz - This
21      * file needs to be writable!
22      *
23      * @author Michael Hamann
24      * @author Andreas Gohr
25      * @link   https://www.google.com/webmasters/sitemaps/docs/en/about.html
26      * @link   http://www.sitemaps.org/
27      */
28     public static function generate(){
29         global $conf;
30         if($conf['sitemap'] < 1 || !is_numeric($conf['sitemap'])) return false;
31
32         $sitemap = Sitemapper::getFilePath();
33
34         if(@file_exists($sitemap)){
35             if(!is_writable($sitemap)) return false;
36         }else{
37             if(!is_writable(dirname($sitemap))) return false;
38         }
39
40         if(@filesize($sitemap) &&
41            @filemtime($sitemap) > (time()-($conf['sitemap']*86400))){ // 60*60*24=86400
42             dbglog('Sitemapper::generate(): Sitemap up to date');
43             return false;
44         }
45
46         dbglog("Sitemapper::generate(): using $sitemap");
47
48         $pages = idx_get_indexer()->getPages();
49         dbglog('Sitemapper::generate(): creating sitemap using '.count($pages).' pages');
50         $items = array();
51
52         // build the sitemap items
53         foreach($pages as $id){
54             //skip hidden, non existing and restricted files
55             if(isHiddenPage($id)) continue;
56             if(auth_aclcheck($id,'','') < AUTH_READ) continue;
57             $item = SitemapItem::createFromID($id);
58             if ($item !== null)
59                 $items[] = $item;
60         }
61
62         $eventData = array('items' => &$items, 'sitemap' => &$sitemap);
63         $event = new Doku_Event('SITEMAP_GENERATE', $eventData);
64         if ($event->advise_before(true)) {
65             //save the new sitemap
66             $event->result = io_saveFile($sitemap, Sitemapper::getXML($items));
67         }
68         $event->advise_after();
69
70         return $event->result;
71     }
72
73     /**
74      * Builds the sitemap XML string from the given array auf SitemapItems.
75      *
76      * @param $items array The SitemapItems that shall be included in the sitemap.
77      * @return string The sitemap XML.
78      * @author Michael Hamann
79      */
80     private static function getXML($items) {
81         ob_start();
82         echo '<?xml version="1.0" encoding="UTF-8"?>'.NL;
83         echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'.NL;
84         foreach ($items as $item) {
85             /** @var SitemapItem $item */
86             echo $item->toXML();
87         }
88         echo '</urlset>'.NL;
89         $result = ob_get_contents();
90         ob_end_clean();
91         return $result;
92     }
93
94     /**
95      * Helper function for getting the path to the sitemap file.
96      *
97      * @return string The path to the sitemap file.
98      * @author Michael Hamann
99      */
100     public static function getFilePath() {
101         global $conf;
102
103         $sitemap = $conf['cachedir'].'/sitemap.xml';
104         if (self::sitemapIsCompressed()) {
105             $sitemap .= '.gz';
106         }
107
108         return $sitemap;
109     }
110
111     /**
112      * Helper function for checking if the sitemap is compressed
113      *
114      * @return bool If the sitemap file is compressed
115      */
116     public static function sitemapIsCompressed() {
117         global $conf;
118         return $conf['compression'] === 'bz2' || $conf['compression'] === 'gz';
119     }
120
121     /**
122      * Pings search engines with the sitemap url. Plugins can add or remove
123      * urls to ping using the SITEMAP_PING event.
124      *
125      * @author Michael Hamann
126      */
127     public static function pingSearchEngines() {
128         //ping search engines...
129         $http = new DokuHTTPClient();
130         $http->timeout = 8;
131
132         $encoded_sitemap_url = urlencode(wl('', array('do' => 'sitemap'), true, '&'));
133         $ping_urls = array(
134             'google' => 'http://www.google.com/webmasters/sitemaps/ping?sitemap='.$encoded_sitemap_url,
135             'yahoo' => 'http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=dokuwiki&url='.$encoded_sitemap_url,
136             'microsoft' => 'http://www.bing.com/webmaster/ping.aspx?siteMap='.$encoded_sitemap_url,
137         );
138
139         $data = array('ping_urls' => $ping_urls,
140                             'encoded_sitemap_url' => $encoded_sitemap_url
141         );
142         $event = new Doku_Event('SITEMAP_PING', $data);
143         if ($event->advise_before(true)) {
144             foreach ($data['ping_urls'] as $name => $url) {
145                 dbglog("Sitemapper::PingSearchEngines(): pinging $name");
146                 $resp = $http->get($url);
147                 if($http->error) dbglog("Sitemapper:pingSearchengines(): $http->error");
148                 dbglog('Sitemapper:pingSearchengines(): '.preg_replace('/[\n\r]/',' ',strip_tags($resp)));
149             }
150         }
151         $event->advise_after();
152
153         return true;
154     }
155 }
156
157 /**
158  * An item of a sitemap.
159  *
160  * @author Michael Hamann
161  */
162 class SitemapItem {
163     public $url;
164     public $lastmod;
165     public $changefreq;
166     public $priority;
167
168     /**
169      * Create a new item.
170      *
171      * @param $url string The url of the item
172      * @param $lastmod int Timestamp of the last modification
173      * @param $changefreq string How frequently the item is likely to change. Valid values: always, hourly, daily, weekly, monthly, yearly, never.
174      * @param $priority float|string The priority of the item relative to other URLs on your site. Valid values range from 0.0 to 1.0.
175      */
176     public function __construct($url, $lastmod, $changefreq = null, $priority = null) {
177         $this->url = $url;
178         $this->lastmod = $lastmod;
179         $this->changefreq = $changefreq;
180         $this->priority = $priority;
181     }
182
183     /**
184      * Helper function for creating an item for a wikipage id.
185      *
186      * @param $id string A wikipage id.
187      * @param $changefreq string How frequently the item is likely to change. Valid values: always, hourly, daily, weekly, monthly, yearly, never.
188      * @param $priority float|string The priority of the item relative to other URLs on your site. Valid values     range from 0.0 to 1.0.
189      * @return SitemapItem The sitemap item.
190      */
191     public static function createFromID($id, $changefreq = null, $priority = null) {
192         $id = trim($id);
193         $date = @filemtime(wikiFN($id));
194         if(!$date) return null;
195         return new SitemapItem(wl($id, '', true), $date, $changefreq, $priority);
196     }
197
198     /**
199      * Get the XML representation of the sitemap item.
200      *
201      * @return string The XML representation.
202      */
203     public function toXML() {
204         $result = '  <url>'.NL
205                  .'    <loc>'.hsc($this->url).'</loc>'.NL
206                  .'    <lastmod>'.date_iso8601($this->lastmod).'</lastmod>'.NL;
207         if ($this->changefreq !== null)
208             $result .= '    <changefreq>'.hsc($this->changefreq).'</changefreq>'.NL;
209         if ($this->priority !== null)
210             $result .= '    <priority>'.hsc($this->priority).'</priority>'.NL;
211         $result .= '  </url>'.NL;
212         return $result;
213     }
214 }