public function testRenderTemplatePlaceholder() { // Create page object $page = $this->objFromFixture('Page', 'page1'); $templateTitle = 'template1'; $templatePlaceHolder = '{{' . $templateTitle . '}}'; // Assert: render page $this->assertContains($templatePlaceHolder, $page->Content()); // Create template $template = $this->objFromFixture('ViewTemplate', $templateTitle); $templatePlaceHolder = '{{' . $template->Title . '}}'; // Page disable template view $page->EnableViewTemplate = false; // Assert: render page without view template $this->assertContains($templatePlaceHolder, $page->Content()); // Page enable template view $page->EnableViewTemplate = true; // Assert: render page with view template $this->assertNotContains($templatePlaceHolder, $page->Content()); // Login admin $this->logInWithPermission('ADMIN'); // Assert: Publish page $published = $page->doPublish(); $this->assertTrue($published); // Assert: page visible to public with render view template Member::currentUser()->logOut(); $response = Director::test(Director::makeRelative($page->Link())); $this->assertNotContains($templatePlaceHolder, $response->getBody()); $this->assertContains($template->ViewTemplate, $response->getBody()); }
/** * Process all incoming requests passed to this controller, checking * that the file exists and passing the file through if possible. */ public function handleRequest(SS_HTTPRequest $request, DataModel $model) { // Copied from Controller::handleRequest() $this->pushCurrent(); $this->urlParams = $request->allParams(); $this->request = $request; $this->response = new SS_HTTPResponse(); $this->setDataModel($model); $url = array_key_exists('url', $_GET) ? $_GET['url'] : $_SERVER['REQUEST_URI']; // remove any relative base URL and prefixed slash that get appended to the file path // e.g. /mysite/assets/test.txt should become assets/test.txt to match the Filename field on File record $url = Director::makeRelative(ltrim(str_replace(BASE_URL, '', $url), '/')); $file = File::find($url); if ($this->canDownloadFile($file)) { // If we're trying to access a resampled image. if (preg_match('/_resampled\\/[^-]+-/', $url)) { // File::find() will always return the original image, but we still want to serve the resampled version. $file = new Image(); $file->Filename = $url; } $this->extend('onBeforeSendFile', $file); return $this->sendFile($file); } else { if ($file instanceof File) { // Permission failure Security::permissionFailure($this, 'You are not authorised to access this resource. Please log in.'); } else { // File doesn't exist $this->response = new SS_HTTPResponse('File Not Found', 404); } } return $this->response; }
public function format($event) { $errno = $event['message']['errno']; $errstr = $event['message']['errstr']; $errfile = $event['message']['errfile']; $errline = $event['message']['errline']; $errcontext = $event['message']['errcontext']; switch ($event['priorityName']) { case 'ERR': $errtype = 'Error'; break; case 'WARN': $errtype = 'Warning'; break; case 'NOTICE': $errtype = 'Notice'; break; } $urlSuffix = ''; $relfile = Director::makeRelative($errfile); if ($relfile[0] == '/') { $relfile = substr($relfile, 1); } if (isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] && isset($_SERVER['REQUEST_URI'])) { $urlSuffix = " (http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']})"; } return '[' . date('d-M-Y h:i:s') . "] {$errtype} at {$relfile} line {$errline}: {$errstr}{$urlSuffix}" . PHP_EOL; }
/** * Gets a thumbnail for this file given a size. If it's an Image, * it will render the actual file. If not, it will provide an icon based * on the extension. * @param int $w The width of the image * @param int $h The height of the image * @return Image_Cached */ public function getPreviewThumbnail($w = null, $h = null) { if (!$w) { $w = $this->owner->config()->grid_thumbnail_width; } if (!$h) { $h = $this->owner->config()->grid_thumbnail_height; } if ($this->IsImage()) { return $this->owner->CroppedImage($w, $h); } $sizes = Config::inst()->forClass('FileAttachmentField')->icon_sizes; sort($sizes); foreach ($sizes as $size) { if ($w <= $size) { if ($this->owner instanceof Folder) { $file = $this->getFilenameForType('_folder', $size); } else { $file = $this->getFilenameForType($this->owner->getExtension(), $size); } if (!file_exists(BASE_PATH . '/' . $file)) { $file = $this->getFilenameForType('_blank', $size); } return new Image_Cached(Director::makeRelative($file)); } } }
/** * Rebuilds the static cache for the pages passed through via $urls * @param array $urls The URLs of pages to re-fetch and cache. */ function rebuildCache($urls, $removeAll = true) { if (!is_array($urls)) { return; } // $urls must be an array if (!Director::is_cli()) { echo "<pre>\n"; } echo "Rebuilding cache.\nNOTE: Please ensure that this page ends with 'Done!' - if not, then something may have gone wrong.\n\n"; $page = singleton('Page'); foreach ($urls as $i => $url) { $url = Director::makeRelative($url); if (substr($url, -1) == '/') { $url = substr($url, 0, -1); } $urls[$i] = $url; } $urls = array_unique($urls); if ($removeAll && file_exists("../cache")) { echo "Removing old cache... \n"; flush(); Filesystem::removeFolder("../cache", true); echo "done.\n\n"; } echo "Republishing " . sizeof($urls) . " urls...\n\n"; $page->publishPages($urls); echo "\n\n== Done! =="; }
/** * 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; } }
/** * Write the log message to the file path set * in this writer. */ public function _write($event) { //Ignore Exceptions New Relic Catches these on it's own if (preg_match('/Uncaught ([A-Za-z]*)Exception: /', trim($errstr)) == true) { return; } $errno = $event['message']['errno']; $errstr = $event['message']['errstr']; $errfile = $event['message']['errfile']; $errline = $event['message']['errline']; $errcontext = $event['message']['errcontext']; switch ($event['priorityName']) { case 'ERR': $errtype = 'Error'; break; case 'WARN': $errtype = 'Warning'; break; case 'NOTICE': $errtype = 'Notice'; break; default: $errtype = $event['priorityName']; } $relfile = Director::makeRelative($errfile); if ($relfile && $relfile[0] == '/') { $relfile = substr($relfile, 1); } //If it's not an exception notice the error newrelic_notice_error($errno, "[{$errtype}] {$errstr} in {$relfile} line {$errline}", $errfile, $errline, $errcontext); }
function testCanViewProductGroupPage() { $g1 = $this->objFromFixture('ProductGroup', 'g1'); $g2 = $this->objFromFixture('ProductGroup', 'g2'); $this->get(Director::makeRelative($g1->Link())); $this->get(Director::makeRelative($g2->Link())); }
/** * @param array $event */ public function _write($event) { $debugbar = DebugBar::getDebugBar(); if (!$debugbar) { return; } /* @var $messagesCollector DebugBar\DataCollector\MessagesCollector */ $messagesCollector = $debugbar['messages']; if (!$messagesCollector) { return; } $level = $event['priorityName']; // Gather info if (isset($event['message']['errstr'])) { $str = $event['message']['errstr']; $file = $event['message']['errfile']; $line = $event['message']['errline']; } else { $str = $event['message']['function']; $file = $event['message']['file']; $line = isset($event['message']['line']) ? $event['message']['line'] : 0; } $relfile = Director::makeRelative($file); // Save message $message = "{$level} - {$str} ({$relfile}:{$line})"; // Escape \ for proper js display $message = str_replace('\\', '\\\\', $message); $messagesCollector->addMessage($message, false); }
/** * Create an {@link ErrorPage} for status code 503 * * @see UnderConstruction_Extension::onBeforeInit() * @see DataObjectDecorator::requireDefaultRecords() * @return Void */ function requireDefaultRecords() { // Ensure that an assets path exists before we do any error page creation if (!file_exists(ASSETS_PATH)) { mkdir(ASSETS_PATH); } $pageUnderConstructionErrorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = '503'"); $pageUnderConstructionErrorPageExists = $pageUnderConstructionErrorPage && $pageUnderConstructionErrorPage->exists() ? true : false; $pageUnderConstructionErrorPagePath = ErrorPage::get_filepath_for_errorcode(503); if (!($pageUnderConstructionErrorPageExists && file_exists($pageUnderConstructionErrorPagePath))) { if (!$pageUnderConstructionErrorPageExists) { $pageUnderConstructionErrorPage = new ErrorPage(); $pageUnderConstructionErrorPage->ErrorCode = 503; $pageUnderConstructionErrorPage->Title = _t('UnderConstruction.TITLE', 'Under Construction'); $pageUnderConstructionErrorPage->Content = _t('UnderConstruction.CONTENT', '<p>Sorry, this site is currently under construction.</p>'); $pageUnderConstructionErrorPage->Status = 'New page'; $pageUnderConstructionErrorPage->write(); $pageUnderConstructionErrorPage->publish('Stage', 'Live'); } // Ensure a static error page is created from latest error page content $response = Director::test(Director::makeRelative($pageUnderConstructionErrorPage->Link())); if ($fh = fopen($pageUnderConstructionErrorPagePath, 'w')) { $written = fwrite($fh, $response->getBody()); fclose($fh); } if ($written) { DB::alteration_message('503 error page created', 'created'); } else { DB::alteration_message(sprintf('503 error page could not be created at %s. Please check permissions', $pageUnderConstructionErrorPagePath), 'error'); } } }
public static function getSmileyDir() { $smileyDir = Director::makeRelative(realpath(dirname(__FILE__) . "/../images/smileys/")); $smileyDir = str_replace("\\", "/", $smileyDir); $smileyDir = Director::baseURL() . $smileyDir; return $smileyDir; }
/** * @param array $properties * * @return string - HTML */ public function FieldHolder($properties = array()) { $moduleDir = substr(Director::makeRelative(dirname(dirname(dirname(__FILE__)))), 1); Requirements::css($moduleDir . '/css/WidgetAreaEditor.css'); Requirements::javascript($moduleDir . '/javascript/WidgetAreaEditor.js'); return $this->renderWith("WidgetAreaEditor"); }
/** * Find the given folder or create it both as {@link Folder} database records * and on the filesystem. If necessary, creates parent folders as well. * * @param $folderPath string Absolute or relative path to the file. * If path is relative, its interpreted relative to the "assets/" directory. * @return Folder */ public static function find_or_make($folderPath) { // Create assets directory, if it is missing if (!file_exists(ASSETS_PATH)) { Filesystem::makeFolder(ASSETS_PATH); } $folderPath = trim(Director::makeRelative($folderPath)); // replace leading and trailing slashes $folderPath = preg_replace('/^\\/?(.*)\\/?$/', '$1', $folderPath); $parts = explode("/", $folderPath); $parentID = 0; $item = null; foreach ($parts as $part) { if (!$part) { continue; } // happens for paths with a trailing slash $item = DataObject::get_one("Folder", sprintf("\"Name\" = '%s' AND \"ParentID\" = %d", Convert::raw2sql($part), (int) $parentID)); if (!$item) { $item = new Folder(); $item->ParentID = $parentID; $item->Name = $part; $item->Title = $part; $item->write(); } if (!file_exists($item->getFullPath())) { Filesystem::makeFolder($item->getFullPath()); } $parentID = $item->ID; } return $item; }
/** * @param $key The nav key, e.g. "doc", "userhelp" * @return HTMLText */ public static function GlobalNav($key) { $baseURL = GlobalNavSiteTreeExtension::get_toolbar_baseurl(); Requirements::css(Controller::join_links($baseURL, Config::inst()->get('GlobalNav', 'css_path'))); // If this method haven't been called before, get the toolbar and cache it if (self::$global_nav_html === null) { // Set the default to empty self::$global_nav_html = ''; // Prevent recursion from happening if (empty($_GET['globaltoolbar'])) { $host = GlobalNavSiteTreeExtension::get_toolbar_hostname(); $path = Director::makeRelative(GlobalNavSiteTreeExtension::get_navbar_filename($key)); if (Config::inst()->get('GlobalNav', 'use_localhost')) { self::$global_nav_html = file_get_contents(BASE_PATH . $path); } else { $url = Controller::join_links($baseURL, $path, '?globaltoolbar=true'); $connectionTimeout = Config::inst()->get('GlobalNavTemplateProvider', 'connection_timeout'); $transferTimeout = Config::inst()->get('GlobalNavTemplateProvider', 'transfer_timeout'); // Get the HTML and cache it self::$global_nav_html = self::curl_call($url, $connectionTimeout, $transferTimeout); } } } $html = DBField::create_field('HTMLText', self::$global_nav_html); $html->setOptions(array('shortcodes' => false)); return $html; }
/** * Browse all enabled test cases in the environment */ function browse() { self::$default_reporter->writeHeader(); self::$default_reporter->writeInfo('Available Tests', false); if(Director::is_cli()) { $tests = ClassInfo::subclassesFor('SapphireTest'); $relativeLink = Director::makeRelative($this->Link()); echo "sake {$relativeLink}all: Run all " . count($tests) . " tests\n"; echo "sake {$relativeLink}coverage: Runs all tests and make test coverage report\n"; foreach ($tests as $test) { echo "sake {$relativeLink}$test: Run $test\n"; } } else { echo '<div class="trace">'; $tests = ClassInfo::subclassesFor('SapphireTest'); asort($tests); echo "<h3><a href=\"" . $this->Link() . "all\">Run all " . count($tests) . " tests</a></h3>"; echo "<h3><a href=\"" . $this->Link() . "coverage\">Runs all tests and make test coverage report</a></h3>"; echo "<hr />"; foreach ($tests as $test) { echo "<h3><a href=\"" . $this->Link() . "$test\">Run $test</a></h3>"; } echo '</div>'; } self::$default_reporter->writeFooter(); }
/** * Verifies that the language/locale is required on the url */ public function testMultilingualRequired() { $page = $this->objFromFixture('Page', 'page1'); $response = $this->get($page->URLSegment); $this->assertEquals(404, $response->getStatusCode()); $response = $this->get(Director::makeRelative($page->Link())); $this->assertEquals(200, $response->getStatusCode()); }
/** * Retrieve the appropriate link mapping for a URL. * * @parameter <{URL}> string * @parameter <{HOSTNAME}> string * @return link mapping */ public function getMapping($URL, $host = null) { $URL = self::is_external_URL($URL) ? parse_url($URL, PHP_URL_PATH) : Director::makeRelative($URL); $parts = explode('?', self::unify_URL($URL)); // Instantiate the link mapping query. $matches = LinkMapping::get(); // Enforce any hostname restriction that may have been defined. if (is_null($host) && ($controller = Controller::curr())) { $host = $controller->getRequest()->getHeader('Host'); } $temporary = $host; $host = Convert::raw2sql($host); $matches = $matches->where("(HostnameRestriction IS NULL) OR (HostnameRestriction = '{$host}')"); $regex = clone $matches; // Determine the simple matching from the database. $base = Convert::raw2sql($parts[0]); $matches = $matches->where("(LinkType = 'Simple') AND (((IncludesHostname = 0) AND ((MappedLink = '{$base}') OR (MappedLink LIKE '{$base}?%'))) OR ((IncludesHostname = 1) AND ((MappedLink = '{$host}/{$base}') OR (MappedLink LIKE '{$host}/{$base}?%'))))"); $host = $temporary; $base = $parts[0]; // Determine the remaining regular expression matching, as this is inconsistent from the database. $regex = $regex->filter('LinkType', 'Regular Expression'); $filtered = ArrayList::create(); foreach ($regex as $match) { if (!$match->IncludesHostname && preg_match("%{$match->MappedLink}%", $base) || $match->IncludesHostname && preg_match("%{$match->MappedLink}%", "{$host}/{$base}")) { $filtered->push($match); } } $filtered->merge($matches); $matches = $filtered; // Make sure the link mappings are ordered by priority and specificity. $matches = $matches->sort(array('Priority' => 'DESC', 'LinkType' => 'DESC', 'MappedLink' => 'DESC', 'ID' => Config::inst()->get('LinkMapping', 'priority'))); // Determine which link mapping should be returned, based on the sort order. $queryParameters = array(); if (isset($parts[1])) { parse_str($parts[1], $queryParameters); } foreach ($matches as $match) { // Make sure the link mapping is live on the current stage. if ($match->isLive() !== 'false') { // Ignore GET parameter matching for regular expressions, considering the special characters. $matchParts = explode('?', $match->MappedLink); if ($match->LinkType === 'Simple' && isset($matchParts[1])) { // Make sure the GET parameters match in any order. $matchParameters = array(); parse_str($matchParts[1], $matchParameters); if ($matchParameters == $queryParameters) { return $match; } } else { // Return the first link mapping when GET parameters aren't present. $match->setMatchedURL($match->IncludesHostname ? "{$host}/{$base}" : $base); return $match; } } } // No mapping has been found. return null; }
public function format($event) { switch ($event['priorityName']) { case 'ERR': $errorType = 'Error'; $colour = 'red'; break; case 'WARN': $errorType = 'Warning'; $colour = 'orange'; break; case 'NOTICE': $errorType = 'Notice'; $colour = 'grey'; break; default: $errorType = $event['priorityName']; $colour = 'grey'; } if (!is_array($event['message'])) { return false; } $errno = $event['message']['errno']; $errstr = $event['message']['errstr']; $errfile = $event['message']['errfile']; $errline = $event['message']['errline']; $errcontext = $event['message']['errcontext']; $data = ''; $data .= '<style type="text/css">html, body, table {font-family: sans-serif; font-size: 12px;}</style>'; $data .= "<div style=\"border: 5px {$colour} solid;\">\n"; $data .= "<p style=\"color: white; background-color: {$colour}; margin: 0\">[{$errorType}] "; $data .= nl2br(htmlspecialchars($errstr)) . "<br />{$errfile}:{$errline}\n<br />\n<br />\n</p>\n"; // Render the provided backtrace $data .= SS_Backtrace::get_rendered_backtrace($errcontext); // Compile extra data $blacklist = array('message', 'timestamp', 'priority', 'priorityName'); $extras = array_diff_key($event, array_combine($blacklist, $blacklist)); if ($extras) { $data .= "<h3>Details</h3>\n"; $data .= "<table class=\"extras\">\n"; foreach ($extras as $k => $v) { if (is_array($v)) { $v = var_export($v, true); } $data .= sprintf("<tr><td><strong>%s</strong></td><td><pre>%s</pre></td></tr>\n", $k, $v); } $data .= "</table>\n"; } $data .= "</div>\n"; $relfile = Director::makeRelative($errfile); if ($relfile && $relfile[0] == '/') { $relfile = substr($relfile, 1); } $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null; $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null; $subject = "[{$errorType}] in {$relfile}:{$errline} (http://{$host}{$uri})"; return array('subject' => $subject, 'data' => $data); }
/** * @param mixed $subject * @throws InvalidArgumentException * @return void */ public function send($subject) { if (!$subject instanceof Member) { return; } $sender = Member::currentUser(); $to = $subject->getEmail(); $from = defined('SURVEY_THANK_U_FROM_EMAIL') ? SURVEY_THANK_U_FROM_EMAIL : Config::inst()->get('Email', 'admin_email'); $email = EmailFactory::getInstance()->buildEmail($from, $to); $email->setUserTemplate('survey-builder-new-team-member')->populateTemplate(array('Sender' => $sender, 'Member' => $subject, 'Link' => Director::absoluteBaseURL() . Director::makeRelative('surveys')))->send(); }
public function getKeyword($keyword) { $k = $this->getAvailableKeywords(); if ($keyword == 'Link') { $link = Director::makeRelative($this->owner->Link()); return Controller::join_links(Director::absoluteBaseURL(), $link); } if (isset($k[$keyword])) { return $this->owner->{$keyword}; } }
/** * Overload some settings to make sure the right script is used. * * @return UploadifyField */ public function FieldHolder() { if (!$this->getSetting('s3script')) { $this->setVar('script', urlencode(Director::baseURL() . Director::makeRelative($this->Link('uploads3')))); } else { $this->setVar('script', $this->getSetting('s3script')); } if (!$this->Backend()) { $this->template = "UploadifyField"; } return parent::FieldHolder(); }
function export() { // specify custom baseurl for publishing to other webroot if (isset($_REQUEST['baseurl'])) { $base = $_REQUEST['baseurl']; if (substr($base, -1) != '/') { $base .= '/'; } Director::setBaseURL($base); } // setup temporary folders $tmpBaseFolder = TEMP_FOLDER . '/static-export'; $tmpFolder = project() ? "{$tmpBaseFolder}/" . project() : "{$tmpBaseFolder}/site"; if (!file_exists($tmpFolder)) { Filesystem::makeFolder($tmpFolder); } $baseFolderName = basename($tmpFolder); // symlink /assets $f1 = ASSETS_PATH; $f2 = Director::baseFolder() . '/' . project(); `cd {$tmpFolder}; ln -s {$f1}; ln -s {$f2}`; // iterate through all instances of SiteTree $pages = DataObject::get("SiteTree"); foreach ($pages as $page) { $subfolder = "{$tmpFolder}/" . trim($page->RelativeLink(null, true), '/'); $contentfile = "{$tmpFolder}/" . trim($page->RelativeLink(null, true), '/') . '/index.html'; // Make the folder if (!file_exists($subfolder)) { Filesystem::makeFolder($subfolder); } // Run the page Requirements::clear(); $link = Director::makeRelative($page->Link()); $response = Director::test($link); // Write to file if ($fh = fopen($contentfile, 'w')) { fwrite($fh, $response->getBody()); fclose($fh); } } // copy homepage (URLSegment: "home") to webroot copy("{$tmpFolder}/home/index.html", "{$tmpFolder}/index.html"); // archive all generated files `cd {$tmpBaseFolder}; tar -czhf {$baseFolderName}.tar.gz {$baseFolderName}`; $archiveContent = file_get_contents("{$tmpBaseFolder}/{$baseFolderName}.tar.gz"); // remove temporary files and folder Filesystem::removeFolder($tmpBaseFolder); // return as download to the client $response = SS_HTTPRequest::send_file($archiveContent, "{$baseFolderName}.tar.gz", 'application/x-tar-gz'); echo $response->output(); }
public function format($event) { switch ($event['priorityName']) { case 'ERR': $errorType = 'Error'; break; case 'WARN': $errorType = 'Warning'; break; case 'NOTICE': $errorType = 'Notice'; break; default: $errorType = $event['priorityName']; } if (!is_array($event['message'])) { return false; } $errno = $event['message']['errno']; $errstr = $event['message']['errstr']; $errfile = $event['message']['errfile']; $errline = $event['message']['errline']; $errcontext = $event['message']['errcontext']; $protocol = 'http'; if (isset($_SERVER['HTTPS'])) { $protocol = 'https'; } $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null; $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null; $relfile = Director::makeRelative($errfile); if ($relfile && $relfile[0] == '/') { $relfile = substr($relfile, 1); } $data = "[{$errorType}] in {$relfile}:{$errline} ({$protocol}://{$host}{$uri})\n"; // Render the provided backtrace $data .= SS_Backtrace::get_rendered_backtrace($errcontext, true); // Compile extra data $blacklist = array('message', 'timestamp', 'priority', 'priorityName'); $extras = array_diff_key($event, array_combine($blacklist, $blacklist)); if ($extras) { $data .= "DETAILS\n\n"; foreach ($extras as $k => $v) { if (is_array($v)) { $v = var_export($v, true); } $data .= sprintf("[%s]\n%s\n\n", strtoupper($k), $v); } } $subject = "[{$errorType}] in {$relfile}:{$errline} ({$host})"; return array('subject' => $subject, 'data' => $data); }
public function testMakeRelative() { $siteUrl = Director::absoluteBaseURL(); $siteUrlNoProtocol = preg_replace('/https?:\\/\\//', '', $siteUrl); $this->assertEquals(Director::makeRelative("{$siteUrl}"), ''); //$this->assertEquals(Director::makeRelative("https://$siteUrlNoProtocol"), ''); $this->assertEquals(Director::makeRelative(" {$siteUrl}/testpage "), 'testpage'); //$this->assertEquals(Director::makeRelative("$siteUrlNoProtocol/testpage"), 'testpage'); $this->assertEquals(Director::makeRelative('ftp://test.com'), 'ftp://test.com'); $this->assertEquals(Director::makeRelative('http://test.com'), 'http://test.com'); $this->assertEquals(Director::makeRelative('/relative'), '/relative'); $this->assertEquals(Director::makeRelative('relative'), 'relative'); $this->assertEquals(Director::makeRelative("{$siteUrl}/?url=http://test.com"), '?url=http://test.com'); }
function css($file, $media = null) { /** * Only initiate automatically if: * - webiste is in dev mode * - or a ?flush is called */ if (preg_match('/\\.less$/i', $file) || Director::isDev() || isset($_GET['flush'])) { /* If file is CSS, check if there is a LESS file */ if (preg_match('/\\.css$/i', $file)) { $less = preg_replace('/\\.css$/i', '.less', $file); if (is_file(Director::getAbsFile($less))) { $file = $less; } } /* If less file exists, then check/compile it */ if (preg_match('/\\.less$/i', $file)) { $out = preg_replace('/\\.less$/i', '.css', $file); $css_file = Director::getAbsFile($out); $options = array(); /* Automatically compress if in live mode */ if (Director::isLive()) { $options['compress'] = true; } try { /* Force recompile & only write to css if updated */ if (isset($_GET['flush']) || !Director::isLive()) { /* Create instance */ $parser = new Less_Parser($options); if (!empty(self::$variables)) { $parser->ModifyVars(self::$variables); } /* calculate the LESS file's parent URL */ $css_dir = rtrim(Director::baseURL(), '/') . Director::makeRelative(dirname(Director::getAbsFile($file)) . '/'); $parser->parseFile(Director::getAbsFile($file), $css_dir); $css = $parser->getCss(); if (!is_file($css_file) || md5_file($css_file) != md5($css)) { file_put_contents($css_file, $css); } } } catch (Exception $ex) { trigger_error("Less.php fatal error: " . $ex->getMessage(), E_USER_ERROR); } $file = $out; } } /* Return css path */ return parent::css($file, $media); }
public function testReflexiveAndTransitiveInternalRedirectors() { /* Reflexive redirectors are those that point to themselves. They should behave the same as an empty redirector */ $page = $this->objFromFixture('RedirectorPage', 'reflexive'); $this->assertEquals(Director::baseURL() . 'reflexive/', $page->Link()); $content = $this->get(Director::makeRelative($page->Link()))->getBody(); $this->assertContains('message-setupWithoutRedirect', $content); /* Transitive redirectors are those that point to another redirector page. They should send people to the URLSegment * of the destination page - the middle-stop, so to speak. That should redirect to the final destination */ $page = $this->objFromFixture('RedirectorPage', 'transitive'); $this->assertEquals(Director::baseURL() . 'good-internal/', $page->Link()); $this->autoFollowRedirection = false; $response = $this->get(Director::makeRelative($page->Link())); $this->assertEquals(Director::baseURL() . "redirection-dest/", $response->getHeader("Location")); }
/** * Renders the contents of a silverstripe URL into a PDF * * @param String $url A relative URL that silverstripe can execute * @param String $outputTo */ public function renderUrl($url, $outputTo = null, $outname = '') { if (strpos($url, '/') === 0) { // fix it $url = Director::makeRelative($url); } // convert the URL to content and 'test' the request, ensure the current session remains active $response = Director::test($url, null, new Session($_SESSION)); if ($response->getStatusCode() == 200) { $content = $response->getBody(); return $this->render($content, $outputTo, $outname); } else { throw new Exception("Failed rendering URL {$url}: " . $response->getStatusCode() . " - " . $response->getStatusDescription()); } }
public function onBeforeSendFile($file) { // check to make sure this is the actual file and not just a rendition... if that matters? $downloadRecord = new FileDownloadRecord(); // store the full filename for now $url = array_key_exists('url', $_GET) ? $_GET['url'] : $_SERVER['REQUEST_URI']; // check if it's a resampled file if (strpos($url, '_resampled') !== false) { // ignore it return; } $file_path = Director::makeRelative($url); $downloadRecord->Filename = $file_path ? $file_path : $file->getFilename(); $downloadRecord->FileID = $file->ID; $downloadRecord->write(); }
public function format($event) { switch ($event['priorityName']) { case 'ERR': $errorType = 'Error'; $colour = 'red'; break; case 'WARN': $errorType = 'Warning'; $colour = 'orange'; break; case 'NOTICE': $errorType = 'Notice'; $colour = 'grey'; break; } if (!is_array($event['message'])) { return false; } $errno = $event['message']['errno']; $errstr = $event['message']['errstr']; $errfile = $event['message']['errfile']; $errline = $event['message']['errline']; $errcontext = $event['message']['errcontext']; $ref = @$_SERVER['HTTP_REFERER']; if (empty($ref)) { $ref = 'N/A'; } if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } $data = "<div style=\"border: 5px {$colour} solid\">\n"; $data .= "<p style=\"color: white; background-color: {$colour}; margin: 0\">HTTP_REFERER :{$ref} - CLIENT_IP : {$ip} <br/>{$errorType}: {$errstr}<br/> At line {$errline} in {$errfile}\n<br />\n<br />\n</p>\n"; // Get a backtrace, filtering out debug method calls $data .= SS_Backtrace::backtrace(true, false, array('SS_LogErrorEmailFormatter->format', 'SS_LogEmailWriter->_write')); $data .= "</div>\n"; $relfile = Director::makeRelative($errfile); if ($relfile[0] == '/') { $relfile = substr($relfile, 1); } $subject = "{$errorType} at {$relfile} line {$errline} (http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']})"; return array('subject' => $subject, 'data' => $data); }
public function testDisabledOption() { // Enable module to error pages only Config::inst()->remove('Templater', 'enabled_for_pagetypes'); Config::inst()->update('Templater', 'enabled_for_pagetypes', ['ErrorPage']); $page = $this->createPage('blue'); $fields = $page->getCMSFields(); $this->assertEmpty($fields->dataFieldByName('Theme')); $this->assertEmpty($fields->dataFieldByName('PageTemplate')); // Assert page content $response = Director::test(Director::makeRelative($page->Link())); $this->assertContains('Theme Blue page content', $response->getBody()); $this->assertNotContains('I\'m in the Blue Theme', $response->getBody()); // Enable module to all pages Config::inst()->remove('Templater', 'enabled_for_pagetypes'); Config::inst()->update('Templater', 'enabled_for_pagetypes', 'all'); }