Merge pull request #94 from helpfulrobot/convert-to-psr-2

Converted to PSR-2
This commit is contained in:
Damian Mooyman 2015-12-18 10:02:57 +13:00
commit 289ed77139
5 changed files with 941 additions and 880 deletions

View File

@ -37,428 +37,443 @@
* *
* @package googlesitemaps * @package googlesitemaps
*/ */
class GoogleSitemap extends Object { class GoogleSitemap extends Object
{
/** /**
* List of {@link DataObject} class names to include. As well as the change * List of {@link DataObject} class names to include. As well as the change
* frequency and priority of each class. * frequency and priority of each class.
* *
* @var array * @var array
*/ */
private static $dataobjects = array(); private static $dataobjects = array();
/** /**
* List of custom routes to include in the sitemap (such as controller * List of custom routes to include in the sitemap (such as controller
* subclasses) as well as the change frequency and priority. * subclasses) as well as the change frequency and priority.
* *
* @var array * @var array
*/ */
private static $routes = array(); private static $routes = array();
/** /**
* Decorates the given DataObject with {@link GoogleSitemapDecorator} * Decorates the given DataObject with {@link GoogleSitemapDecorator}
* and pushes the class name to the registered DataObjects. * and pushes the class name to the registered DataObjects.
* Note that all registered DataObjects need the method AbsoluteLink(). * Note that all registered DataObjects need the method AbsoluteLink().
* *
* @param string $className name of DataObject to register * @param string $className name of DataObject to register
* @param string $changeFreq how often is this DataObject updated? * @param string $changeFreq how often is this DataObject updated?
* Possible values: * Possible values:
* always, hourly, daily, weekly, monthly, yearly, never * always, hourly, daily, weekly, monthly, yearly, never
* @param string $priority How important is this DataObject in comparison to other urls? * @param string $priority How important is this DataObject in comparison to other urls?
* Possible values: 0.1, 0.2 ... , 0.9, 1.0 * Possible values: 0.1, 0.2 ... , 0.9, 1.0
* *
* @return void * @return void
*/ */
public static function register_dataobject($className, $changeFreq = 'monthly', $priority = '0.6') { public static function register_dataobject($className, $changeFreq = 'monthly', $priority = '0.6')
if (!self::is_registered($className)) { {
$className::add_extension('GoogleSitemapExtension'); if (!self::is_registered($className)) {
$className::add_extension('GoogleSitemapExtension');
self::$dataobjects[$className] = array(
'frequency' => ($changeFreq) ? $changeFreq : 'monthly', self::$dataobjects[$className] = array(
'priority' => ($priority) ? $priority : '0.6' 'frequency' => ($changeFreq) ? $changeFreq : 'monthly',
); 'priority' => ($priority) ? $priority : '0.6'
} );
} }
}
/**
* Registers multiple dataobjects in a single line. See {@link register_dataobject} /**
* for the heavy lifting * Registers multiple dataobjects in a single line. See {@link register_dataobject}
* * for the heavy lifting
* @param array $dataobjects array of class names of DataObject to register *
* @param string $changeFreq how often is this DataObject updated? * @param array $dataobjects array of class names of DataObject to register
* Possible values: * @param string $changeFreq how often is this DataObject updated?
* always, hourly, daily, weekly, monthly, yearly, never * Possible values:
* @param string $priority How important is this DataObject in comparison to other urls? * always, hourly, daily, weekly, monthly, yearly, never
* Possible values: 0.1, 0.2 ... , 0.9, 1.0 * @param string $priority How important is this DataObject in comparison to other urls?
* * Possible values: 0.1, 0.2 ... , 0.9, 1.0
* @return void *
*/ * @return void
public static function register_dataobjects($dataobjects, $changeFreq = 'monthly', $priority = '0.6') { */
foreach($dataobjects as $obj) { public static function register_dataobjects($dataobjects, $changeFreq = 'monthly', $priority = '0.6')
self::register_dataobject($obj, $changeFreq, $priority); {
} foreach ($dataobjects as $obj) {
} self::register_dataobject($obj, $changeFreq, $priority);
}
}
/** /**
* Checks whether the given class name is already registered or not. * Checks whether the given class name is already registered or not.
* *
* @param string $className Name of DataObject to check * @param string $className Name of DataObject to check
* *
* @return bool * @return bool
*/ */
public static function is_registered($className) { public static function is_registered($className)
return isset(self::$dataobjects[$className]); {
} return isset(self::$dataobjects[$className]);
}
/**
* Unregisters a class from the sitemap. Mostly used for the test suite /**
* * Unregisters a class from the sitemap. Mostly used for the test suite
* @param string *
*/ * @param string
public static function unregister_dataobject($className) { */
unset(self::$dataobjects[$className]); public static function unregister_dataobject($className)
} {
unset(self::$dataobjects[$className]);
}
/** /**
* Clears registered {@link DataObjects}. Useful for unit tests. * Clears registered {@link DataObjects}. Useful for unit tests.
* *
* @return void * @return void
*/ */
public static function clear_registered_dataobjects() { public static function clear_registered_dataobjects()
self::$dataobjects = array(); {
} self::$dataobjects = array();
}
/** /**
* Register a given route to the sitemap list * Register a given route to the sitemap list
* *
* @param string * @param string
* @param string * @param string
* @param string * @param string
* *
* @return void * @return void
*/ */
public static function register_route($route, $changeFreq = 'monthly', $priority = '0.6') { public static function register_route($route, $changeFreq = 'monthly', $priority = '0.6')
self::$routes = array_merge(self::$routes, array( {
$route => array( self::$routes = array_merge(self::$routes, array(
'frequency' => ($changeFreq) ? $changeFreq : 'monthly', $route => array(
'priority' => ($priority) ? $priority : '0.6' 'frequency' => ($changeFreq) ? $changeFreq : 'monthly',
) 'priority' => ($priority) ? $priority : '0.6'
)); )
} ));
}
/** /**
* Registers a given list of relative urls. Will be merged with the current * Registers a given list of relative urls. Will be merged with the current
* registered routes. If you want to replace them, please call {@link clear_routes} * registered routes. If you want to replace them, please call {@link clear_routes}
* *
* @param array * @param array
* @param string * @param string
* @param string * @param string
* *
* @return void * @return void
*/ */
public static function register_routes($routes, $changeFreq = 'monthly', $priority = '0.6') { public static function register_routes($routes, $changeFreq = 'monthly', $priority = '0.6')
foreach($routes as $route) { {
self::register_route($route, $changeFreq, $priority); foreach ($routes as $route) {
} self::register_route($route, $changeFreq, $priority);
} }
}
/** /**
* Clears registered routes * Clears registered routes
* *
* @return void * @return void
*/ */
public static function clear_registered_routes() { public static function clear_registered_routes()
self::$routes = array(); {
} self::$routes = array();
}
/** /**
* Constructs the list of data to include in the rendered sitemap. Links * Constructs the list of data to include in the rendered sitemap. Links
* can include pages from the website, dataobjects (such as forum posts) * can include pages from the website, dataobjects (such as forum posts)
* as well as custom registered paths. * as well as custom registered paths.
* *
* @param string * @param string
* @param int * @param int
* *
* @return ArrayList * @return ArrayList
*/ */
public function getItems($class, $page = 1) { public function getItems($class, $page = 1)
//normalise the class name {
try { //normalise the class name
$reflectionClass = new ReflectionClass($class); try {
$class = $reflectionClass->getName(); $reflectionClass = new ReflectionClass($class);
} catch (ReflectionException $e) { $class = $reflectionClass->getName();
// this can happen when $class is GoogleSitemapRoute } catch (ReflectionException $e) {
//we should try to carry on // this can happen when $class is GoogleSitemapRoute
} //we should try to carry on
}
$output = new ArrayList(); $output = new ArrayList();
$count = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap'); $count = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap');
$filter = Config::inst()->get('GoogleSitemap', 'use_show_in_search'); $filter = Config::inst()->get('GoogleSitemap', 'use_show_in_search');
// todo migrate to extension hook or DI point for other modules to // todo migrate to extension hook or DI point for other modules to
// modify state filters // modify state filters
if(class_exists('Translatable')) { if (class_exists('Translatable')) {
Translatable::disable_locale_filter(); Translatable::disable_locale_filter();
} }
if($class == "SiteTree") { if ($class == "SiteTree") {
$filter = ($filter) ? "\"ShowInSearch\" = 1" : ""; $filter = ($filter) ? "\"ShowInSearch\" = 1" : "";
$instances = Versioned::get_by_stage('SiteTree', 'Live', $filter); $instances = Versioned::get_by_stage('SiteTree', 'Live', $filter);
} } elseif ($class == "GoogleSitemapRoute") {
else if($class == "GoogleSitemapRoute") { $instances = array_slice(self::$routes, ($page - 1) * $count, $count);
$instances = array_slice(self::$routes, ($page - 1) * $count, $count); $output = new ArrayList();
$output = new ArrayList();
if($instances) { if ($instances) {
foreach($instances as $route => $config) { foreach ($instances as $route => $config) {
$output->push(new ArrayData(array( $output->push(new ArrayData(array(
'AbsoluteLink' => Director::absoluteURL($route), 'AbsoluteLink' => Director::absoluteURL($route),
'ChangeFrequency' => $config['frequency'], 'ChangeFrequency' => $config['frequency'],
'GooglePriority' => $config['priority'] 'GooglePriority' => $config['priority']
))); )));
} }
} }
return $output; return $output;
} } else {
else { $instances = new DataList($class);
$instances = new DataList($class); }
}
$this->extend("alterDataList", $instances, $class); $this->extend("alterDataList", $instances, $class);
$instances = $instances->limit( $instances = $instances->limit(
$count, $count,
($page - 1) * $count ($page - 1) * $count
); );
if($instances) { if ($instances) {
foreach($instances as $obj) { foreach ($instances as $obj) {
if($obj->canIncludeInGoogleSitemap()) { if ($obj->canIncludeInGoogleSitemap()) {
$output->push($obj); $output->push($obj);
} }
} }
} }
return $output; return $output;
} }
/** /**
* Static interface to instance level ->getItems() for backward compatibility. * Static interface to instance level ->getItems() for backward compatibility.
* *
* @param string * @param string
* @param int * @param int
* *
* @return ArrayList * @return ArrayList
* @deprecated Please create an instance and call ->getSitemaps() instead. * @deprecated Please create an instance and call ->getSitemaps() instead.
*/ */
public static function get_items($class, $page = 1) { public static function get_items($class, $page = 1)
return static::inst()->getItems($class, $page); {
} return static::inst()->getItems($class, $page);
}
/** /**
* Returns the string frequency of edits for a particular dataobject class. * Returns the string frequency of edits for a particular dataobject class.
* *
* Frequency for {@link SiteTree} objects can be determined from the version * Frequency for {@link SiteTree} objects can be determined from the version
* history. * history.
* *
* @param string * @param string
* *
* @return string * @return string
*/ */
public static function get_frequency_for_class($class) { public static function get_frequency_for_class($class)
foreach(self::$dataobjects as $type => $config) { {
if($class == $type) { foreach (self::$dataobjects as $type => $config) {
return $config['frequency']; if ($class == $type) {
} return $config['frequency'];
} }
}
return ''; return '';
} }
/** /**
* Returns the default priority of edits for a particular dataobject class. * Returns the default priority of edits for a particular dataobject class.
* *
* @param string * @param string
* *
* @return float * @return float
*/ */
public static function get_priority_for_class($class) { public static function get_priority_for_class($class)
foreach(self::$dataobjects as $type => $config) { {
if($class == $type) { foreach (self::$dataobjects as $type => $config) {
return $config['priority']; if ($class == $type) {
} return $config['priority'];
} }
}
return 0.5; return 0.5;
} }
/** /**
* The google site map is broken down into multiple smaller files to * The google site map is broken down into multiple smaller files to
* prevent overbearing a server. By default separate {@link DataObject} * prevent overbearing a server. By default separate {@link DataObject}
* records are keep in separate files and broken down into chunks. * records are keep in separate files and broken down into chunks.
* *
* @return ArrayList * @return ArrayList
*/ */
public function getSitemaps() { public function getSitemaps()
$countPerFile = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap'); {
$sitemaps = new ArrayList(); $countPerFile = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap');
$filter = Config::inst()->get('GoogleSitemap', 'use_show_in_search'); $sitemaps = new ArrayList();
$filter = Config::inst()->get('GoogleSitemap', 'use_show_in_search');
if(class_exists('SiteTree')) { if (class_exists('SiteTree')) {
// move to extension hook. At the moment moduleexists config hook // move to extension hook. At the moment moduleexists config hook
// does not work. // does not work.
if(class_exists('Translatable')) { if (class_exists('Translatable')) {
Translatable::disable_locale_filter(); Translatable::disable_locale_filter();
} }
$filter = ($filter) ? "\"ShowInSearch\" = 1" : ""; $filter = ($filter) ? "\"ShowInSearch\" = 1" : "";
$class = 'SiteTree'; $class = 'SiteTree';
$instances = Versioned::get_by_stage($class, 'Live', $filter); $instances = Versioned::get_by_stage($class, 'Live', $filter);
$this->extend("alterDataList", $instances, $class); $this->extend("alterDataList", $instances, $class);
$count = $instances->count(); $count = $instances->count();
$neededForPage = ceil($count / $countPerFile); $neededForPage = ceil($count / $countPerFile);
for($i = 1; $i <= $neededForPage; $i++) { for ($i = 1; $i <= $neededForPage; $i++) {
$lastEdited = $instances
->limit($countPerFile, ($i - 1) * $countPerFile)
->sort(array())
->max('LastEdited');
$lastEdited = $instances $lastModified = ($lastEdited) ? date('Y-m-d', strtotime($lastEdited)) : date('Y-m-d');
->limit($countPerFile, ($i - 1) * $countPerFile)
->sort(array())
->max('LastEdited');
$lastModified = ($lastEdited) ? date('Y-m-d', strtotime($lastEdited)) : date('Y-m-d'); $sitemaps->push(new ArrayData(array(
'ClassName' => 'SiteTree',
'LastModified' => $lastModified,
'Page' => $i
)));
}
}
$sitemaps->push(new ArrayData(array( if (count(self::$dataobjects) > 0) {
'ClassName' => 'SiteTree', foreach (self::$dataobjects as $class => $config) {
'LastModified' => $lastModified, $list = new DataList($class);
'Page' => $i $list = $list->sort('LastEdited ASC');
))); $this->extend("alterDataList", $list, $class);
} $neededForClass = ceil($list->count() / $countPerFile);
}
if(count(self::$dataobjects) > 0) { for ($i = 1; $i <= $neededForClass; $i++) {
foreach(self::$dataobjects as $class => $config) { // determine the last modified date for this slice
$list = new DataList($class); $sliced = $list
$list = $list->sort('LastEdited ASC'); ->limit($countPerFile, ($i - 1) * $countPerFile)
$this->extend("alterDataList", $list, $class); ->last();
$neededForClass = ceil($list->count() / $countPerFile);
for($i = 1; $i <= $neededForClass; $i++) { $lastModified = ($sliced) ? $sliced->dbObject('LastEdited')->Format('Y-m-d') : date('Y-m-d');
// determine the last modified date for this slice
$sliced = $list
->limit($countPerFile, ($i - 1) * $countPerFile)
->last();
$lastModified = ($sliced) ? $sliced->dbObject('LastEdited')->Format('Y-m-d') : date('Y-m-d'); $sitemaps->push(new ArrayData(array(
'ClassName' => $class,
'Page' => $i,
'LastModified' => $lastModified
)));
}
}
}
$sitemaps->push(new ArrayData(array( if (count(self::$routes) > 0) {
'ClassName' => $class, $needed = ceil(count(self::$routes) / $countPerFile);
'Page' => $i,
'LastModified' => $lastModified
)));
}
}
}
if(count(self::$routes) > 0) { for ($i = 1; $i <= $needed; $i++) {
$needed = ceil(count(self::$routes) / $countPerFile); $sitemaps->push(new ArrayData(array(
'ClassName' => 'GoogleSitemapRoute',
'Page' => $i
)));
}
}
for($i = 1; $i <= $needed; $i++) { return $sitemaps;
$sitemaps->push(new ArrayData(array( }
'ClassName' => 'GoogleSitemapRoute',
'Page' => $i
)));
}
}
return $sitemaps; /**
} * Static interface to instance level ->getSitemaps() for backward compatibility.
*
* @return ArrayList
* @deprecated Please create an instance and call ->getSitemaps() instead.
*/
public static function get_sitemaps()
{
return static::inst()->getSitemaps();
}
/** /**
* Static interface to instance level ->getSitemaps() for backward compatibility. * Notifies Google about changes to your sitemap. This behavior is disabled
* * by default, to enable, read the documentation provided in the docs folder.
* @return ArrayList *
* @deprecated Please create an instance and call ->getSitemaps() instead. * After notifications have been enabled, every publish / unpublish of a page.
*/ * will notify Google of the update.
public static function get_sitemaps() { *
return static::inst()->getSitemaps(); * If the site is in development mode no ping will be sent regardless whether
} * the Google notification is enabled.
*
* @return string Response text
*/
public static function ping()
{
if (!self::enabled()) {
return false;
}
// Don't ping if the site has disabled it, or if the site is in dev mode
$active = Config::inst()->get('GoogleSitemap', 'google_notification_enabled');
/** if (!$active || Director::isDev()) {
* Notifies Google about changes to your sitemap. This behavior is disabled return;
* by default, to enable, read the documentation provided in the docs folder. }
*
* After notifications have been enabled, every publish / unpublish of a page. $location = urlencode(Controller::join_links(
* will notify Google of the update. Director::absoluteBaseURL(),
* 'sitemap.xml'
* If the site is in development mode no ping will be sent regardless whether ));
* the Google notification is enabled.
* $response = self::send_ping(
* @return string Response text "www.google.com", "/webmasters/sitemaps/ping", sprintf("sitemap=%s", $location)
*/ );
public static function ping() {
if(!self::enabled()) {
return false;
}
// Don't ping if the site has disabled it, or if the site is in dev mode
$active = Config::inst()->get('GoogleSitemap', 'google_notification_enabled');
if(!$active || Director::isDev()) { return $response;
return; }
}
$location = urlencode(Controller::join_links(
Director::absoluteBaseURL(),
'sitemap.xml'
));
$response = self::send_ping(
"www.google.com", "/webmasters/sitemaps/ping", sprintf("sitemap=%s", $location)
);
return $response; /**
} * Send an HTTP request to the host.
*
* @return String Response text
*/
protected static function send_ping($host, $path, $query)
{
$socket = fsockopen($host, 80, $errno, $error);
if (!$socket) {
return $error;
}
if ($query) {
$query = '?' . $query;
}
$request = "GET {$path}{$query} HTTP/1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n";
fwrite($socket, $request);
$response = stream_get_contents($socket);
/** return $response;
* Send an HTTP request to the host. }
*
* @return String Response text
*/
protected static function send_ping($host, $path, $query) {
$socket = fsockopen($host, 80, $errno, $error);
if (!$socket) {
return $error;
}
if ($query) {
$query = '?' . $query;
}
$request = "GET {$path}{$query} HTTP/1.1\r\nHost: $host\r\nConnection: Close\r\n\r\n";
fwrite($socket, $request);
$response = stream_get_contents($socket);
return $response; /**
} * Is GoogleSitemap enabled?
*
/** * @return boolean
* Is GoogleSitemap enabled? */
* public static function enabled()
* @return boolean {
*/ return (Config::inst()->get('GoogleSitemap', 'enabled', Config::INHERITED));
public static function enabled() { }
return (Config::inst()->get('GoogleSitemap', 'enabled', Config::INHERITED));
}
/** /**
* Convenience method for manufacturing an instance for hew instance-level methods (and for easier type definition). * Convenience method for manufacturing an instance for hew instance-level methods (and for easier type definition).
* *
* @return GoogleSitemap * @return GoogleSitemap
*/ */
public static function inst() { public static function inst()
return GoogleSitemap::create(); {
} return GoogleSitemap::create();
}
} }

View File

@ -12,65 +12,68 @@
* *
* @package googlesitemaps * @package googlesitemaps
*/ */
class GoogleSitemapController extends Controller { class GoogleSitemapController extends Controller
{
/** /**
* @var array * @var array
*/ */
private static $allowed_actions = array( private static $allowed_actions = array(
'index', 'index',
'sitemap' 'sitemap'
); );
/** /**
* Default controller action for the sitemap.xml file. Renders a index * Default controller action for the sitemap.xml file. Renders a index
* file containing a list of links to sub sitemaps containing the data. * file containing a list of links to sub sitemaps containing the data.
* *
* @return mixed * @return mixed
*/ */
public function index($url) { public function index($url)
if(GoogleSitemap::enabled()) { {
Config::inst()->update('SSViewer', 'set_source_file_comments', false); if (GoogleSitemap::enabled()) {
Config::inst()->update('SSViewer', 'set_source_file_comments', false);
$this->getResponse()->addHeader('Content-Type', 'application/xml; charset="utf-8"');
$this->getResponse()->addHeader('X-Robots-Tag', 'noindex'); $this->getResponse()->addHeader('Content-Type', 'application/xml; charset="utf-8"');
$this->getResponse()->addHeader('X-Robots-Tag', 'noindex');
$sitemaps = GoogleSitemap::inst()->getSitemaps(); $sitemaps = GoogleSitemap::inst()->getSitemaps();
$this->extend('updateGoogleSitemaps', $sitemaps); $this->extend('updateGoogleSitemaps', $sitemaps);
return array( return array(
'Sitemaps' => $sitemaps 'Sitemaps' => $sitemaps
); );
} else { } else {
return new SS_HTTPResponse('Page not found', 404); return new SS_HTTPResponse('Page not found', 404);
} }
} }
/** /**
* Specific controller action for displaying a particular list of links * Specific controller action for displaying a particular list of links
* for a class * for a class
* *
* @return mixed * @return mixed
*/ */
public function sitemap() { public function sitemap()
$class = $this->request->param('ID'); {
$page = $this->request->param('OtherID'); $class = $this->request->param('ID');
$page = $this->request->param('OtherID');
if(GoogleSitemap::enabled() && $class && $page) { if (GoogleSitemap::enabled() && $class && $page) {
Config::inst()->update('SSViewer', 'set_source_file_comments', false); Config::inst()->update('SSViewer', 'set_source_file_comments', false);
$this->getResponse()->addHeader('Content-Type', 'application/xml; charset="utf-8"'); $this->getResponse()->addHeader('Content-Type', 'application/xml; charset="utf-8"');
$this->getResponse()->addHeader('X-Robots-Tag', 'noindex'); $this->getResponse()->addHeader('X-Robots-Tag', 'noindex');
$items = GoogleSitemap::inst()->getItems($class, $page); $items = GoogleSitemap::inst()->getItems($class, $page);
$this->extend('updateGoogleSitemapItems', $items, $class, $page); $this->extend('updateGoogleSitemapItems', $items, $class, $page);
return array( return array(
'Items' => $items 'Items' => $items
); );
} else { } else {
return new SS_HTTPResponse('Page not found', 404); return new SS_HTTPResponse('Page not found', 404);
} }
} }
} }

View File

@ -6,111 +6,117 @@
* *
* @package googlesitemaps * @package googlesitemaps
*/ */
class GoogleSitemapExtension extends DataExtension { class GoogleSitemapExtension extends DataExtension
{
/** /**
* @return boolean * @return boolean
*/ */
public function canIncludeInGoogleSitemap() { public function canIncludeInGoogleSitemap()
$can = true; {
$can = true;
if($this->owner->hasMethod('AbsoluteLink')) { if ($this->owner->hasMethod('AbsoluteLink')) {
$hostHttp = parse_url(Director::protocolAndHost(), PHP_URL_HOST); $hostHttp = parse_url(Director::protocolAndHost(), PHP_URL_HOST);
$objHttp = parse_url($this->owner->AbsoluteLink(), PHP_URL_HOST); $objHttp = parse_url($this->owner->AbsoluteLink(), PHP_URL_HOST);
if($objHttp != $hostHttp) { if ($objHttp != $hostHttp) {
$can = false; $can = false;
} }
} }
if($can) { if ($can) {
$can = $this->owner->canView(); $can = $this->owner->canView();
} }
if($can) { if ($can) {
$can = $this->owner->getGooglePriority(); $can = $this->owner->getGooglePriority();
} }
$this->owner->invokeWithExtensions('alterCanIncludeInGoogleSitemap', $can); $this->owner->invokeWithExtensions('alterCanIncludeInGoogleSitemap', $can);
return $can; return $can;
} }
/** /**
* @return void * @return void
*/ */
public function onAfterPublish() { public function onAfterPublish()
GoogleSitemap::ping(); {
} GoogleSitemap::ping();
}
/** /**
* @return void * @return void
*/ */
public function onAfterUnpublish() { public function onAfterUnpublish()
GoogleSitemap::ping(); {
} GoogleSitemap::ping();
}
/** /**
* The default value of the priority field depends on the depth of the page in * The default value of the priority field depends on the depth of the page in
* the site tree, so it must be calculated dynamically. * the site tree, so it must be calculated dynamically.
* *
* @return mixed * @return mixed
*/ */
public function getGooglePriority() { public function getGooglePriority()
$field = $this->owner->hasField('Priority'); {
$field = $this->owner->hasField('Priority');
if(isset($this->Priority) || ($field && $this->Priority = $this->owner->getField('Priority'))) { if (isset($this->Priority) || ($field && $this->Priority = $this->owner->getField('Priority'))) {
return ($this->Priority < 0) ? false : $this->Priority; return ($this->Priority < 0) ? false : $this->Priority;
} }
return GoogleSitemap::get_priority_for_class($this->owner->class); return GoogleSitemap::get_priority_for_class($this->owner->class);
} }
/** /**
* Returns a pages change frequency calculated by pages age and number of * Returns a pages change frequency calculated by pages age and number of
* versions. Google expects always, hourly, daily, weekly, monthly, yearly * versions. Google expects always, hourly, daily, weekly, monthly, yearly
* or never as values. * or never as values.
* *
* @see http://support.google.com/webmasters/bin/answer.py?hl=en&answer=183668&topic=8476&ctx=topic * @see http://support.google.com/webmasters/bin/answer.py?hl=en&answer=183668&topic=8476&ctx=topic
* *
* @return SS_Datetime * @return SS_Datetime
*/ */
public function getChangeFrequency() { public function getChangeFrequency()
if($freq = GoogleSitemap::get_frequency_for_class($this->owner->class)) { {
return $freq; if ($freq = GoogleSitemap::get_frequency_for_class($this->owner->class)) {
} return $freq;
}
$date = date('Y-m-d H:i:s'); $date = date('Y-m-d H:i:s');
$created = new SS_Datetime(); $created = new SS_Datetime();
$created->value = ($this->owner->Created) ? $this->owner->Created : $date; $created->value = ($this->owner->Created) ? $this->owner->Created : $date;
$now = new SS_Datetime(); $now = new SS_Datetime();
$now->value = $date; $now->value = $date;
$versions = ($this->owner->Version) ? $this->owner->Version : 1; $versions = ($this->owner->Version) ? $this->owner->Version : 1;
$timediff = $now->format('U') - $created->format('U'); $timediff = $now->format('U') - $created->format('U');
// Check how many revisions have been made over the lifetime of the // Check how many revisions have been made over the lifetime of the
// Page for a rough estimate of it's changing frequency. // Page for a rough estimate of it's changing frequency.
$period = $timediff / ($versions + 1); $period = $timediff / ($versions + 1);
if ($period > 60 * 60 * 24 * 365) { if ($period > 60 * 60 * 24 * 365) {
$freq = 'yearly'; $freq = 'yearly';
} elseif ($period > 60 * 60 * 24 * 30) { } elseif ($period > 60 * 60 * 24 * 30) {
$freq = 'monthly'; $freq = 'monthly';
} elseif ($period > 60 * 60 * 24 * 7) { } elseif ($period > 60 * 60 * 24 * 7) {
$freq = 'weekly'; $freq = 'weekly';
} elseif ($period > 60 * 60 * 24) { } elseif ($period > 60 * 60 * 24) {
$freq = 'daily'; $freq = 'daily';
} elseif ($period > 60 * 60) { } elseif ($period > 60 * 60) {
$freq = 'hourly'; $freq = 'hourly';
} else { } else {
$freq = 'always'; $freq = 'always';
} }
return $freq; return $freq;
} }
} }

View File

@ -3,111 +3,123 @@
/** /**
* @package googlesitemaps * @package googlesitemaps
*/ */
class GoogleSitemapSiteTreeExtension extends GoogleSitemapExtension { class GoogleSitemapSiteTreeExtension extends GoogleSitemapExtension
{
/** /**
* @var array * @var array
*/ */
private static $db = array( private static $db = array(
"Priority" => "Varchar(5)" "Priority" => "Varchar(5)"
); );
/** /**
* @param FieldList * @param FieldList
*/ */
public function updateSettingsFields(&$fields) { public function updateSettingsFields(&$fields)
$prorities = array( {
'-1' => _t('GoogleSitemaps.PRIORITYNOTINDEXED', "Not indexed"), $prorities = array(
'1.0' => '1 - ' . _t('GoogleSitemaps.PRIORITYMOSTIMPORTANT', "Most important"), '-1' => _t('GoogleSitemaps.PRIORITYNOTINDEXED', "Not indexed"),
'0.9' => '2', '1.0' => '1 - ' . _t('GoogleSitemaps.PRIORITYMOSTIMPORTANT', "Most important"),
'0.8' => '3', '0.9' => '2',
'0.7' => '4', '0.8' => '3',
'0.6' => '5', '0.7' => '4',
'0.5' => '6', '0.6' => '5',
'0.4' => '7', '0.5' => '6',
'0.3' => '8', '0.4' => '7',
'0.2' => '9', '0.3' => '8',
'0.1' => '10 - ' . _t('GoogleSitemaps.PRIORITYLEASTIMPORTANT', "Least important") '0.2' => '9',
); '0.1' => '10 - ' . _t('GoogleSitemaps.PRIORITYLEASTIMPORTANT', "Least important")
);
$tabset = $fields->findOrMakeTab('Root.Settings'); $tabset = $fields->findOrMakeTab('Root.Settings');
$message = "<p>"; $message = "<p>";
$message .= sprintf(_t('GoogleSitemaps.METANOTEPRIORITY', "Manually specify a Google Sitemaps priority for this page (%s)"), $message .= sprintf(_t('GoogleSitemaps.METANOTEPRIORITY', "Manually specify a Google Sitemaps priority for this page (%s)"),
'<a href="http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=71936#prioritize" target="_blank">?</a>' '<a href="http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=71936#prioritize" target="_blank">?</a>'
); );
$message .= "</p>"; $message .= "</p>";
$tabset->push(new Tab('GoogleSitemap', _t('GoogleSitemaps.TABGOOGLESITEMAP', 'Google Sitemap'), $tabset->push(new Tab('GoogleSitemap', _t('GoogleSitemaps.TABGOOGLESITEMAP', 'Google Sitemap'),
new LiteralField("GoogleSitemapIntro", $message), new LiteralField("GoogleSitemapIntro", $message),
$priority = new DropdownField("Priority", $this->owner->fieldLabel('Priority'), $prorities, $this->owner->Priority) $priority = new DropdownField("Priority", $this->owner->fieldLabel('Priority'), $prorities, $this->owner->Priority)
)); ));
$priority->setEmptyString(_t('GoogleSitemaps.PRIORITYAUTOSET', 'Auto-set based on page depth')); $priority->setEmptyString(_t('GoogleSitemaps.PRIORITYAUTOSET', 'Auto-set based on page depth'));
} }
/** /**
* @param FieldList * @param FieldList
* *
* @return void * @return void
*/ */
public function updateFieldLabels(&$labels) { public function updateFieldLabels(&$labels)
parent::updateFieldLabels($labels); {
parent::updateFieldLabels($labels);
$labels['Priority'] = _t('GoogleSitemaps.METAPAGEPRIO', "Page Priority"); $labels['Priority'] = _t('GoogleSitemaps.METAPAGEPRIO', "Page Priority");
} }
/** /**
* Ensure that all parent pages of this page (if any) are published * Ensure that all parent pages of this page (if any) are published
* *
* @return boolean * @return boolean
*/ */
public function hasPublishedParent() { public function hasPublishedParent()
{
// Skip root pages
if(empty($this->owner->ParentID)) return true; // Skip root pages
if (empty($this->owner->ParentID)) {
// Ensure direct parent exists return true;
$parent = $this->owner->Parent(); }
if(empty($parent) || !$parent->exists()) return false;
// Ensure direct parent exists
// Check ancestry $parent = $this->owner->Parent();
return $parent->hasPublishedParent(); if (empty($parent) || !$parent->exists()) {
} return false;
}
// Check ancestry
return $parent->hasPublishedParent();
}
/** /**
* @return boolean * @return boolean
*/ */
public function canIncludeInGoogleSitemap() { public function canIncludeInGoogleSitemap()
{
// Check that parent page is published
if(!$this->owner->hasPublishedParent()) return false; // Check that parent page is published
if (!$this->owner->hasPublishedParent()) {
$result = parent::canIncludeInGoogleSitemap(); return false;
$result = ($this->owner instanceof ErrorPage) ? false : $result; }
$result = parent::canIncludeInGoogleSitemap();
$result = ($this->owner instanceof ErrorPage) ? false : $result;
return $result; return $result;
} }
/** /**
* @return mixed * @return mixed
*/ */
public function getGooglePriority() { public function getGooglePriority()
setlocale(LC_ALL, "en_US.UTF8"); {
$priority = $this->owner->getField('Priority'); setlocale(LC_ALL, "en_US.UTF8");
$priority = $this->owner->getField('Priority');
if(!$priority) { if (!$priority) {
$parentStack = $this->owner->parentStack(); $parentStack = $this->owner->parentStack();
$numParents = is_array($parentStack) ? count($parentStack) - 1 : 0; $numParents = is_array($parentStack) ? count($parentStack) - 1 : 0;
$num = max(0.1, 1.0 - ($numParents / 10)); $num = max(0.1, 1.0 - ($numParents / 10));
$result = str_replace(",", ".", $num); $result = str_replace(",", ".", $num);
return $result; return $result;
} else if ($priority == -1) { } elseif ($priority == -1) {
return false; return false;
} else { } else {
return (is_numeric($priority) && $priority <= 1.0) ? $priority : 0.5; return (is_numeric($priority) && $priority <= 1.0) ? $priority : 0.5;
} }
} }
} }

View File

@ -6,350 +6,375 @@
* @package googlesitemaps * @package googlesitemaps
* @subpackage tests * @subpackage tests
*/ */
class GoogleSitemapTest extends FunctionalTest { class GoogleSitemapTest extends FunctionalTest
{
public static $fixture_file = 'googlesitemaps/tests/GoogleSitemapTest.yml'; public static $fixture_file = 'googlesitemaps/tests/GoogleSitemapTest.yml';
protected $extraDataObjects = array( protected $extraDataObjects = array(
'GoogleSitemapTest_DataObject', 'GoogleSitemapTest_DataObject',
'GoogleSitemapTest_OtherDataObject', 'GoogleSitemapTest_OtherDataObject',
'GoogleSitemapTest_UnviewableDataObject' 'GoogleSitemapTest_UnviewableDataObject'
); );
public function setUp() { public function setUp()
parent::setUp(); {
parent::setUp();
if(class_exists('Page')) { if (class_exists('Page')) {
$this->loadFixture('googlesitemaps/tests/GoogleSitemapPageTest.yml'); $this->loadFixture('googlesitemaps/tests/GoogleSitemapPageTest.yml');
} }
GoogleSitemap::clear_registered_dataobjects(); GoogleSitemap::clear_registered_dataobjects();
GoogleSitemap::clear_registered_routes(); GoogleSitemap::clear_registered_routes();
} }
public function tearDown() { public function tearDown()
parent::tearDown(); {
parent::tearDown();
GoogleSitemap::clear_registered_dataobjects(); GoogleSitemap::clear_registered_dataobjects();
GoogleSitemap::clear_registered_routes(); GoogleSitemap::clear_registered_routes();
} }
public function testIndexFileWithCustomRoute() { public function testIndexFileWithCustomRoute()
GoogleSitemap::register_route('/test/'); {
GoogleSitemap::register_route('/test/');
$response = $this->get('sitemap.xml'); $response = $this->get('sitemap.xml');
$body = $response->getBody(); $body = $response->getBody();
$expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapRoute/1") ."</loc>"; $expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapRoute/1") ."</loc>";
$this->assertEquals(1, substr_count($body, $expected) , 'A link to the custom routes exists'); $this->assertEquals(1, substr_count($body, $expected), 'A link to the custom routes exists');
} }
public function testGetItems() { public function testGetItems()
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject", ''); {
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject", '');
$items = GoogleSitemap::get_items('GoogleSitemapTest_DataObject', 1); $items = GoogleSitemap::get_items('GoogleSitemapTest_DataObject', 1);
$this->assertEquals(2, $items->count()); $this->assertEquals(2, $items->count());
$this->assertDOSEquals(array( $this->assertDOSEquals(array(
array("Priority" => "0.2"), array("Priority" => "0.2"),
array("Priority" => "0.4") array("Priority" => "0.4")
), $items); ), $items);
GoogleSitemap::register_dataobject("GoogleSitemapTest_OtherDataObject"); GoogleSitemap::register_dataobject("GoogleSitemapTest_OtherDataObject");
$this->assertEquals(1, GoogleSitemap::get_items('GoogleSitemapTest_OtherDataObject', 1)->count()); $this->assertEquals(1, GoogleSitemap::get_items('GoogleSitemapTest_OtherDataObject', 1)->count());
GoogleSitemap::register_dataobject("GoogleSitemapTest_UnviewableDataObject"); GoogleSitemap::register_dataobject("GoogleSitemapTest_UnviewableDataObject");
$this->assertEquals(0, GoogleSitemap::get_items('GoogleSitemapTest_UnviewableDataObject', 1)->count()); $this->assertEquals(0, GoogleSitemap::get_items('GoogleSitemapTest_UnviewableDataObject', 1)->count());
} }
public function testGetItemsWithCustomRoutes() { public function testGetItemsWithCustomRoutes()
GoogleSitemap::register_routes(array( {
'/test-route/', GoogleSitemap::register_routes(array(
'/someother-route/', '/test-route/',
'/fake-sitemap-route/' '/someother-route/',
)); '/fake-sitemap-route/'
));
$items = GoogleSitemap::get_items('GoogleSitemapRoute', 1); $items = GoogleSitemap::get_items('GoogleSitemapRoute', 1);
$this->assertEquals(3, $items->count()); $this->assertEquals(3, $items->count());
} }
public function testAccessingSitemapRootXMLFile() { public function testAccessingSitemapRootXMLFile()
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject"); {
GoogleSitemap::register_dataobject("GoogleSitemapTest_OtherDataObject"); GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject");
GoogleSitemap::register_dataobject("GoogleSitemapTest_OtherDataObject");
$response = $this->get('sitemap.xml'); $response = $this->get('sitemap.xml');
$body = $response->getBody(); $body = $response->getBody();
// the sitemap should contain <loc> to both those files and not the other // the sitemap should contain <loc> to both those files and not the other
// dataobject as it hasn't been registered // dataobject as it hasn't been registered
$expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1") ."</loc>"; $expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1") ."</loc>";
$this->assertEquals(1, substr_count($body, $expected) , 'A link to GoogleSitemapTest_DataObject exists'); $this->assertEquals(1, substr_count($body, $expected), 'A link to GoogleSitemapTest_DataObject exists');
$expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_OtherDataObject/1") ."</loc>"; $expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_OtherDataObject/1") ."</loc>";
$this->assertEquals(1, substr_count($body, $expected) , 'A link to GoogleSitemapTest_OtherDataObject exists'); $this->assertEquals(1, substr_count($body, $expected), 'A link to GoogleSitemapTest_OtherDataObject exists');
$expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_UnviewableDataObject/2") ."</loc>"; $expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_UnviewableDataObject/2") ."</loc>";
$this->assertEquals(0, substr_count($body, $expected) , 'A link to a GoogleSitemapTest_UnviewableDataObject does not exist'); $this->assertEquals(0, substr_count($body, $expected), 'A link to a GoogleSitemapTest_UnviewableDataObject does not exist');
} }
public function testLastModifiedDateOnRootXML() { public function testLastModifiedDateOnRootXML()
Config::inst()->update('GoogleSitemap', 'enabled', true); {
Config::inst()->update('GoogleSitemap', 'enabled', true);
if(!class_exists('Page')) { if (!class_exists('Page')) {
$this->markTestIncomplete('No cms module installed, page related test skipped'); $this->markTestIncomplete('No cms module installed, page related test skipped');
} }
$page = $this->objFromFixture('Page', 'Page1'); $page = $this->objFromFixture('Page', 'Page1');
$page->publish('Stage', 'Live'); $page->publish('Stage', 'Live');
$page->flushCache(); $page->flushCache();
$page2 = $this->objFromFixture('Page', 'Page2'); $page2 = $this->objFromFixture('Page', 'Page2');
$page2->publish('Stage', 'Live'); $page2->publish('Stage', 'Live');
$page2->flushCache(); $page2->flushCache();
DB::query("UPDATE \"SiteTree_Live\" SET \"LastEdited\"='2014-03-14 00:00:00' WHERE \"ID\"='".$page->ID."'"); DB::query("UPDATE \"SiteTree_Live\" SET \"LastEdited\"='2014-03-14 00:00:00' WHERE \"ID\"='".$page->ID."'");
DB::query("UPDATE \"SiteTree_Live\" SET \"LastEdited\"='2014-01-01 00:00:00' WHERE \"ID\"='".$page2->ID."'"); DB::query("UPDATE \"SiteTree_Live\" SET \"LastEdited\"='2014-01-01 00:00:00' WHERE \"ID\"='".$page2->ID."'");
$response = $this->get('sitemap.xml'); $response = $this->get('sitemap.xml');
$body = $response->getBody(); $body = $response->getBody();
$expected = '<lastmod>2014-03-14</lastmod>'; $expected = '<lastmod>2014-03-14</lastmod>';
$this->assertEquals(1, substr_count($body, $expected) , 'The last mod date should use most recent LastEdited date'); $this->assertEquals(1, substr_count($body, $expected), 'The last mod date should use most recent LastEdited date');
} }
public function testIndexFilePaginatedSitemapFiles() { public function testIndexFilePaginatedSitemapFiles()
$original = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap'); {
Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', 1); $original = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap');
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject"); Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', 1);
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject");
$response = $this->get('sitemap.xml'); $response = $this->get('sitemap.xml');
$body = $response->getBody(); $body = $response->getBody();
$expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1") ."</loc>"; $expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1") ."</loc>";
$this->assertEquals(1, substr_count($body, $expected) , 'A link to the first page of GoogleSitemapTest_DataObject exists'); $this->assertEquals(1, substr_count($body, $expected), 'A link to the first page of GoogleSitemapTest_DataObject exists');
$expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_DataObject/2") ."</loc>"; $expected = "<loc>". Director::absoluteURL("sitemap.xml/sitemap/GoogleSitemapTest_DataObject/2") ."</loc>";
$this->assertEquals(1, substr_count($body, $expected) , 'A link to the second page GoogleSitemapTest_DataObject exists'); $this->assertEquals(1, substr_count($body, $expected), 'A link to the second page GoogleSitemapTest_DataObject exists');
Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', $original); Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', $original);
} }
public function testRegisterRoutesIncludesAllRoutes() { public function testRegisterRoutesIncludesAllRoutes()
GoogleSitemap::register_route('/test/'); {
GoogleSitemap::register_routes(array( GoogleSitemap::register_route('/test/');
'/test/', // duplication should be replaced GoogleSitemap::register_routes(array(
'/unittests/', '/test/', // duplication should be replaced
'/anotherlink/' '/unittests/',
), 'weekly'); '/anotherlink/'
), 'weekly');
$response = $this->get('sitemap.xml/sitemap/GoogleSitemapRoute/1'); $response = $this->get('sitemap.xml/sitemap/GoogleSitemapRoute/1');
$body = $response->getBody(); $body = $response->getBody();
$this->assertEquals(200, $response->getStatusCode(), 'successful loaded nested sitemap'); $this->assertEquals(200, $response->getStatusCode(), 'successful loaded nested sitemap');
$this->assertEquals(3, substr_count($body, "<loc>")); $this->assertEquals(3, substr_count($body, "<loc>"));
} }
public function testAccessingNestedSiteMap() { public function testAccessingNestedSiteMap()
$original = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap'); {
Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', 1); $original = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap');
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject"); Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', 1);
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject");
$response = $this->get('sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1'); $response = $this->get('sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1');
$body = $response->getBody(); $body = $response->getBody();
$this->assertEquals(200, $response->getStatusCode(), 'successful loaded nested sitemap'); $this->assertEquals(200, $response->getStatusCode(), 'successful loaded nested sitemap');
Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', $original); Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', $original);
} }
public function testAccessingNestedSiteMapCaseInsensitive() { public function testAccessingNestedSiteMapCaseInsensitive()
$original = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap'); {
Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', 1); $original = Config::inst()->get('GoogleSitemap', 'objects_per_sitemap');
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject"); Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', 1);
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject");
$response = $this->get('sitemap.xml/sitemap/googlesitemaptest_dataobject/1'); $response = $this->get('sitemap.xml/sitemap/googlesitemaptest_dataobject/1');
$body = $response->getBody(); $body = $response->getBody();
$this->assertEquals(200, $response->getStatusCode(), 'successful loaded nested sitemap'); $this->assertEquals(200, $response->getStatusCode(), 'successful loaded nested sitemap');
Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', $original); Config::inst()->update('GoogleSitemap', 'objects_per_sitemap', $original);
} }
public function testGetItemsWithPages() { public function testGetItemsWithPages()
if(!class_exists('Page')) { {
$this->markTestIncomplete('No cms module installed, page related test skipped'); if (!class_exists('Page')) {
} $this->markTestIncomplete('No cms module installed, page related test skipped');
}
$page = $this->objFromFixture('Page', 'Page1');
$page->publish('Stage', 'Live'); $page = $this->objFromFixture('Page', 'Page1');
$page->flushCache(); $page->publish('Stage', 'Live');
$page->flushCache();
$page2 = $this->objFromFixture('Page', 'Page2');
$page2->publish('Stage', 'Live'); $page2 = $this->objFromFixture('Page', 'Page2');
$page2->flushCache(); $page2->publish('Stage', 'Live');
$page2->flushCache();
$this->assertDOSContains(array( $this->assertDOSContains(array(
array('Title' => 'Testpage1'), array('Title' => 'Testpage1'),
array('Title' => 'Testpage2') array('Title' => 'Testpage2')
), GoogleSitemap::get_items('SiteTree'), "There should be 2 pages in the sitemap after publishing"); ), GoogleSitemap::get_items('SiteTree'), "There should be 2 pages in the sitemap after publishing");
// check if we make a page readonly that it is hidden // check if we make a page readonly that it is hidden
$page2->CanViewType = 'LoggedInUsers'; $page2->CanViewType = 'LoggedInUsers';
$page2->write(); $page2->write();
$page2->publish('Stage', 'Live'); $page2->publish('Stage', 'Live');
$this->session()->inst_set('loggedInAs', null); $this->session()->inst_set('loggedInAs', null);
$this->assertDOSEquals(array( $this->assertDOSEquals(array(
array('Title' => 'Testpage1') array('Title' => 'Testpage1')
), GoogleSitemap::get_items('SiteTree'), "There should be only 1 page, other is logged in only"); ), GoogleSitemap::get_items('SiteTree'), "There should be only 1 page, other is logged in only");
} }
public function testAccess() { public function testAccess()
Config::inst()->update('GoogleSitemap', 'enabled', true); {
Config::inst()->update('GoogleSitemap', 'enabled', true);
$response = $this->get('sitemap.xml');
$response = $this->get('sitemap.xml');
$this->assertEquals(200, $response->getStatusCode(), 'Sitemap returns a 200 success when enabled'); $this->assertEquals(200, $response->getStatusCode(), 'Sitemap returns a 200 success when enabled');
$this->assertEquals('application/xml; charset="utf-8"', $response->getHeader('Content-Type')); $this->assertEquals('application/xml; charset="utf-8"', $response->getHeader('Content-Type'));
GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject"); GoogleSitemap::register_dataobject("GoogleSitemapTest_DataObject");
$response = $this->get('sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1'); $response = $this->get('sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1');
$this->assertEquals(200, $response->getStatusCode(), 'Sitemap returns a 200 success when enabled'); $this->assertEquals(200, $response->getStatusCode(), 'Sitemap returns a 200 success when enabled');
$this->assertEquals('application/xml; charset="utf-8"', $response->getHeader('Content-Type')); $this->assertEquals('application/xml; charset="utf-8"', $response->getHeader('Content-Type'));
Config::inst()->remove('GoogleSitemap', 'enabled'); Config::inst()->remove('GoogleSitemap', 'enabled');
Config::inst()->update('GoogleSitemap', 'enabled', false); Config::inst()->update('GoogleSitemap', 'enabled', false);
$response = $this->get('sitemap.xml'); $response = $this->get('sitemap.xml');
$this->assertEquals(404, $response->getStatusCode(), 'Sitemap index returns a 404 when disabled'); $this->assertEquals(404, $response->getStatusCode(), 'Sitemap index returns a 404 when disabled');
$response = $this->get('sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1'); $response = $this->get('sitemap.xml/sitemap/GoogleSitemapTest_DataObject/1');
$this->assertEquals(404, $response->getStatusCode(), 'Sitemap file returns a 404 when disabled'); $this->assertEquals(404, $response->getStatusCode(), 'Sitemap file returns a 404 when disabled');
} }
public function testDecoratorAddsFields() { public function testDecoratorAddsFields()
if(!class_exists("Page")) { {
$this->markTestIncomplete('No cms module installed, page related test skipped'); if (!class_exists("Page")) {
} $this->markTestIncomplete('No cms module installed, page related test skipped');
}
$page = $this->objFromFixture('Page', 'Page1'); $page = $this->objFromFixture('Page', 'Page1');
$fields = $page->getSettingsFields(); $fields = $page->getSettingsFields();
$tab = $fields->fieldByName('Root')->fieldByName('Settings')->fieldByName('GoogleSitemap'); $tab = $fields->fieldByName('Root')->fieldByName('Settings')->fieldByName('GoogleSitemap');
$this->assertInstanceOf('Tab', $tab); $this->assertInstanceOf('Tab', $tab);
$this->assertInstanceOf('DropdownField', $tab->fieldByName('Priority')); $this->assertInstanceOf('DropdownField', $tab->fieldByName('Priority'));
$this->assertInstanceOf('LiteralField', $tab->fieldByName('GoogleSitemapIntro')); $this->assertInstanceOf('LiteralField', $tab->fieldByName('GoogleSitemapIntro'));
} }
public function testGetPriority() { public function testGetPriority()
if(!class_exists("Page")) { {
$this->markTestIncomplete('No cms module installed, page related test skipped'); if (!class_exists("Page")) {
} $this->markTestIncomplete('No cms module installed, page related test skipped');
}
$page = $this->objFromFixture('Page', 'Page1');
$page = $this->objFromFixture('Page', 'Page1');
// invalid field doesn't break google // invalid field doesn't break google
$page->Priority = 'foo'; $page->Priority = 'foo';
$this->assertEquals(0.5, $page->getGooglePriority()); $this->assertEquals(0.5, $page->getGooglePriority());
// custom value (set as string as db field is varchar) // custom value (set as string as db field is varchar)
$page->Priority = '0.2'; $page->Priority = '0.2';
$this->assertEquals(0.2, $page->getGooglePriority()); $this->assertEquals(0.2, $page->getGooglePriority());
// -1 indicates that we should not index this // -1 indicates that we should not index this
$page->Priority = -1; $page->Priority = -1;
$this->assertFalse($page->getGooglePriority()); $this->assertFalse($page->getGooglePriority());
} }
public function testUnpublishedPage() { public function testUnpublishedPage()
{
if(!class_exists('SiteTree')) { if (!class_exists('SiteTree')) {
$this->markTestSkipped('Test skipped; CMS module required for testUnpublishedPage'); $this->markTestSkipped('Test skipped; CMS module required for testUnpublishedPage');
} }
$orphanedPage = new SiteTree(); $orphanedPage = new SiteTree();
$orphanedPage->ParentID = 999999; // missing parent id $orphanedPage->ParentID = 999999; // missing parent id
$orphanedPage->write(); $orphanedPage->write();
$orphanedPage->publish("Stage", "Live"); $orphanedPage->publish("Stage", "Live");
$rootPage = new SiteTree(); $rootPage = new SiteTree();
$rootPage->ParentID = 0; $rootPage->ParentID = 0;
$rootPage->write(); $rootPage->write();
$rootPage->publish("Stage", "Live"); $rootPage->publish("Stage", "Live");
$oldMode = Versioned::get_reading_mode(); $oldMode = Versioned::get_reading_mode();
Versioned::reading_stage('Live'); Versioned::reading_stage('Live');
try { try {
$this->assertEmpty($orphanedPage->hasPublishedParent()); $this->assertEmpty($orphanedPage->hasPublishedParent());
$this->assertEmpty($orphanedPage->canIncludeInGoogleSitemap()); $this->assertEmpty($orphanedPage->canIncludeInGoogleSitemap());
$this->assertNotEmpty($rootPage->hasPublishedParent()); $this->assertNotEmpty($rootPage->hasPublishedParent());
$this->assertNotEmpty($rootPage->canIncludeInGoogleSitemap()); $this->assertNotEmpty($rootPage->canIncludeInGoogleSitemap());
} catch(Exception $ex) { } catch (Exception $ex) {
Versioned::set_reading_mode($oldMode); Versioned::set_reading_mode($oldMode);
throw $ex; throw $ex;
} // finally { } // finally {
Versioned::set_reading_mode($oldMode); Versioned::set_reading_mode($oldMode);
// } // }
} }
} }
/** /**
* @package googlesitemaps * @package googlesitemaps
* @subpackage tests * @subpackage tests
*/ */
class GoogleSitemapTest_DataObject extends DataObject implements TestOnly { class GoogleSitemapTest_DataObject extends DataObject implements TestOnly
{
public static $db = array(
'Priority' => 'Varchar(10)' public static $db = array(
); 'Priority' => 'Varchar(10)'
);
public function canView($member = null) { public function canView($member = null)
return true; {
} return true;
}
public function AbsoluteLink() { public function AbsoluteLink()
return Director::absoluteBaseURL(); {
} return Director::absoluteBaseURL();
}
} }
/** /**
* @package googlesitemaps * @package googlesitemaps
* @subpackage tests * @subpackage tests
*/ */
class GoogleSitemapTest_OtherDataObject extends DataObject implements TestOnly { class GoogleSitemapTest_OtherDataObject extends DataObject implements TestOnly
{
public static $db = array( public static $db = array(
'Priority' => 'Varchar(10)' 'Priority' => 'Varchar(10)'
); );
public function canView($member = null) { public function canView($member = null)
return true; {
} return true;
}
public function AbsoluteLink() { public function AbsoluteLink()
return Director::absoluteBaseURL(); {
} return Director::absoluteBaseURL();
}
} }
/** /**
* @package googlesitemaps * @package googlesitemaps
* @subpackage tests * @subpackage tests
*/ */
class GoogleSitemapTest_UnviewableDataObject extends DataObject implements TestOnly { class GoogleSitemapTest_UnviewableDataObject extends DataObject implements TestOnly
{
public static $db = array( public static $db = array(
'Priority' => 'Varchar(10)' 'Priority' => 'Varchar(10)'
); );
public function canView($member = null) { public function canView($member = null)
return false; {
} return false;
}
public function AbsoluteLink() { public function AbsoluteLink()
return Director::absoluteBaseURL(); {
} return Director::absoluteBaseURL();
}
} }