-
Notifications
You must be signed in to change notification settings - Fork 0
/
Generator.php
104 lines (75 loc) · 2.59 KB
/
Generator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php namespace Adjuvant\Sitemap;
use SitemapPHP\Sitemap as Sitemap;
class Generator extends Sitemap {
public $record = false;
public $frequency = 'monthly';
public $priority = '1.0';
protected $language = 'neutral';
protected $trackPath = null;
protected $trackFile = '.sitemap.json';
protected $host = null;
public function __construct($host = null)
{
$this->host = !is_null($host) ? $host : 'http://' . $_SERVER['SERVER_NAME'];
if( is_null($this->trackPath)) $this->trackPath = getcwd();
parent::__construct($this->host);
}
protected function getTrackFileName(){
return preg_replace("`\/{2,}`", '/', $this->trackPath . '/' . $this->trackFile);
}
protected function getTracker(){
$trackFile = $this->getTrackFileName();
if(!is_file($trackFile)) {
file_put_contents($trackFile, json_encode(array()));
}
return (object) json_decode( file_get_contents( $trackFile ));
}
public function setTrackerPath($path)
{
$this->trackPath = $path;
}
public function saveTracker($tree)
{
file_put_contents($this->getTrackFileName(), json_encode($tree, JSON_PRETTY_PRINT));
}
public function track($language = 'neutral', $url = null)
{
if($this->record){
if( is_null($url) ) $url = $_SERVER['REQUEST_URI'];
$url = preg_replace("`\/{2,}`", '/', '/' . $url);
$tree = $this->getTracker();
$oldHash = md5( json_encode($tree) );
if(empty($tree->$language)) $tree->$language = array();
if( !in_array($url, $tree->$language) ) {
array_push($tree->$language, $url);
}
$newHash = md5( json_encode($tree) );
if( $oldHash !== $newHash ) {
$this->saveTracker( $tree );
}
}
}
public function output($language = 'neutral')
{
$tree = $this->getTracker();
$hash = md5( json_encode($tree) . $this->host );
$filename = '.sitemap-' . $language. '-' . $hash . ".xml";
$trackpath = preg_replace("`\/{2,}`", '/', $this->trackPath . '/');
$xml = $trackpath . $filename;
if( ! is_file( $xml )) {
foreach (glob(".sitemap-" . $language. "-*") as $oldxmlfile) {
unlink($trackpath . $oldxmlfile);
}
$this->setPath( $trackpath);
$this->setFilename( basename($filename, '.xml') );
foreach( $tree->$language as $leaf ){
$this->addItem($leaf, $this->priority, $this->frequency);
}
$lang = strlen($language) == 2 ? $language : '';
$this->createSitemapIndex( $this->host . preg_replace("`\/{2,}`", '/', '/' . $lang . '/sitemap.xml') , 'Today');
}
header("Content-Type: application/xml; charset=utf-8");
echo file_get_contents($xml);
exit();
}
}