/** * When an error page is published, create a static HTML page with its * content, so the page can be shown even when SilverStripe is not * functioning correctly before publishing this page normally. * @param string|int $fromStage Place to copy from. Can be either a stage name or a version number. * @param string $toStage Place to copy to. Must be a stage name. * @param boolean $createNewVersion Set this to true to create a new version number. By default, the existing version number will be copied over. */ function doPublish() { parent::doPublish(); // Run the page (reset the theme, it might've been disabled by LeftAndMain::init()) $oldTheme = SSViewer::current_theme(); SSViewer::set_theme(SSViewer::current_custom_theme()); $response = Director::test(Director::makeRelative($this->Link())); SSViewer::set_theme($oldTheme); $errorContent = $response->getBody(); // Make the base tag dynamic. // $errorContent = preg_replace('/<base[^>]+href="' . str_replace('/','\\/', Director::absoluteBaseURL()) . '"[^>]*>/i', '<base href="$BaseURL" />', $errorContent); // Check we have an assets base directory, creating if it we don't if (!file_exists(ASSETS_PATH)) { mkdir(ASSETS_PATH, 02775); } // if the page is published in a language other than default language, // write a specific language version of the HTML page $filePath = self::get_filepath_for_errorcode($this->ErrorCode, $this->Locale); if ($fh = fopen($filePath, "w")) { fwrite($fh, $errorContent); fclose($fh); } else { $fileErrorText = sprintf(_t("ErrorPage.ERRORFILEPROBLEM", "Error opening file \"%s\" for writing. Please check file permissions."), $errorFile); FormResponse::status_message($fileErrorText, 'bad'); FormResponse::respond(); return; } }
/** * looked-up the email template_paths. * if not set, will look up both theme folder and project folder * in both cases, email folder exsits or Email folder exists * return an array containing all folders pointing to the bunch of email templates * * @return array */ public static function template_paths() { if (!isset(self::$template_paths)) { if (class_exists('SiteConfig') && ($config = SiteConfig::current_site_config()) && $config->Theme) { $theme = $config->Theme; } elseif (SSViewer::current_custom_theme()) { $theme = SSViewer::current_custom_theme(); } elseif (SSViewer::current_theme()) { $theme = SSViewer::current_theme(); } else { $theme = false; } if ($theme) { if (file_exists("../" . THEMES_DIR . "/" . $theme . "/templates/email")) { self::$template_paths[] = THEMES_DIR . "/" . $theme . "/templates/email"; } if (file_exists("../" . THEMES_DIR . "/" . $theme . "/templates/Email")) { self::$template_paths[] = THEMES_DIR . "/" . $theme . "/templates/Email"; } } $project = project(); if (file_exists("../" . $project . '/templates/email')) { self::$template_paths[] = $project . '/templates/email'; } if (file_exists("../" . $project . '/templates/Email')) { self::$template_paths[] = $project . '/templates/Email'; } } else { if (is_string(self::$template_paths)) { self::$template_paths = array(self::$template_paths); } } return self::$template_paths; }
/** * Returns a relative path to current theme directory. * * @return mixed */ public function ThemeDir() { if ($theme = SSViewer::current_theme()) { return THEMES_DIR . "/{$theme}"; } elseif ($theme = SSViewer::current_custom_theme()) { return THEMES_DIR . "/{$theme}"; } elseif ($theme = SiteConfig::current_site_config()->Theme) { return THEMES_DIR . "/{$theme}"; } else { throw new Exception("cannot detect theme"); } }
/** * @param string $theme The "base theme" name (without underscores). */ public static function set_theme($theme) { self::$current_theme = $theme; //Static publishing needs to have a theme set, otherwise it defaults to the content controller theme if (!is_null($theme)) { self::$current_custom_theme = $theme; } }
function testStaticPublisherTheme() { //This will be the name of the default theme of this particular project $default_theme = SSViewer::current_theme(); $p1 = new Page(); $p1->URLSegment = strtolower(__CLASS__) . '-page-1'; $p1->HomepageForDomain = ''; $p1->write(); $p1->doPublish(); $current_theme = SSViewer::current_custom_theme(); $this->assertEquals($current_theme, $default_theme, 'After a standard publication, the theme is correct'); //The CMS sometimes sets the theme to null. Check that the $current_custom_theme is still the default SSViewer::set_theme(null); $current_theme = SSViewer::current_custom_theme(); $this->assertEquals($current_theme, $default_theme, 'After a setting the theme to null, the default theme is correct'); //We can set the static_publishing theme to something completely different: //Static publishing will use this one instead of the current_custom_theme if it is not false StaticPublisher::set_static_publisher_theme('otherTheme'); $current_theme = StaticPublisher::static_publisher_theme(); $this->assertNotEquals($current_theme, $default_theme, 'The static publisher theme overrides the custom theme'); }
<?php global $project; $project = 'beardpapa'; global $database; $database = 'beardpapa'; require_once 'conf/ConfigureFromEnv.php'; Director::setBaseURL('/'); // Set the site locale i18n::set_locale('en_US'); define('CSS_DIR', THEMES_DIR . "/" . SSViewer::current_custom_theme() . '/css'); define('JS_DIR', THEMES_DIR . "/" . SSViewer::current_custom_theme() . '/javascript'); define('BOWER_PATH', 'bower_components');
function publishPages($urls) { // Do we need to map these? // Detect a numerically indexed arrays 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 increase_time_limit_to(); increase_memory_limit_to(); // Set the appropriate theme for this publication batch. // This may have been set explicitly via StaticPublisher::static_publisher_theme, // or we can use the last non-null theme. if (!StaticPublisher::static_publisher_theme()) { SSViewer::set_theme(SSViewer::current_custom_theme()); } else { SSViewer::set_theme(StaticPublisher::static_publisher_theme()); } $currentBaseURL = Director::baseURL(); if (self::$static_base_url) { Director::setBaseURL(self::$static_base_url); } if ($this->fileExtension == 'php') { SSViewer::setOption('rewriteHashlinks', 'php'); } if (StaticPublisher::echo_progress()) { echo $this->class . ": Publishing to " . self::$static_base_url . "\n"; } $files = array(); $i = 0; $totalURLs = sizeof($urls); foreach ($urls as $url => $path) { if (self::$static_base_url) { Director::setBaseURL(self::$static_base_url); } $i++; if ($url && !is_string($url)) { user_error("Bad url:" . var_export($url, true), E_USER_WARNING); continue; } if (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); } $response = Director::test(str_replace('+', ' ', $url)); Requirements::clear(); singleton('DataObject')->flushCache(); //skip any responses with a 404 status code. We don't want to turn those into statically cached pages if (!$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') { $content = $this->generatePHPCacheRedirection($response->getHeader('Location')); } else { $content = $this->generatePHPCacheFile($response->getBody(), HTTP::get_cache_age(), date('Y-m-d H:i:s')); } } else { $content = $this->generatePHPCacheFile($response . '', HTTP::get_cache_age(), date('Y-m-d H:i:s')); } // HTML file caching generally just creates a simple file } else { if (is_object($response)) { if ($response->getStatusCode() == '301' || $response->getStatusCode() == '302') { $absoluteURL = Director::absoluteURL($response->getHeader('Location')); $content = "<meta http-equiv=\"refresh\" content=\"2; URL={$absoluteURL}\">"; } else { $content = $response->getBody(); } } else { $content = $response . ''; } } $files[] = array('Content' => $content, 'Folder' => dirname($path) . '/', 'Filename' => basename($path)); // Add externals /* $externals = $this->externalReferencesFor($content); if($externals) foreach($externals as $external) { // Skip absolute URLs if(preg_match('/^[a-zA-Z]+:\/\//', $external)) continue; // Drop querystring parameters $external = strtok($external, '?'); if(file_exists("../" . $external)) { // Break into folder and filename if(preg_match('/^(.*\/)([^\/]+)$/', $external, $matches)) { $files[$external] = array( "Copy" => "../$external", "Folder" => $matches[1], "Filename" => $matches[2], ); } else { user_error("Can't parse external: $external", E_USER_WARNING); } } else { $missingFiles[$external] = true; } }*/ } if (self::$static_base_url) { Director::setBaseURL($currentBaseURL); } if ($this->fileExtension == 'php') { SSViewer::setOption('rewriteHashlinks', true); } $base = BASE_PATH . "/{$this->destFolder}"; foreach ($files as $file) { Filesystem::makeFolder("{$base}/{$file['Folder']}"); if (isset($file['Content'])) { $fh = fopen("{$base}/{$file['Folder']}{$file['Filename']}", "w"); fwrite($fh, $file['Content']); fclose($fh); } else { if (isset($file['Copy'])) { copy($file['Copy'], "{$base}/{$file['Folder']}{$file['Filename']}"); } } } }
public function exportTo($directory) { $directory = rtrim($directory, '/'); $links = $this->urlsToPaths($this->getLinks()); $files = array(); increase_time_limit_to(); increase_memory_limit_to(); // Make the output directory if it doesn't exist. if (!is_dir($directory)) { mkdir($directory, Filesystem::$folder_create_mask, true); } if ($this->theme) { SSViewer::set_theme($this->theme); } else { SSViewer::set_theme(SSViewer::current_custom_theme()); } if ($this->baseUrl && !$this->makeRelative) { $originalBaseUrl = Director::baseURL(); Director::setBaseURL($this->baseUrl); } // Loop through each link that we're publishing, and create a static // html file for each. foreach ($links as $link => $path) { Requirements::clear(); singleton('DataObject')->flushCache(); $response = Director::test($link); $target = $directory . '/' . $path; if (is_object($response)) { if ($response->getStatusCode() == '301' || $response->getStatusCode() == '302') { $absoluteURL = Director::absoluteURL($response->getHeader('Location')); $content = "<meta http-equiv=\"refresh\" content=\"2; URL={$absoluteURL}\">"; } else { $content = $response->getBody(); } } else { $content = (string) $response; } // Find any external content references inside the response, and add // them to the copy array. $externals = $this->externalReferencesFor($content); if ($externals) { foreach ($externals as $external) { if (!Director::is_site_url($external)) { continue; } $external = strtok($external, '?'); $external = Director::makeRelative($external); if (file_exists(BASE_PATH . '/' . $external)) { $files["{$directory}/{$external}"] = array('copy', BASE_PATH . '/' . $external); } } } // Append any anchor links which point to a relative site link // with a .html extension. $base = preg_quote(Director::baseURL()); $content = preg_replace('~<a(.+?)href="(' . $base . '[^"]*?)/?"~i', '<a$1href="$2.html"', $content); $content = str_replace('/.html', '/index.html', $content); // If we want to rewrite links to relative, then determine how many // levels deep we are and rewrite the relevant attributes globally. // Also, string the base tag. if ($this->makeRelative) { $content = preg_replace('~(src|href)="' . Director::protocolAndHost() . '~i', '$1="', $content); if (($trimmed = trim($link, '/')) && strpos($trimmed, '/')) { $prepend = str_repeat('../', substr_count($trimmed, '/')); } else { $prepend = './'; } $base = preg_quote(Director::baseURL()); $content = preg_replace('~(href|src)="' . $base . '~i', '$1="' . $prepend, $content); $content = preg_replace('~<base href="([^"]+)" />~', '', $content); $content = preg_replace('~<base href="([^"]+)"><!--[if lte IE 6]></base><![endif]-->~', '', $content); } $files[$target] = array('create', $content); } // If we currently have a theme active, then copy all the theme // assets across to the site. if ($theme = SSViewer::current_theme()) { $stack = array(THEMES_PATH . '/' . $theme); // Build up a list of every file present in the current theme // which is not a .ss template, and add it to the files array while ($path = array_pop($stack)) { foreach (scandir($path) as $file) { if ($file[0] == '.' || $file[0] == '_') { continue; } if (is_dir("{$path}/{$file}")) { $stack[] = "{$path}/{$file}"; } else { if (substr($file, -3) != '.ss') { $loc = "{$path}/{$file}"; $to = $directory . '/' . substr($loc, strlen(BASE_PATH) + 1); $files[$to] = array('copy', $loc); } } } } } // If theres a favicon.ico file in the site root, copy it across if (file_exists(BASE_PATH . '/favicon.ico')) { $files["{$directory}/favicon.ico"] = array('copy', BASE_PATH . '/favicon.ico'); } // Copy across or create all the files that have been generated. foreach ($files as $to => $from) { list($mode, $content) = $from; if (!is_dir(dirname($to))) { mkdir(dirname($to), Filesystem::$folder_create_mask, true); } if ($mode == 'create') { file_put_contents($to, $content); } else { if (!file_exists($to)) { copy($content, $to); } } } if ($this->baseUrl && !$this->makeRelative) { Director::setBaseURL($originalBaseUrl); } }