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

Converted to PSR-2
This commit is contained in:
Damian Mooyman 2015-12-21 10:30:04 +13:00
commit 1a37a8033a
7 changed files with 1262 additions and 1186 deletions

View File

@ -14,7 +14,8 @@
*
* @package staticpublisher
*/
class StaticExporter extends Controller {
class StaticExporter extends Controller
{
/**
* @config
@ -42,17 +43,18 @@ class StaticExporter extends Controller {
/**
*
*/
public function __construct() {
public function __construct()
{
parent::__construct();
if(class_exists('SiteTree')) {
if(!$this->config()->get('disable_sitetree_export')) {
if (class_exists('SiteTree')) {
if (!$this->config()->get('disable_sitetree_export')) {
$objs = $this->config()->export_objects;
if (!is_array($objs)) {
$objs = array($objs);
}
if(!in_array('SiteTree', $objs)) {
if (!in_array('SiteTree', $objs)) {
$objs[] = "SiteTree";
}
@ -64,12 +66,13 @@ class StaticExporter extends Controller {
/**
*
*/
public function init() {
public function init()
{
parent::init();
$canAccess = (Director::isDev() || Director::is_cli());
if(!Permission::check("ADMIN") && !$canAccess) {
if (!Permission::check("ADMIN") && !$canAccess) {
return Security::permissionFailure($this);
}
}
@ -79,7 +82,8 @@ class StaticExporter extends Controller {
*
* @return string
*/
public function Link($action = null) {
public function Link($action = null)
{
return "dev/staticexporter/$action";
}
@ -88,16 +92,18 @@ class StaticExporter extends Controller {
*
* @return string
*/
public function AbsoluteLink($action = null) {
public function AbsoluteLink($action = null)
{
return Director::absoluteURL($this->Link($action));
}
/**
* @return array
*/
public function index() {
public function index()
{
return array(
'Title' => _t('StaticExporter.NAME','Static exporter'),
'Title' => _t('StaticExporter.NAME', 'Static exporter'),
'Form' => $this->StaticExportForm()->forTemplate()
);
}
@ -105,26 +111,29 @@ class StaticExporter extends Controller {
/**
* @return Form
*/
public function StaticExportForm() {
public function StaticExportForm()
{
$form = new Form($this, 'StaticExportForm', new FieldList(
new TextField('baseurl', _t('StaticExporter.BASEURL','Base URL'))
new TextField('baseurl', _t('StaticExporter.BASEURL', 'Base URL'))
), new FieldList(
new FormAction('export', _t('StaticExporter.EXPORT','Export'))
new FormAction('export', _t('StaticExporter.EXPORT', 'Export'))
));
return $form;
}
public function export() {
if(isset($_REQUEST['baseurl'])) {
public function export()
{
if (isset($_REQUEST['baseurl'])) {
$base = $_REQUEST['baseurl'];
if(substr($base,-1) != '/') $base .= '/';
if (substr($base, -1) != '/') {
$base .= '/';
}
Config::inst()->update('Director', 'alternate_base_url', $base);
}
else {
} else {
$base = Director::baseURL();
}
@ -159,12 +168,13 @@ class StaticExporter extends Controller {
*
* @return string path to export
*/
public function doExport($base, $folder, $symlink = true, $quiet = true) {
public function doExport($base, $folder, $symlink = true, $quiet = true)
{
ini_set('max_execution_time', 0);
Config::inst()->update('Director', 'alternate_base_url', $base);
if(is_dir($folder)) {
if (is_dir($folder)) {
Filesystem::removeFolder($folder);
}
@ -174,26 +184,25 @@ class StaticExporter extends Controller {
$f1 = ASSETS_PATH;
$f2 = Director::baseFolder() . '/' . project();
if($symlink) {
if ($symlink) {
`cd $folder; ln -s $f1; ln -s $f2`;
}
else {
} else {
`cp -R $f1 $folder; cp -R $f2 $folder`;
}
// iterate through items we need to export
$urls = $this->getExportUrls();
if($urls) {
if ($urls) {
$total = count($urls);
$i = 1;
foreach($urls as $url) {
foreach ($urls as $url) {
$subfolder = "$folder/" . trim($url, '/');
$contentfile = "$folder/" . trim($url, '/') . '/index.html';
// Make the folder
if(!file_exists($subfolder)) {
if (!file_exists($subfolder)) {
Filesystem::makeFolder($subfolder);
}
@ -204,8 +213,8 @@ class StaticExporter extends Controller {
$response = Director::test($url);
// Write to file
if($fh = fopen($contentfile, 'w')) {
if(!$quiet) {
if ($fh = fopen($contentfile, 'w')) {
if (!$quiet) {
printf("-- (%s/%s) Outputting page (%s)%s",
$i,
$total,
@ -230,11 +239,12 @@ class StaticExporter extends Controller {
*
* @return array
*/
public function getExportUrls() {
public function getExportUrls()
{
$classes = $this->config()->get('export_objects');
$urls = array();
foreach($classes as $obj) {
foreach ($classes as $obj) {
if (!class_exists($obj)) {
continue;
}
@ -250,8 +260,8 @@ class StaticExporter extends Controller {
$objs = new ArrayList();
$this->extend('alterObjectsToExport', $objs);
if($objs) {
foreach($objs as $obj) {
if ($objs) {
foreach ($objs as $obj) {
$link = $obj->Link;
$urls[$link] = $link;

View File

@ -3,7 +3,8 @@
/**
* @package staticpublisher
*/
class FilesystemPublisher extends StaticPublisher {
class FilesystemPublisher extends StaticPublisher
{
/**
* @var string
@ -38,7 +39,8 @@ class FilesystemPublisher extends StaticPublisher {
*
* @deprecated 3.2 Use the "FilesystemPublisher.static_base_url" config setting instead
*/
static public function set_static_base_url($url) {
public static function set_static_base_url($url)
{
Deprecation::notice('3.2', 'Use the "FilesystemPublisher.static_base_url" config setting instead');
Config::inst()->update('FilesystemPublisher', 'static_base_url', $url);
@ -52,15 +54,16 @@ class FilesystemPublisher extends StaticPublisher {
* with the filename 'index.html'. If you set the extension to PHP, then a simple PHP script will
* be generated that can do appropriate cache & redirect header negotation.
*/
public function __construct($destFolder = 'cache', $fileExtension = null) {
public function __construct($destFolder = 'cache', $fileExtension = null)
{
// Remove trailing slash from folder
if(substr($destFolder, -1) == '/') {
if (substr($destFolder, -1) == '/') {
$destFolder = substr($destFolder, 0, -1);
}
$this->destFolder = $destFolder;
if($fileExtension) {
if ($fileExtension) {
$this->fileExtension = $fileExtension;
}
@ -91,10 +94,11 @@ class FilesystemPublisher extends StaticPublisher {
* @param array $urls Absolute or relative URLs
* @return array Map of original URLs to filesystem paths (relative to {@link $destFolder}).
*/
public function urlsToPaths($urls) {
public function urlsToPaths($urls)
{
$mappedUrls = array();
foreach($urls as $url) {
foreach ($urls as $url) {
// parse_url() is not multibyte safe, see https://bugs.php.net/bug.php?id=52923.
// We assume that the URL hsa been correctly encoded either on storage (for SiteTree->URLSegment),
@ -103,7 +107,7 @@ class FilesystemPublisher extends StaticPublisher {
// Remove base folders from the URL if webroot is hosted in a subfolder (same as static-main.php)
$path = isset($urlParts['path']) ? $urlParts['path'] : '';
if(mb_substr(mb_strtolower($path), 0, mb_strlen(BASE_URL)) == mb_strtolower(BASE_URL)) {
if (mb_substr(mb_strtolower($path), 0, mb_strlen(BASE_URL)) == mb_strtolower(BASE_URL)) {
$urlSegment = mb_substr($path, mb_strlen(BASE_URL));
} else {
$urlSegment = $path;
@ -115,7 +119,9 @@ class FilesystemPublisher extends StaticPublisher {
$filename = $urlSegment ? "$urlSegment.$this->fileExtension" : "index.$this->fileExtension";
if (Config::inst()->get('FilesystemPublisher', 'domain_based_caching')) {
if (!$urlParts) continue; // seriously malformed url here...
if (!$urlParts) {
continue;
} // seriously malformed url here...
$filename = $urlParts['host'] . '/' . $filename;
}
@ -128,10 +134,13 @@ class FilesystemPublisher extends StaticPublisher {
/**
* @param array $urls
*/
public function unpublishPages($urls) {
public function unpublishPages($urls)
{
// Do we need to map these?
// Detect a numerically indexed arrays
if (is_numeric(join('', array_keys($urls)))) $urls = $this->urlsToPaths($urls);
if (is_numeric(join('', array_keys($urls)))) {
$urls = $this->urlsToPaths($urls);
}
// This can be quite memory hungry and time-consuming
// @todo - Make a more memory efficient publisher
@ -140,7 +149,7 @@ class FilesystemPublisher extends StaticPublisher {
$cacheBaseDir = $this->getDestDir();
foreach($urls as $url => $path) {
foreach ($urls as $url => $path) {
if (file_exists($cacheBaseDir.'/'.$path)) {
@unlink($cacheBaseDir.'/'.$path);
}
@ -157,7 +166,8 @@ class FilesystemPublisher extends StaticPublisher {
* - "redirect": A redirect location (if applicable)
* - "path": The filesystem path where the cache has been written
*/
public function publishPages($urls) {
public function publishPages($urls)
{
// Save current stage and temporarily force it to Live
$oldStage = Versioned::current_stage();
Versioned::reading_stage("Live");
@ -169,7 +179,9 @@ class FilesystemPublisher extends StaticPublisher {
// Do we need to map these?
// Detect a numerically indexed arrays
if (is_numeric(join('', array_keys($urls)))) $urls = $this->urlsToPaths($urls);
if (is_numeric(join('', array_keys($urls)))) {
$urls = $this->urlsToPaths($urls);
}
// This can be quite memory hungry and time-consuming
// @todo - Make a more memory efficient publisher
@ -181,7 +193,7 @@ class FilesystemPublisher extends StaticPublisher {
// or we can use the last non-null theme.
$customTheme = Config::inst()->get('StaticPublisher', 'static_publisher_theme');
if($customTheme) {
if ($customTheme) {
Config::inst()->update('SSViewer', 'theme', $customTheme);
}
@ -190,15 +202,15 @@ class FilesystemPublisher extends StaticPublisher {
$staticBaseUrl = Config::inst()->get('FilesystemPublisher', 'static_base_url');
if($staticBaseUrl) {
if ($staticBaseUrl) {
Config::inst()->update('Director', 'alternate_base_url', $staticBaseUrl);
}
if($this->fileExtension == 'php') {
if ($this->fileExtension == 'php') {
Config::inst()->update('SSViewer', 'rewrite_hash_links', 'php');
}
if(Config::inst()->get('StaticPublisher', 'echo_progress')) {
if (Config::inst()->get('StaticPublisher', 'echo_progress')) {
echo $this->class.": Publishing to " . $staticBaseUrl . "\n";
}
@ -206,7 +218,7 @@ class FilesystemPublisher extends StaticPublisher {
$i = 0;
$totalURLs = sizeof($urls);
foreach($urls as $url => $path) {
foreach ($urls as $url => $path) {
$origUrl = $url;
$result[$origUrl] = array(
'statuscode' => null,
@ -216,25 +228,31 @@ class FilesystemPublisher extends StaticPublisher {
$i++;
if($url && !is_string($url)) {
user_error("Bad url:" . var_export($url,true), E_USER_WARNING);
if ($url && !is_string($url)) {
user_error("Bad url:" . var_export($url, true), E_USER_WARNING);
continue;
}
if(Config::inst()->get('StaticPublisher', 'echo_progress')) {
if (Config::inst()->get('StaticPublisher', 'echo_progress')) {
echo " * Publishing page $i/$totalURLs: $url\n";
flush();
}
Requirements::clear();
if($url == "") $url = "/";
if(Director::is_relative_url($url)) $url = Director::absoluteURL($url);
if ($url == "") {
$url = "/";
}
if (Director::is_relative_url($url)) {
$url = Director::absoluteURL($url);
}
$response = Director::test(str_replace('+', ' ', $url));
if (!$response) continue;
if (!$response) {
continue;
}
if($response) {
if ($response) {
$result[$origUrl]['statuscode'] = $response->getStatusCode();
}
Requirements::clear();
@ -246,17 +264,21 @@ class FilesystemPublisher extends StaticPublisher {
$pageObject = null;
if ($response && is_object($response) && ((int)$response->getStatusCode())>=400) {
$pageObject = SiteTree::get_by_link($url);
if ($pageObject && $pageObject instanceof ErrorPage) $isErrorPage = true;
if ($pageObject && $pageObject instanceof ErrorPage) {
$isErrorPage = true;
}
}
// Skip any responses with a 404 status code unless it's the ErrorPage itself.
if (!$isErrorPage && is_object($response) && $response->getStatusCode()=='404') continue;
if (!$isErrorPage && is_object($response) && $response->getStatusCode()=='404') {
continue;
}
// Generate file content
// PHP file caching will generate a simple script from a template
if($this->fileExtension == 'php') {
if(is_object($response)) {
if($response->getStatusCode() == '301' || $response->getStatusCode() == '302') {
if ($this->fileExtension == 'php') {
if (is_object($response)) {
if ($response->getStatusCode() == '301' || $response->getStatusCode() == '302') {
$content = $this->generatePHPCacheRedirection($response->getHeader('Location'));
} else {
$content = $this->generatePHPCacheFile($response->getBody(), HTTP::get_cache_age(), date('Y-m-d H:i:s'), $response->getHeader('Content-Type'));
@ -267,8 +289,8 @@ class FilesystemPublisher extends StaticPublisher {
// HTML file caching generally just creates a simple file
} else {
if(is_object($response)) {
if($response->getStatusCode() == '301' || $response->getStatusCode() == '302') {
if (is_object($response)) {
if ($response->getStatusCode() == '301' || $response->getStatusCode() == '302') {
$absoluteURL = Director::absoluteURL($response->getHeader('Location'));
$result[$origUrl]['redirect'] = $response->getHeader('Location');
$content = "<meta http-equiv=\"refresh\" content=\"2; URL=$absoluteURL\">";
@ -280,7 +302,7 @@ class FilesystemPublisher extends StaticPublisher {
}
}
if(Config::inst()->get('StaticPublisher', 'include_caching_metadata')) {
if (Config::inst()->get('StaticPublisher', 'include_caching_metadata')) {
$content = str_replace(
'</html>',
sprintf("</html>\n\n<!-- %s -->", implode(" ", $this->getMetadata($url))),
@ -289,13 +311,11 @@ class FilesystemPublisher extends StaticPublisher {
}
if (!$isErrorPage) {
$files[$origUrl] = array(
'Content' => $content,
'Folder' => dirname($path).'/',
'Filename' => basename($path),
);
} else {
// Generate a static version of the error page with a standardised name, so they can be plugged
@ -306,7 +326,6 @@ class FilesystemPublisher extends StaticPublisher {
'Folder' => dirname($path).'/',
'Filename' => "error-$code.html",
);
}
}
@ -315,17 +334,17 @@ class FilesystemPublisher extends StaticPublisher {
$base = BASE_PATH . "/$this->destFolder";
foreach($files as $origUrl => $file) {
foreach ($files as $origUrl => $file) {
Filesystem::makeFolder("$base/$file[Folder]");
$path = "$base/$file[Folder]$file[Filename]";
$result[$origUrl]['path'] = $path;
if(isset($file['Content'])) {
if (isset($file['Content'])) {
$fh = fopen($path, "w");
fwrite($fh, $file['Content']);
fclose($fh);
} else if(isset($file['Copy'])) {
} elseif (isset($file['Copy'])) {
copy($file['Copy'], $path);
}
}
@ -347,7 +366,8 @@ class FilesystemPublisher extends StaticPublisher {
*
* @return string
*/
protected function generatePHPCacheFile($content, $age, $lastModified, $contentType) {
protected function generatePHPCacheFile($content, $age, $lastModified, $contentType)
{
$template = file_get_contents(STATIC_MODULE_DIR . '/code/CachedPHPPage.tmpl');
return str_replace(
array('**MAX_AGE**', '**LAST_MODIFIED**', '**CONTENT**', '**CONTENT_TYPE**'),
@ -364,7 +384,8 @@ class FilesystemPublisher extends StaticPublisher {
*
* @return string
*/
protected function generatePHPCacheRedirection($destination) {
protected function generatePHPCacheRedirection($destination)
{
$template = file_get_contents(STATIC_MODULE_DIR . '/code/CachedPHPRedirection.tmpl');
return str_replace(
@ -377,7 +398,8 @@ class FilesystemPublisher extends StaticPublisher {
/**
* @return string
*/
public function getDestDir() {
public function getDestDir()
{
return BASE_PATH . '/' . $this->destFolder;
}
@ -388,7 +410,8 @@ class FilesystemPublisher extends StaticPublisher {
*
* @return array
*/
public function getExistingStaticCacheFiles() {
public function getExistingStaticCacheFiles()
{
$cacheDir = BASE_PATH . '/' . $this->destFolder;
$urlMapper = array_flip($this->urlsToPaths($this->owner->allPagesToCache()));
@ -396,10 +419,10 @@ class FilesystemPublisher extends StaticPublisher {
$output = array();
// Glob each dir, then glob each one of those
foreach(glob("$cacheDir/*", GLOB_ONLYDIR) as $cacheDir) {
foreach(glob($cacheDir.'/*') as $cacheFile) {
$mapKey = str_replace(BASE_PATH . "/cache/","",$cacheFile);
if(isset($urlMapper[$mapKey])) {
foreach (glob("$cacheDir/*", GLOB_ONLYDIR) as $cacheDir) {
foreach (glob($cacheDir.'/*') as $cacheFile) {
$mapKey = str_replace(BASE_PATH . "/cache/", "", $cacheFile);
if (isset($urlMapper[$mapKey])) {
$url = $urlMapper[$mapKey];
$output[$url] = $cacheFile;
}

View File

@ -8,7 +8,8 @@
*
* @package staticpublisher
*/
class RsyncMultiHostPublisher extends FilesystemPublisher {
class RsyncMultiHostPublisher extends FilesystemPublisher
{
/**
* @config
@ -38,7 +39,8 @@ class RsyncMultiHostPublisher extends FilesystemPublisher {
*
* @param $targets An array of targets to publish to.
*/
public static function set_targets($targets) {
public static function set_targets($targets)
{
Deprecation::notice('3.2', 'Use the "RsyncMultiHostPublisher.targets" config setting instead');
Config::inst()->update('RsyncMultiHostPublisher', 'targets', $targets);
@ -50,28 +52,34 @@ class RsyncMultiHostPublisher extends FilesystemPublisher {
*
* @deprecated 3.2 Use the "RsyncMultiHostPublisher.excluded_folders" config setting instead
*/
public static function set_excluded_folders($folders) {
public static function set_excluded_folders($folders)
{
Deprecation::notice('3.2', 'Use the "RsyncMultiHostPublisher.excluded_folders" config setting instead');
Config::inst()->update('RsyncMultiHostPublisher', 'excluded_folders', $folders);
}
public function publishPages($urls) {
public function publishPages($urls)
{
parent::publishPages($urls);
$base = Director::baseFolder();
$framework = FRAMEWORK_DIR;
// Get variable that can turn off the rsync component of publication
if(isset($_GET['norsync']) && $_GET['norsync']) return;
if (isset($_GET['norsync']) && $_GET['norsync']) {
return;
}
$extraArg = "";
$excludedFolders = Config::inst()->get('RsyncMultiHostPublisher', 'excluded_folders');
if($excludedFolders) foreach($excludedFolders as $folder) {
if ($excludedFolders) {
foreach ($excludedFolders as $folder) {
$extraArg .= " --exclude " . escapeshellarg($folder);
}
}
$targets = Config::inst()->get('RsyncMultiHostPublisher', 'targets');
foreach((array)$targets as $target) {
foreach ((array)$targets as $target) {
// Transfer non-PHP content from everything to the target; that will ensure that we have all the JS/CSS/etc
$rsyncOutput = `cd $base; rsync -av -e ssh --exclude /.htaccess --exclude /web.config --exclude '*.php' --exclude '*.svn' --exclude '*.git' --exclude '*~' $extraArg --delete . $target`;
// Then transfer "safe" PHP from the cache/ directory
@ -79,7 +87,7 @@ class RsyncMultiHostPublisher extends FilesystemPublisher {
// Transfer framework/static-main.php to the target
$rsyncOutput .= `cd $base; rsync -av -e ssh --delete $framework/static-main.php $target/$framework`;
if(Config::inst()->get('StaticPublisher', 'echo_progress')) {
if (Config::inst()->get('StaticPublisher', 'echo_progress')) {
echo $rsyncOutput;
}
}

View File

@ -2,7 +2,8 @@
/**
* @package staticpublisher
*/
abstract class StaticPublisher extends DataExtension {
abstract class StaticPublisher extends DataExtension
{
/**
* Defines whether to output information about publishing or not. By
@ -49,18 +50,19 @@ abstract class StaticPublisher extends DataExtension {
/**
* @param array
*/
abstract function publishPages($pages);
abstract public function publishPages($pages);
/**
* @param array
*/
abstract function unpublishPages($pages);
abstract public function unpublishPages($pages);
/**
* @deprecated
* @param string
*/
public static function set_static_publisher_theme($theme) {
public static function set_static_publisher_theme($theme)
{
Deprecation::notice('1.0', 'Use the new config system. SSViewer.static_publisher_theme');
Config::inst()->update('StaticPublisher', 'static_publisher_theme', $theme);
@ -71,7 +73,8 @@ abstract class StaticPublisher extends DataExtension {
*
* @return string
*/
public static function static_publisher_theme() {
public static function static_publisher_theme()
{
Deprecation::notice('1.0', 'Use the new config system. SSViewer.static_publisher_theme');
return Config::inst()->get('StaticPublisher', 'static_publisher_theme');
@ -82,7 +85,8 @@ abstract class StaticPublisher extends DataExtension {
*
* @return boolean
*/
public static function echo_progress() {
public static function echo_progress()
{
Deprecation::notice('1.0', 'Use the new config system. SSViewer.static_publisher_theme');
return Config::inst()->get('StaticPublisher', 'echo_progress');
@ -92,7 +96,8 @@ abstract class StaticPublisher extends DataExtension {
* @deprecated
*
*/
public static function set_echo_progress($progress) {
public static function set_echo_progress($progress)
{
Deprecation::notice('1.0', 'Use the new config system. SSViewer.static_publisher_theme');
Config::inst()->get('StaticPublisher', 'echo_progress', $progress);
@ -103,7 +108,8 @@ abstract class StaticPublisher extends DataExtension {
*
* @param SiteTree
*/
public function onAfterPublish($original) {
public function onAfterPublish($original)
{
$this->republish($original);
}
@ -113,37 +119,41 @@ abstract class StaticPublisher extends DataExtension {
*
* Only called if the published content exists and has been modified.
*/
public function onRenameLinkedAsset($original) {
public function onRenameLinkedAsset($original)
{
$this->republish($original);
}
public function republish($original) {
public function republish($original)
{
if (Config::inst()->get('StaticPublisher', 'disable_realtime')) {
return;
}
$urls = array();
if($this->owner->hasMethod('pagesAffectedByChanges')) {
if ($this->owner->hasMethod('pagesAffectedByChanges')) {
$urls = $this->owner->pagesAffectedByChanges($original);
} else {
$pages = Versioned::get_by_stage('SiteTree', 'Live', '', '', '', 10);
if($pages) {
foreach($pages as $page) {
if ($pages) {
foreach ($pages as $page) {
$urls[] = $page->AbsoluteLink();
}
}
}
// Note: Similiar to RebuildStaticCacheTask->rebuildCache()
foreach($urls as $i => $url) {
if(!is_string($url)) {
foreach ($urls as $i => $url) {
if (!is_string($url)) {
user_error("Bad URL: " . var_export($url, true), E_USER_WARNING);
continue;
}
// Remove leading slashes from all URLs (apart from the homepage)
if(substr($url,-1) == '/' && $url != '/') $url = substr($url,0,-1);
if (substr($url, -1) == '/' && $url != '/') {
$url = substr($url, 0, -1);
}
$urls[$i] = $url;
}
@ -159,13 +169,14 @@ abstract class StaticPublisher extends DataExtension {
/**
* Get changes and hook into underlying functionality.
*/
public function onAfterUnpublish($page) {
public function onAfterUnpublish($page)
{
if (Config::inst()->get('StaticPublisher', 'disable_realtime')) {
return;
}
// Get the affected URLs
if($this->owner->hasMethod('pagesAffectedByUnpublishing')) {
if ($this->owner->hasMethod('pagesAffectedByUnpublishing')) {
$urls = $this->owner->pagesAffectedByUnpublishing();
$urls = array_unique($urls);
} else {
@ -186,7 +197,8 @@ abstract class StaticPublisher extends DataExtension {
* @param string $url
* @return array
*/
public function getMetadata($url) {
public function getMetadata($url)
{
return array(
'Cache generated on ' . date('Y-m-d H:i:s T (O)')
);

View File

@ -2,12 +2,14 @@
/**
* @package staticpublisher
*/
class RebuildStaticCacheTask extends BuildTask {
class RebuildStaticCacheTask extends BuildTask
{
private static $quiet = false;
public function run($request) {
if(Config::inst()->get('RebuildStaticCacheTask', 'quiet')) {
public function run($request)
{
if (Config::inst()->get('RebuildStaticCacheTask', 'quiet')) {
Config::inst()->update('StaticPublisher', 'echo_progress', false);
} else {
Config::inst()->update('StaticPublisher', 'echo_progress', true);
@ -15,7 +17,7 @@ class RebuildStaticCacheTask extends BuildTask {
$page = singleton('Page');
if(!$page->hasMethod('allPagesToCache')) {
if (!$page->hasMethod('allPagesToCache')) {
user_error(
'RebuildStaticCacheTask::index(): Please define a method "allPagesToCache()" on your Page class to return all pages affected by a cache refresh.',
E_USER_ERROR
@ -23,7 +25,7 @@ class RebuildStaticCacheTask extends BuildTask {
}
if(!empty($_GET['urls'])) {
if (!empty($_GET['urls'])) {
$urls = $_GET['urls'];
} else {
$urls = $page->allPagesToCache();
@ -32,10 +34,11 @@ class RebuildStaticCacheTask extends BuildTask {
$this->rebuildCache($urls, true);
}
public function log($message = null) {
public function log($message = null)
{
$quiet = Config::inst()->get('RebuildStaticCacheTask', 'quiet');
if($quiet) {
if ($quiet) {
return;
}
@ -48,15 +51,15 @@ class RebuildStaticCacheTask extends BuildTask {
* @param array $urls The URLs of pages to re-fetch and cache.
* @param bool $removeAll Remove all stale cache files (default TRUE).
*/
public function rebuildCache($urls, $removeAll = true) {
if(!is_array($urls)) {
public function rebuildCache($urls, $removeAll = true)
{
if (!is_array($urls)) {
// $urls must be an array
user_error("Rebuild cache must be passed an array of urls. Make sure your allPagesToCache function returns an array", E_USER_ERROR);
return;
};
if(!Director::is_cli()) {
if (!Director::is_cli()) {
$this->log("<pre>\n");
$this->log("Rebuilding cache.\nNOTE: Please ensure that this page ends with 'Done!' - if not, then something may have gone wrong.\n\n");
}
@ -64,13 +67,13 @@ class RebuildStaticCacheTask extends BuildTask {
$page = singleton('Page');
$cacheBaseDir = $page->getDestDir();
if(!file_exists($cacheBaseDir)) {
if (!file_exists($cacheBaseDir)) {
Filesystem::makeFolder($cacheBaseDir);
}
$quiet = Config::inst()->get('RebuildStaticCacheTask', 'quiet');
if(!$quiet) {
if (!$quiet) {
if (file_exists($cacheBaseDir.'/lock') && !isset($_REQUEST['force'])) {
die("There already appears to be a publishing queue running. You can skip warning this by adding ?/&force to the URL.");
}
@ -79,8 +82,8 @@ class RebuildStaticCacheTask extends BuildTask {
touch($cacheBaseDir.'/lock');
// Note: Similiar to StaticPublisher->republish()
foreach($urls as $i => $url) {
if($url && !is_string($url)) {
foreach ($urls as $i => $url) {
if ($url && !is_string($url)) {
user_error("Bad URL: " . var_export($url, true), E_USER_WARNING);
continue;
}
@ -94,7 +97,7 @@ class RebuildStaticCacheTask extends BuildTask {
$start = isset($_GET['start']) ? $_GET['start'] : 0;
$count = isset($_GET['count']) ? $_GET['count'] : sizeof($urls);
if(($start + $count) > sizeof($urls)) {
if (($start + $count) > sizeof($urls)) {
$count = sizeof($urls) - $start;
}
@ -102,17 +105,17 @@ class RebuildStaticCacheTask extends BuildTask {
$mappedUrls = $page->urlsToPaths($urls);
if($removeAll && !isset($_GET['urls']) && $start == 0 && file_exists("../cache")) {
if ($removeAll && !isset($_GET['urls']) && $start == 0 && file_exists("../cache")) {
$this->log("Removing stale cache files... \n");
if(!$quiet) {
if (!$quiet) {
flush();
}
if (Config::inst()->get('FilesystemPublisher', 'domain_based_caching')) {
// Glob each dir, then glob each one of those
foreach(glob(BASE_PATH . '/cache/*', GLOB_ONLYDIR) as $cacheDir) {
foreach(glob($cacheDir.'/*') as $cacheFile) {
foreach (glob(BASE_PATH . '/cache/*', GLOB_ONLYDIR) as $cacheDir) {
foreach (glob($cacheDir.'/*') as $cacheFile) {
$searchCacheFile = trim(str_replace($cacheBaseDir, '', $cacheFile), '\/');
if (!in_array($searchCacheFile, $mappedUrls)) {

View File

@ -3,9 +3,11 @@
/**
* @package staticpublisher
*/
class StaticExporterTask extends BuildTask {
class StaticExporterTask extends BuildTask
{
public function run($request) {
public function run($request)
{
$now = microtime(true);
$export = new StaticExporter();
@ -14,16 +16,20 @@ class StaticExporterTask extends BuildTask {
$quiet = $request->getVar('quiet');
$folder = $request->getVar('path');
if(!$folder) $folder = TEMP_FOLDER . '/static-export';
if (!$folder) {
$folder = TEMP_FOLDER . '/static-export';
}
$url = ($url) ? $url : Director::baseURL();
$symlink = ($sym != "false");
$quiet = ($quiet) ? $quiet : false;
if(!$quiet) printf("Exporting website with %s base URL... %s", $url, PHP_EOL);
if (!$quiet) {
printf("Exporting website with %s base URL... %s", $url, PHP_EOL);
}
$path = $export->doExport($url, $folder, $symlink, $quiet);
if(!$quiet) {
if (!$quiet) {
printf("\nWebsite exported to %s\nTotal time %s\nMemory used %s. %s",
$path,
number_format(microtime(true) - $now, 2) . 's',

View File

@ -5,13 +5,15 @@
*
* @package staticpublisher
*/
class FilesystemPublisherTest extends SapphireTest {
class FilesystemPublisherTest extends SapphireTest
{
protected $usesDatabase = true;
protected $orig = array();
public function setUp() {
public function setUp()
{
parent::setUp();
SiteTree::add_extension("FilesystemPublisher('assets/FilesystemPublisherTest-static-folder/')");
@ -21,19 +23,21 @@ class FilesystemPublisherTest extends SapphireTest {
Config::inst()->update('FilesystemPublisher', 'domain_based_caching', false);
}
public function tearDown() {
public function tearDown()
{
parent::tearDown();
SiteTree::remove_extension("FilesystemPublisher('assets/FilesystemPublisherTest-static-folder/')");
Config::inst()->update('FilesystemPublisher', 'domain_based_caching', $this->orig['domain_based_caching']);
if(file_exists(BASE_PATH . '/assets/FilesystemPublisherTest-static-folder')) {
if (file_exists(BASE_PATH . '/assets/FilesystemPublisherTest-static-folder')) {
Filesystem::removeFolder(BASE_PATH . '/assets/FilesystemPublisherTest-static-folder');
}
}
public function testUrlsToPathsWithRelativeUrls() {
public function testUrlsToPathsWithRelativeUrls()
{
$fsp = new FilesystemPublisher('.', 'html');
$this->assertEquals(
@ -55,7 +59,8 @@ class FilesystemPublisherTest extends SapphireTest {
);
}
public function testUrlsToPathsWithAbsoluteUrls() {
public function testUrlsToPathsWithAbsoluteUrls()
{
$fsp = new FilesystemPublisher('.', 'html');
$url = Director::absoluteBaseUrl();
@ -80,7 +85,8 @@ class FilesystemPublisherTest extends SapphireTest {
);
}
public function testUrlsToPathsWithDomainBasedCaching() {
public function testUrlsToPathsWithDomainBasedCaching()
{
$origDomainBasedCaching = Config::inst()->get('FilesystemPublisher', 'domain_based_caching');
Config::inst()->update('FilesystemPublisher', 'domain_based_caching', true);
@ -121,7 +127,8 @@ class FilesystemPublisherTest extends SapphireTest {
* is where extension instances are set up and subsequently used by
* {@link DataObject::defineMethods()}.
*/
public function testHasCalledParentConstructor() {
public function testHasCalledParentConstructor()
{
$fsp = new FilesystemPublisher('.', '.html');
$this->assertEquals($fsp->class, 'FilesystemPublisher');
@ -132,7 +139,8 @@ class FilesystemPublisherTest extends SapphireTest {
* correct theme when we need it. StaticPublishing needs to be able to
* retrieve a non-null theme at the time publishPages() is called.
*/
public function testStaticPublisherTheme(){
public function testStaticPublisherTheme()
{
// This will be the name of the default theme of this particular project
$default_theme = Config::inst()->get('SSViewer', 'theme');
@ -154,7 +162,8 @@ class FilesystemPublisherTest extends SapphireTest {
$this->assertNotEquals($current_theme, $default_theme, 'The static publisher theme overrides the custom theme');
}
public function testMenu2LinkingMode() {
public function testMenu2LinkingMode()
{
$this->logInWithPermission('ADMIN');
Config::inst()->update('SSViewer', 'theme', null);
@ -184,7 +193,8 @@ class FilesystemPublisherTest extends SapphireTest {
$this->assertEquals(trim($response->getBody()), "linkcurrent", "current page is level 2-2");
}
public function testContentTypeHTML() {
public function testContentTypeHTML()
{
SiteTree::remove_extension('FilesystemPublisher');
SiteTree::add_extension("FilesystemPublisher('assets/FilesystemPublisherTest-static-folder/', 'php')");
$l1 = new StaticPublisherTestPage();
@ -195,7 +205,8 @@ class FilesystemPublisherTest extends SapphireTest {
$this->assertEquals($response->getHeader('Content-Type'), 'text/html; charset=utf-8', 'Content-Type should be text/html; charset=utf-8');
}
public function testContentTypeJSON() {
public function testContentTypeJSON()
{
SiteTree::remove_extension('FilesystemPublisher');
SiteTree::add_extension("FilesystemPublisher('assets/FilesystemPublisherTest-static-folder/', 'php')");
$l1 = new StaticPublisherTestPage();
@ -210,18 +221,21 @@ class FilesystemPublisherTest extends SapphireTest {
/**
* @package staticpublisher
*/
class StaticPublisherTestPage extends Page implements TestOnly {
class StaticPublisherTestPage extends Page implements TestOnly
{
private static $allowed_children = array(
'StaticPublisherTestPage'
);
public function canPublish($member = null) {
public function canPublish($member = null)
{
return true;
}
public function getTemplate() {
public function getTemplate()
{
return STATIC_MODULE_DIR . '/tests/templates/StaticPublisherTestPage.ss';
}
}
@ -229,7 +243,8 @@ class StaticPublisherTestPage extends Page implements TestOnly {
/**
* @package staticpublisher
*/
class StaticPublisherTestPage_Controller extends Page_Controller implements TestOnly {
class StaticPublisherTestPage_Controller extends Page_Controller implements TestOnly
{
/**
*
@ -237,11 +252,10 @@ class StaticPublisherTestPage_Controller extends Page_Controller implements Test
*/
private static $allowed_actions = array('json');
public function json(SS_HTTPRequest $request) {
public function json(SS_HTTPRequest $request)
{
$response = new SS_HTTPResponse('{"firstName": "John"}');
$response->addHeader('Content-Type', 'application/json');
return $response;
}
}