API CHANGE: Renamed conflicting classes to have an "SS_" namespace, and renamed existing "SS" namespace to "SS_". The affected classes are: HTTPRequest, HTTPResponse, Query, Database, SSBacktrace, SSCli, SSDatetime, SSDatetimeTest, SSLog, SSLogTest, SSLogEmailWriter, SSLogErrorEmailFormatter, SSLogErrorFileFormatter, SSLogFileWriter and SSZendLog.

MINOR: Replaced usage of renamed classes with the new namespaced name.

From: Andrew Short <andrewjshort@gmail.com>

git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@90075 467b73ca-7a2a-4603-9d3b-597d59a354a9
This commit is contained in:
Andrew Short 2009-10-26 03:06:31 +00:00 committed by Sam Minnee
parent a6562452ce
commit 79773042be
59 changed files with 353 additions and 351 deletions

16
_config.php Normal file → Executable file
View File

@ -36,17 +36,19 @@ Director::addRules(1, array(
'$URLSegment//$Action/$ID/$OtherID' => 'ModelAsController', '$URLSegment//$Action/$ID/$OtherID' => 'ModelAsController',
)); ));
/** /**
* Register the default internal shortcodes. * Register the default internal shortcodes.
*/ */
ShortcodeParser::get('default')->register('sitetree_link', array('SiteTree', 'link_shortcode_handler')); ShortcodeParser::get('default')->register('sitetree_link', array('SiteTree', 'link_shortcode_handler'));
/** /**
* PHP 5.2 has a namespace conflict with our datetime class, * PHP 5.2 introduced a conflict with the Datetime field type, which was renamed to SSDatetime. This was later renamed
* for legacy support, we use this overload method. * to SS_Datetime to be consistent with other namespaced classes.
* // ENFORCE STRONG_CREATE *
* Overload both of these to support legacy code.
*/ */
Object::useCustomClass('Datetime','SSDatetime',true); Object::useCustomClass('SSDatetime', 'SS_Datetime', true);
Object::useCustomClass('Datetime', 'SS_Datetime', true);
/** /**

View File

@ -315,7 +315,7 @@ class RestfulService extends ViewableData {
} }
} }
class RestfulService_Response extends HTTPResponse { class RestfulService_Response extends SS_HTTPResponse {
protected $simpleXML; protected $simpleXML;
function __construct($body, $statusCode = 200, $headers = null) { function __construct($body, $statusCode = 200, $headers = null) {

View File

@ -239,7 +239,7 @@ class SOAPModelAccess extends SapphireSoapServer {
} }
/** /**
* @param HTTPResponse $response * @param SS_HTTPResponse $response
* @return string XML string containing the HTTP error message * @return string XML string containing the HTTP error message
*/ */
protected function getErrorMessage($response) { protected function getErrorMessage($response) {

View File

@ -30,7 +30,7 @@ class ClassInfo {
private static $_cache_all_tables = null; private static $_cache_all_tables = null;
/** /**
* @todo Move this to Database or DB * @todo Move this to SS_Database or DB
*/ */
static function hasTable($class) { static function hasTable($class) {
if(DB::isActive()) { if(DB::isActive()) {

View File

@ -271,13 +271,13 @@ class HTTP {
/** /**
* Add the appropriate caching headers to the response, including If-Modified-Since / 304 handling. * Add the appropriate caching headers to the response, including If-Modified-Since / 304 handling.
* *
* @param HTTPResponse The HTTPResponse object to augment. Omitted the argument or passing a string is deprecated; in these * @param SS_HTTPResponse The SS_HTTPResponse object to augment. Omitted the argument or passing a string is deprecated; in these
* cases, the headers are output directly. * cases, the headers are output directly.
*/ */
static function add_cache_headers($body = null) { static function add_cache_headers($body = null) {
// Validate argument // Validate argument
if($body && !($body instanceof HTTPResponse)) { if($body && !($body instanceof SS_HTTPResponse)) {
user_error("HTTP::add_cache_headers() must be passed an HTTPResponse object", E_USER_WARNING); user_error("HTTP::add_cache_headers() must be passed an SS_HTTPResponse object", E_USER_WARNING);
$body = null; $body = null;
} }
@ -285,7 +285,7 @@ class HTTP {
// below. // below.
if(Director::isDev()) return; if(Director::isDev()) return;
// The headers have been sent and we don't have an HTTPResponse object to attach things to; no point in us trying. // The headers have been sent and we don't have an SS_HTTPResponse object to attach things to; no point in us trying.
if(headers_sent() && !$body) return; if(headers_sent() && !$body) return;
// Popuplate $responseHeaders with all the headers that we want to build // Popuplate $responseHeaders with all the headers that we want to build
@ -329,7 +329,7 @@ class HTTP {
$responseHeaders['ETag'] = self::$etag; $responseHeaders['ETag'] = self::$etag;
} }
// Now that we've generated them, either output them or attach them to the HTTPResponse as appropriate // Now that we've generated them, either output them or attach them to the SS_HTTPResponse as appropriate
foreach($responseHeaders as $k => $v) { foreach($responseHeaders as $k => $v) {
if($body) $body->addHeader($k, $v); if($body) $body->addHeader($k, $v);
else if(!headers_sent()) header("$k: $v"); else if(!headers_sent()) header("$k: $v");

View File

@ -217,7 +217,7 @@ class Requirements {
return self::backend()->includeInHTML($templateFile, $content); return self::backend()->includeInHTML($templateFile, $content);
} }
static function include_in_response(HTTPResponse $response) { static function include_in_response(SS_HTTPResponse $response) {
return self::backend()->include_in_response($response); return self::backend()->include_in_response($response);
} }
@ -643,7 +643,7 @@ class Requirements_Backend {
/** /**
* Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the HTTP response * Attach requirements inclusion to X-Include-JS and X-Include-CSS headers on the HTTP response
*/ */
function include_in_response(HTTPResponse $response) { function include_in_response(SS_HTTPResponse $response) {
$this->process_combined_files(); $this->process_combined_files();
$jsRequirements = array(); $jsRequirements = array();
$cssRequirements = array(); $cssRequirements = array();

View File

@ -123,9 +123,9 @@ class ContentController extends Controller {
* This acts the same as {@link Controller::handleRequest()}, but if an action cannot be found this will attempt to * This acts the same as {@link Controller::handleRequest()}, but if an action cannot be found this will attempt to
* fall over to a child controller in order to provide functionality for nested URLs. * fall over to a child controller in order to provide functionality for nested URLs.
* *
* @return HTTPResponse * @return SS_HTTPResponse
*/ */
public function handleRequest(HTTPRequest $request) { public function handleRequest(SS_HTTPRequest $request) {
$child = null; $child = null;
$action = $request->param('Action'); $action = $request->param('Action');
@ -163,7 +163,7 @@ class ContentController extends Controller {
if($this->request->isMedia() || !$response = ErrorPage::response_for($code)) { if($this->request->isMedia() || !$response = ErrorPage::response_for($code)) {
parent::httpError($code, $message); parent::httpError($code, $message);
} else { } else {
throw new HTTPResponse_Exception($response); throw new SS_HTTPResponse_Exception($response);
} }
} }

View File

@ -51,7 +51,7 @@ class ContentNegotiator {
return self::$encoding; return self::$encoding;
} }
static function process(HTTPResponse $response) { static function process(SS_HTTPResponse $response) {
if(!self::enabled_for($response)) return; if(!self::enabled_for($response)) return;
$mimes = array( $mimes = array(
@ -100,11 +100,11 @@ class ContentNegotiator {
* Assumes that a correct doctype is set, and doesn't change or append to it. * Assumes that a correct doctype is set, and doesn't change or append to it.
* Replaces a few common tags and entities with their XHTML representations (<br>, <img>, &nbsp;). * Replaces a few common tags and entities with their XHTML representations (<br>, <img>, &nbsp;).
* *
* @param $response HTTPResponse * @param $response SS_HTTPResponse
* @return string * @return string
* @todo More flexible tag and entity parsing through regular expressions or tag definition lists * @todo More flexible tag and entity parsing through regular expressions or tag definition lists
*/ */
function xhtml(HTTPResponse $response) { function xhtml(SS_HTTPResponse $response) {
$content = $response->getBody(); $content = $response->getBody();
// Only serve "pure" XHTML if the XML header is present // Only serve "pure" XHTML if the XML header is present
@ -130,7 +130,7 @@ class ContentNegotiator {
* Replaces all occurrences of "application/xhtml+xml" with "text/html" in the template. * Replaces all occurrences of "application/xhtml+xml" with "text/html" in the template.
* Removes "xmlns" attributes and any <?xml> Pragmas. * Removes "xmlns" attributes and any <?xml> Pragmas.
*/ */
function html(HTTPResponse $response) { function html(SS_HTTPResponse $response) {
$response->addHeader("Content-Type", "text/html; charset=" . self::$encoding); $response->addHeader("Content-Type", "text/html; charset=" . self::$encoding);
$response->addHeader("Vary", "Accept"); $response->addHeader("Vary", "Accept");

View File

@ -18,8 +18,8 @@ class Controller extends RequestHandler {
/** /**
* @var array $requestParams Contains all GET and POST parameters * @var array $requestParams Contains all GET and POST parameters
* passed to the current {@link HTTPRequest}. * passed to the current {@link SS_HTTPRequest}.
* @uses HTTPRequest->requestVars() * @uses SS_HTTPRequest->requestVars()
*/ */
protected $requestParams; protected $requestParams;
@ -46,13 +46,13 @@ class Controller extends RequestHandler {
protected $basicAuthEnabled = true; protected $basicAuthEnabled = true;
/** /**
* @var HTTPResponse $response The response object that the controller returns. * @var SS_HTTPResponse $response The response object that the controller returns.
* Set in {@link handleRequest()}. * Set in {@link handleRequest()}.
*/ */
protected $response; protected $response;
/** /**
* @var HTTPRequest $request The request object that the controller was called with. * @var SS_HTTPRequest $request The request object that the controller was called with.
* Set in {@link handleRequest()}. Useful to generate the {} * Set in {@link handleRequest()}. Useful to generate the {}
*/ */
protected $request; protected $request;
@ -94,7 +94,7 @@ class Controller extends RequestHandler {
} }
/** /**
* Executes this controller, and return an {@link HTTPResponse} object with the result. * Executes this controller, and return an {@link SS_HTTPResponse} object with the result.
* *
* This method first does a few set-up activities: * This method first does a few set-up activities:
* - Push this controller ont to the controller stack - * - Push this controller ont to the controller stack -
@ -119,18 +119,18 @@ class Controller extends RequestHandler {
* and end the method with $this->popCurrent(). * and end the method with $this->popCurrent().
* Failure to do this will create weird session errors. * Failure to do this will create weird session errors.
* *
* @param $request The {@link HTTPRequest} object that is responsible * @param $request The {@link SS_HTTPRequest} object that is responsible
* for distributing request parsing. * for distributing request parsing.
* @return HTTPResponse The response that this controller produces, * @return SS_HTTPResponse The response that this controller produces,
* including HTTP headers such as redirection info * including HTTP headers such as redirection info
*/ */
function handleRequest(HTTPRequest $request) { function handleRequest(SS_HTTPRequest $request) {
if(!$request) user_error("Controller::handleRequest() not passed a request!", E_USER_ERROR); if(!$request) user_error("Controller::handleRequest() not passed a request!", E_USER_ERROR);
$this->pushCurrent(); $this->pushCurrent();
$this->urlParams = $request->allParams(); $this->urlParams = $request->allParams();
$this->request = $request; $this->request = $request;
$this->response = new HTTPResponse(); $this->response = new SS_HTTPResponse();
$this->extend('onBeforeInit'); $this->extend('onBeforeInit');
@ -148,8 +148,8 @@ class Controller extends RequestHandler {
} }
$body = parent::handleRequest($request); $body = parent::handleRequest($request);
if($body instanceof HTTPResponse) { if($body instanceof SS_HTTPResponse) {
if(isset($_REQUEST['debug_request'])) Debug::message("Request handler returned HTTPResponse object to $this->class controller; returning it without modification."); if(isset($_REQUEST['debug_request'])) Debug::message("Request handler returned SS_HTTPResponse object to $this->class controller; returning it without modification.");
$this->response = $body; $this->response = $body;
} else { } else {
@ -218,7 +218,7 @@ class Controller extends RequestHandler {
} }
/** /**
* Returns the HTTPResponse object that this controller is building up. * Returns the SS_HTTPResponse object that this controller is building up.
* Can be used to set the status code and headers * Can be used to set the status code and headers
*/ */
function getResponse() { function getResponse() {
@ -229,7 +229,7 @@ class Controller extends RequestHandler {
* Get the request with which this controller was called (if any). * Get the request with which this controller was called (if any).
* Usually set in {@link handleRequest()}. * Usually set in {@link handleRequest()}.
* *
* @return HTTPRequest * @return SS_HTTPRequest
*/ */
function getRequest() { function getRequest() {
return $this->request; return $this->request;

View File

@ -77,7 +77,7 @@ class Director {
* Process the given URL, creating the appropriate controller and executing it. * Process the given URL, creating the appropriate controller and executing it.
* *
* Request processing is handled as folows: * Request processing is handled as folows:
* - Director::direct() creates a new HTTPResponse object and passes this to Director::handleRequest(). * - Director::direct() creates a new SS_HTTPResponse object and passes this to Director::handleRequest().
* - Director::handleRequest($request) checks each of the Director rules and identifies a controller to handle this * - Director::handleRequest($request) checks each of the Director rules and identifies a controller to handle this
* request. * request.
* - Controller::handleRequest($request) is then called. This will find a rule to handle the URL, and call the rule * - Controller::handleRequest($request) is then called. This will find a rule to handle the URL, and call the rule
@ -108,7 +108,7 @@ class Director {
} }
} }
$req = new HTTPRequest( $req = new SS_HTTPRequest(
(isset($_SERVER['X-HTTP-Method-Override'])) ? $_SERVER['X-HTTP-Method-Override'] : $_SERVER['REQUEST_METHOD'], (isset($_SERVER['X-HTTP-Method-Override'])) ? $_SERVER['X-HTTP-Method-Override'] : $_SERVER['REQUEST_METHOD'],
$url, $url,
$_GET, $_GET,
@ -129,17 +129,17 @@ class Director {
// Return code for a redirection request // Return code for a redirection request
if(is_string($result) && substr($result,0,9) == 'redirect:') { if(is_string($result) && substr($result,0,9) == 'redirect:') {
$response = new HTTPResponse(); $response = new SS_HTTPResponse();
$response->redirect(substr($result, 9)); $response->redirect(substr($result, 9));
$response->output(); $response->output();
// Handle a controller // Handle a controller
} else if($result) { } else if($result) {
if($result instanceof HTTPResponse) { if($result instanceof SS_HTTPResponse) {
$response = $result; $response = $result;
} else { } else {
$response = new HTTPResponse(); $response = new SS_HTTPResponse();
$response->setBody($result); $response->setBody($result);
} }
@ -170,7 +170,7 @@ class Director {
* Overwritten by $postVars['_method'] if present. * Overwritten by $postVars['_method'] if present.
* @param string $body The HTTP body * @param string $body The HTTP body
* @param array $headers HTTP headers with key-value pairs * @param array $headers HTTP headers with key-value pairs
* @return HTTPResponse * @return SS_HTTPResponse
* *
* @uses getControllerForURL() The rule-lookup logic is handled by this. * @uses getControllerForURL() The rule-lookup logic is handled by this.
* @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call. * @uses Controller::run() Controller::run() handles the page logic for a Director::direct() call.
@ -219,7 +219,7 @@ class Director {
$_COOKIE = array(); $_COOKIE = array();
$_SERVER['REQUEST_URI'] = Director::baseURL() . $urlWithQuerystring; $_SERVER['REQUEST_URI'] = Director::baseURL() . $urlWithQuerystring;
$req = new HTTPRequest($httpMethod, $url, $getVars, $postVars, $body); $req = new SS_HTTPRequest($httpMethod, $url, $getVars, $postVars, $body);
if($headers) foreach($headers as $k => $v) $req->addHeader($k, $v); if($headers) foreach($headers as $k => $v) $req->addHeader($k, $v);
$result = Director::handleRequest($req, $session); $result = Director::handleRequest($req, $session);
@ -242,11 +242,11 @@ class Director {
} }
/** /**
* Handle an HTTP request, defined with a HTTPRequest object. * Handle an HTTP request, defined with a SS_HTTPRequest object.
* *
* @return HTTPResponse|string * @return SS_HTTPResponse|string
*/ */
protected static function handleRequest(HTTPRequest $request, Session $session) { protected static function handleRequest(SS_HTTPRequest $request, Session $session) {
krsort(Director::$rules); krsort(Director::$rules);
if(isset($_REQUEST['debug'])) Debug::show(Director::$rules); if(isset($_REQUEST['debug'])) Debug::show(Director::$rules);
@ -732,7 +732,7 @@ class Director {
*/ */
static function set_environment_type($et) { static function set_environment_type($et) {
if($et != 'dev' && $et != 'test' && $et != 'live') { if($et != 'dev' && $et != 'test' && $et != 'live') {
SSBacktrace::backtrace(); SS_Backtrace::backtrace();
user_error("Director::set_environment_type passed '$et'. It should be passed dev, test, or live", E_USER_WARNING); user_error("Director::set_environment_type passed '$et'. It should be passed dev, test, or live", E_USER_WARNING);
} else { } else {
self::$environment_type = $et; self::$environment_type = $et;

View File

@ -4,7 +4,7 @@
* Represents a HTTP-request, including a URL that is tokenised for parsing, and a request method (GET/POST/PUT/DELETE). * Represents a HTTP-request, including a URL that is tokenised for parsing, and a request method (GET/POST/PUT/DELETE).
* This is used by {@link RequestHandler} objects to decide what to do. * This is used by {@link RequestHandler} objects to decide what to do.
* *
* The intention is that a single HTTPRequest object can be passed from one object to another, each object calling * The intention is that a single SS_HTTPRequest object can be passed from one object to another, each object calling
* match() to get the information that they need out of the URL. This is generally handled by * match() to get the information that they need out of the URL. This is generally handled by
* {@link RequestHandler::handleRequest()}. * {@link RequestHandler::handleRequest()}.
* *
@ -14,7 +14,7 @@
* @package sapphire * @package sapphire
* @subpackage control * @subpackage control
*/ */
class HTTPRequest implements ArrayAccess { class SS_HTTPRequest implements ArrayAccess {
/** /**
* @var string $url * @var string $url
@ -85,7 +85,7 @@ class HTTPRequest implements ArrayAccess {
protected $unshiftedButParsedParts = 0; protected $unshiftedButParsedParts = 0;
/** /**
* Construct a HTTPRequest from a URL relative to the site root. * Construct a SS_HTTPRequest from a URL relative to the site root.
*/ */
function __construct($httpMethod, $url, $getVars = array(), $postVars = array(), $body = null) { function __construct($httpMethod, $url, $getVars = array(), $postVars = array(), $body = null) {
$this->httpMethod = strtoupper(self::detect_method($httpMethod, $postVars)); $this->httpMethod = strtoupper(self::detect_method($httpMethod, $postVars));
@ -176,7 +176,7 @@ class HTTPRequest implements ArrayAccess {
} }
/** /**
* Checks if the {@link HTTPRequest->getExtension()} on this request matches one of the more common media types * Checks if the {@link SS_HTTPRequest->getExtension()} on this request matches one of the more common media types
* embedded into a webpage - e.g. css, png. * embedded into a webpage - e.g. css, png.
* *
* This is useful for things like determining wether to display a fully rendered error page or not. Note that the * This is useful for things like determining wether to display a fully rendered error page or not. Note that the
@ -265,12 +265,12 @@ class HTTPRequest implements ArrayAccess {
function offsetUnset($offset) {} function offsetUnset($offset) {}
/** /**
* Construct an HTTPResponse that will deliver a file to the client * Construct an SS_HTTPResponse that will deliver a file to the client
*/ */
static function send_file($fileData, $fileName, $mimeType = null) { static function send_file($fileData, $fileName, $mimeType = null) {
if(!$mimeType) $mimeType = HTTP::getMimeType($fileName); if(!$mimeType) $mimeType = HTTP::getMimeType($fileName);
$response = new HTTPResponse($fileData); $response = new SS_HTTPResponse($fileData);
$response->addHeader("Content-Type", "$mimeType; name=\"" . addslashes($fileName) . "\""); $response->addHeader("Content-Type", "$mimeType; name=\"" . addslashes($fileName) . "\"");
$response->addHeader("Content-disposition", "attachment; filename=" . addslashes($fileName)); $response->addHeader("Content-disposition", "attachment; filename=" . addslashes($fileName));
$response->addHeader("Content-Length", strlen($fileData)); $response->addHeader("Content-Length", strlen($fileData));

View File

@ -1,11 +1,11 @@
<?php <?php
/** /**
* Represenets an HTTPResponse returned by a controller. * Represents a response returned by a controller.
* *
* @package sapphire * @package sapphire
* @subpackage control * @subpackage control
*/ */
class HTTPResponse { class SS_HTTPResponse {
protected static $status_codes = array( protected static $status_codes = array(
100 => 'Continue', 100 => 'Continue',
101 => 'Switching Protocols', 101 => 'Switching Protocols',
@ -214,7 +214,7 @@ class HTTPResponse {
*/ */
public function getLinks() { public function getLinks() {
user_error ( user_error (
'HTTPResponse->getLinks() is deprecated, please use HTTP::getLinksIn() or DOMDocument.', E_USER_NOTICE 'SS_HTTPResponse->getLinks() is deprecated, please use HTTP::getLinksIn() or DOMDocument.', E_USER_NOTICE
); );
$attributes = array('id', 'href', 'class'); $attributes = array('id', 'href', 'class');
@ -238,46 +238,46 @@ class HTTPResponse {
} }
/** /**
* A {@link HTTPResponse} encapsulated in an exception, which can interrupt the processing flow and be caught by the * A {@link SS_HTTPResponse} encapsulated in an exception, which can interrupt the processing flow and be caught by the
* {@link RequestHandler} and returned to the user. * {@link RequestHandler} and returned to the user.
* *
* Example Usage: * Example Usage:
* <code> * <code>
* throw new HTTPResponse_Exception('This request was invalid.', 400); * throw new SS_HTTPResponse_Exception('This request was invalid.', 400);
* throw new HTTPResponse_Exception(new HTTPResponse('There was an internal server error.', 500)); * throw new SS_HTTPResponse_Exception(new SS_HTTPResponse('There was an internal server error.', 500));
* </code> * </code>
* *
* @package sapphire * @package sapphire
* @subpackage control * @subpackage control
*/ */
class HTTPResponse_Exception extends Exception { class SS_HTTPResponse_Exception extends Exception {
protected $response; protected $response;
/** /**
* @see HTTPResponse::__construct(); * @see SS_HTTPResponse::__construct();
*/ */
public function __construct($body = null, $statusCode = null, $statusDescription = null) { public function __construct($body = null, $statusCode = null, $statusDescription = null) {
if($body instanceof HTTPResponse) { if($body instanceof SS_HTTPResponse) {
$this->setResponse($body); $this->setResponse($body);
} else { } else {
$this->setResponse(new HTTPResponse($body, $statusCode, $statusDescription)); $this->setResponse(new SS_HTTPResponse($body, $statusCode, $statusDescription));
} }
parent::__construct($this->getResponse()->getBody(), $this->getResponse()->getStatusCode()); parent::__construct($this->getResponse()->getBody(), $this->getResponse()->getStatusCode());
} }
/** /**
* @return HTTPResponse * @return SS_HTTPResponse
*/ */
public function getResponse() { public function getResponse() {
return $this->response; return $this->response;
} }
/** /**
* @param HTTPResponse $response * @param SS_HTTPResponse $response
*/ */
public function setResponse(HTTPResponse $response) { public function setResponse(SS_HTTPResponse $response) {
$this->response = $response; $this->response = $response;
} }

View File

@ -32,9 +32,9 @@ class ModelAsController extends Controller implements NestedController {
/** /**
* @uses ModelAsController::getNestedController() * @uses ModelAsController::getNestedController()
* @return HTTPResponse * @return SS_HTTPResponse
*/ */
public function handleRequest(HTTPRequest $request) { public function handleRequest(SS_HTTPRequest $request) {
$this->request = $request; $this->request = $request;
$this->pushCurrent(); $this->pushCurrent();
@ -42,7 +42,7 @@ class ModelAsController extends Controller implements NestedController {
// If the database has not yet been created, redirect to the build page. // If the database has not yet been created, redirect to the build page.
if(!DB::isActive() || !ClassInfo::hasTable('SiteTree')) { if(!DB::isActive() || !ClassInfo::hasTable('SiteTree')) {
$this->response = new HTTPResponse(); $this->response = new SS_HTTPResponse();
$this->response->redirect('dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null)); $this->response->redirect('dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
$this->popCurrent(); $this->popCurrent();
@ -80,7 +80,7 @@ class ModelAsController extends Controller implements NestedController {
if(!$sitetree) { if(!$sitetree) {
// If a root page has been renamed, redirect to the new location. // If a root page has been renamed, redirect to the new location.
if($redirect = $this->findOldPage($URLSegment)) { if($redirect = $this->findOldPage($URLSegment)) {
$this->response = new HTTPResponse(); $this->response = new SS_HTTPResponse();
$this->response->redirect($redirect->Link ( $this->response->redirect($redirect->Link (
Controller::join_links($request->param('Action'), $request->param('ID'), $request->param('OtherID')) Controller::join_links($request->param('Action'), $request->param('ID'), $request->param('OtherID'))
)); ));

View File

@ -6,7 +6,7 @@
* Any RequestHandler object can be made responsible for handling its own segment of the URL namespace. * Any RequestHandler object can be made responsible for handling its own segment of the URL namespace.
* The {@link Director} begins the URL parsing process; it will parse the beginning of the URL to identify which * The {@link Director} begins the URL parsing process; it will parse the beginning of the URL to identify which
* controller is being used. It will then call {@link handleRequest()} on that Controller, passing it the parameters that it * controller is being used. It will then call {@link handleRequest()} on that Controller, passing it the parameters that it
* parsed from the URL, and the {@link HTTPRequest} that contains the remainder of the URL to be parsed. * parsed from the URL, and the {@link SS_HTTPRequest} that contains the remainder of the URL to be parsed.
* *
* You can use ?debug_request=1 to view information about the different components and rule matches for a specific URL. * You can use ?debug_request=1 to view information about the different components and rule matches for a specific URL.
* *
@ -44,7 +44,7 @@ class RequestHandler extends ViewableData {
* The default URL handling rules. This specifies that the next component of the URL corresponds to a method to * The default URL handling rules. This specifies that the next component of the URL corresponds to a method to
* be called on this RequestHandlingData object. * be called on this RequestHandlingData object.
* *
* The keys of this array are parse rules. See {@link HTTPRequest::match()} for a description of the rules available. * The keys of this array are parse rules. See {@link SS_HTTPRequest::match()} for a description of the rules available.
* *
* The values of the array are the method to be called if the rule matches. If this value starts with a '$', then the * The values of the array are the method to be called if the rule matches. If this value starts with a '$', then the
* named parameter of the parsed URL wil be used to determine the method name. * named parameter of the parsed URL wil be used to determine the method name.
@ -91,10 +91,10 @@ class RequestHandler extends ViewableData {
* customise the controller. * customise the controller.
* *
* @param $params The parameters taken from the parsed URL of the parent url handler * @param $params The parameters taken from the parsed URL of the parent url handler
* @param $request The {@link HTTPRequest} object that is reponsible for distributing URL parsing * @param $request The {@link SS_HTTPRequest} object that is reponsible for distributing URL parsing
* @uses HTTPRequest * @uses SS_HTTPRequest
* @uses HTTPRequest->match() * @uses SS_HTTPRequest->match()
* @return HTTPResponse|RequestHandler|string|array * @return SS_HTTPResponse|RequestHandler|string|array
*/ */
function handleRequest($request) { function handleRequest($request) {
// $handlerClass is used to step up the class hierarchy to implement url_handlers inheritance // $handlerClass is used to step up the class hierarchy to implement url_handlers inheritance
@ -133,14 +133,14 @@ class RequestHandler extends ViewableData {
try { try {
$result = $this->$action($request); $result = $this->$action($request);
} catch(HTTPResponse_Exception $responseException) { } catch(SS_HTTPResponse_Exception $responseException) {
$result = $responseException->getResponse(); $result = $responseException->getResponse();
} }
} else { } else {
return $this->httpError(403, "Action '$action' isn't allowed on class $this->class"); return $this->httpError(403, "Action '$action' isn't allowed on class $this->class");
} }
if($result instanceof HTTPResponse && $result->isError()) { if($result instanceof SS_HTTPResponse && $result->isError()) {
if(isset($_REQUEST['debug_request'])) Debug::message("Rule resulted in HTTP error; breaking"); if(isset($_REQUEST['debug_request'])) Debug::message("Rule resulted in HTTP error; breaking");
return $result; return $result;
} }
@ -276,21 +276,21 @@ class RequestHandler extends ViewableData {
} }
/** /**
* Throws a HTTP error response encased in a {@link HTTPResponse_Exception}, which is later caught in * Throws a HTTP error response encased in a {@link SS_HTTPResponse_Exception}, which is later caught in
* {@link RequestHandler::handleAction()} and returned to the user. * {@link RequestHandler::handleAction()} and returned to the user.
* *
* @param int $errorCode * @param int $errorCode
* @param string $errorMessage * @param string $errorMessage
* @uses HTTPResponse_Exception * @uses SS_HTTPResponse_Exception
*/ */
public function httpError($errorCode, $errorMessage = null) { public function httpError($errorCode, $errorMessage = null) {
throw new HTTPResponse_Exception($errorMessage, $errorCode); throw new SS_HTTPResponse_Exception($errorMessage, $errorCode);
} }
/** /**
* Returns the HTTPRequest object that this controller is using. * Returns the SS_HTTPRequest object that this controller is using.
* *
* @return HTTPRequest * @return SS_HTTPRequest
*/ */
function getRequest() { function getRequest() {
return $this->request; return $this->request;

View File

@ -98,23 +98,23 @@ class RootURLController extends Controller {
} }
/** /**
* @param HTTPRequest $request * @param SS_HTTPRequest $request
* @return HTTPResponse * @return SS_HTTPResponse
*/ */
public function handleRequest(HTTPRequest $request) { public function handleRequest(SS_HTTPRequest $request) {
self::$is_at_root = true; self::$is_at_root = true;
$this->pushCurrent(); $this->pushCurrent();
$this->init(); $this->init();
if(!DB::isActive() || !ClassInfo::hasTable('SiteTree')) { if(!DB::isActive() || !ClassInfo::hasTable('SiteTree')) {
$this->response = new HTTPResponse(); $this->response = new SS_HTTPResponse();
$this->response->redirect('dev/build/?returnURL='); $this->response->redirect('dev/build/?returnURL=');
return $this->response; return $this->response;
} }
$request = new HTTPRequest ( $request = new SS_HTTPRequest (
$request->httpMethod(), self::get_homepage_link() . '/', $request->getVars(), $request->postVars() $request->httpMethod(), self::get_homepage_link() . '/', $request->getVars(), $request->postVars()
); );
$request->match('$URLSegment//$Action', true); $request->match('$URLSegment//$Action', true);

View File

@ -8,7 +8,7 @@
class DB { class DB {
/** /**
* The global database connection. * The global database connection.
* @var Database * @var SS_Database
*/ */
private static $connections = array(); private static $connections = array();
@ -25,7 +25,7 @@ class DB {
/** /**
* Set the global database connection. * Set the global database connection.
* Pass an object that's a subclass of Database. This object will be used when {@link DB::query()} * Pass an object that's a subclass of SS_Database. This object will be used when {@link DB::query()}
* is called. * is called.
* @param $connection The connecton object to set as the connection. * @param $connection The connecton object to set as the connection.
* @param $name The name to give to this connection. If you omit this argument, the connection * @param $name The name to give to this connection. If you omit this argument, the connection
@ -33,7 +33,7 @@ class DB {
* be accessed through DB::getConn($name). This is useful when you have an application that * be accessed through DB::getConn($name). This is useful when you have an application that
* needs to connect to more than one database. * needs to connect to more than one database.
*/ */
static function setConn(Database $connection, $name = 'default') { static function setConn(SS_Database $connection, $name = 'default') {
self::$connections[$name] = $connection; self::$connections[$name] = $connection;
} }
@ -41,7 +41,7 @@ class DB {
* Get the global database connection. * Get the global database connection.
* @param $name An optional name given to a connection in the DB::setConn() call. If omitted, * @param $name An optional name given to a connection in the DB::setConn() call. If omitted,
* the default connection is returned. * the default connection is returned.
* @return Database * @return SS_Database
*/ */
static function getConn($name = 'default') { static function getConn($name = 'default') {
if(isset(self::$connections[$name])) { if(isset(self::$connections[$name])) {
@ -67,9 +67,9 @@ class DB {
/** /**
* Connect to a database. * Connect to a database.
* Given the database configuration, this method will create the correct subclass of Database, * Given the database configuration, this method will create the correct subclass of SS_Database,
* and set it as the global connection. * and set it as the global connection.
* @param array $database A map of options. The 'type' is the name of the subclass of Database to use. For the rest of the options, see the specific class. * @param array $database A map of options. The 'type' is the name of the subclass of SS_Database to use. For the rest of the options, see the specific class.
*/ */
static function connect($databaseConfig) { static function connect($databaseConfig) {
// This is used by TestRunner::startsession() to test up a test session using an alt // This is used by TestRunner::startsession() to test up a test session using an alt
@ -109,7 +109,7 @@ class DB {
* Execute the given SQL query. * Execute the given SQL query.
* @param string $sql The SQL query to execute * @param string $sql The SQL query to execute
* @param int $errorLevel The level of error reporting to enable for the query * @param int $errorLevel The level of error reporting to enable for the query
* @return Query * @return SS_Query
*/ */
static function query($sql, $errorLevel = E_USER_ERROR) { static function query($sql, $errorLevel = E_USER_ERROR) {
self::$lastQuery = $sql; self::$lastQuery = $sql;
@ -161,9 +161,9 @@ class DB {
* initial database connection is not successful because the database * initial database connection is not successful because the database
* does not exist. * does not exist.
* @param string $connect Connection string * @param string $connect Connection string
* @param string $username Database username * @param string $username SS_Database username
* @param string $password Database Password * @param string $password SS_Database Password
* @param string $database Database to which to create * @param string $database SS_Database to which to create
* @return boolean Returns true if successful * @return boolean Returns true if successful
*/ */
static function createDatabase($connect, $username, $password, $database) { static function createDatabase($connect, $username, $password, $database) {
@ -240,7 +240,7 @@ class DB {
} }
/** /**
* See {@link Database->dontRequireField()}. * See {@link SS_Database->dontRequireField()}.
* *
* @param string $table The table name. * @param string $table The table name.
* @param string $fieldName * @param string $fieldName

View File

@ -171,8 +171,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
return array_merge ( return array_merge (
array ( array (
'ClassName' => "Enum('" . implode(', ', ClassInfo::subclassesFor($class)) . "')", 'ClassName' => "Enum('" . implode(', ', ClassInfo::subclassesFor($class)) . "')",
'Created' => 'SSDatetime', 'Created' => 'SS_Datetime',
'LastEdited' => 'SSDatetime' 'LastEdited' => 'SS_Datetime'
), ),
self::custom_database_fields($class) self::custom_database_fields($class)
); );
@ -317,12 +317,12 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
foreach($record as $k => $v) { foreach($record as $k => $v) {
if($v) { if($v) {
if($k == 'Created' || $k == 'LastEdited') { if($k == 'Created' || $k == 'LastEdited') {
$fieldtype = 'SSDatetime'; $fieldtype = 'SS_Datetime';
} else { } else {
$fieldtype = $this->db($k); $fieldtype = $this->db($k);
} }
// MSSQLDatabase::date() uses datetime for the data type for "Date" and "SSDatetime" // MSSQLDatabase::date() uses datetime for the data type for "Date" and "SS_Datetime"
switch($fieldtype) { switch($fieldtype) {
case "Date": case "Date":
$v = preg_replace('/:[0-9][0-9][0-9]([ap]m)$/i', ' \\1', $v); $v = preg_replace('/:[0-9][0-9][0-9]([ap]m)$/i', ' \\1', $v);
@ -330,7 +330,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
break; break;
case "Datetime": case "Datetime":
case "SSDatetime": case "SS_Datetime":
$v = preg_replace('/:[0-9][0-9][0-9]([ap]m)$/i', ' \\1', $v); $v = preg_replace('/:[0-9][0-9][0-9]([ap]m)$/i', ' \\1', $v);
$record[$k] = date('Y-m-d H:i:s', strtotime($v)); $record[$k] = date('Y-m-d H:i:s', strtotime($v));
break; break;
@ -2136,8 +2136,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
static $fixedFields = array( static $fixedFields = array(
'ID' => 'Int', 'ID' => 'Int',
'ClassName' => 'Enum', 'ClassName' => 'Enum',
'LastEdited' => 'SSDatetime', 'LastEdited' => 'SS_Datetime',
'Created' => 'SSDatetime', 'Created' => 'SS_Datetime',
); );
if(isset($fixedFields[$field])) return true; if(isset($fixedFields[$field])) return true;
@ -2155,8 +2155,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
// Add base fields which are not defined in static $db // Add base fields which are not defined in static $db
if($field == "ID") return "Int"; if($field == "ID") return "Int";
if($field == "ClassName" && get_parent_class($this) == "DataObject") return "Enum"; if($field == "ClassName" && get_parent_class($this) == "DataObject") return "Enum";
if($field == "LastEdited" && get_parent_class($this) == "DataObject") return "SSDatetime"; if($field == "LastEdited" && get_parent_class($this) == "DataObject") return "SS_Datetime";
if($field == "Created" && get_parent_class($this) == "DataObject") return "SSDatetime"; if($field == "Created" && get_parent_class($this) == "DataObject") return "SS_Datetime";
// Add fields from Versioned decorator // Add fields from Versioned decorator
if($field == "Version") return $this->hasExtension('Versioned') ? "Int" : false; if($field == "Version") return $this->hasExtension('Versioned') ? "Int" : false;
@ -2633,9 +2633,9 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
} }
/** /**
* Take a database {@link Query} and instanciate an object for each record. * Take a database {@link SS_Query} and instanciate an object for each record.
* *
* @param Query|array $records The database records, a {@link Query} object or an array of maps. * @param SS_Query|array $records The database records, a {@link SS_Query} object or an array of maps.
* @param string $containerClass The class to place all of the objects into. * @param string $containerClass The class to place all of the objects into.
* *
* @return mixed The new objects in an object of type $containerClass * @return mixed The new objects in an object of type $containerClass
@ -2909,7 +2909,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
$obj = new $className($record); $obj = new $className($record);
$obj->write(); $obj->write();
} }
Database::alteration_message("Added default records to $className table","created"); SS_Database::alteration_message("Added default records to $className table","created");
} }
} }
@ -3211,8 +3211,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* @var array * @var array
*/ */
public static $casting = array( public static $casting = array(
"LastEdited" => "SSDatetime", "LastEdited" => "SS_Datetime",
"Created" => "SSDatetime", "Created" => "SS_Datetime",
"Title" => 'Text', "Title" => 'Text',
); );
@ -3220,7 +3220,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
* Specify custom options for a CREATE TABLE call. * Specify custom options for a CREATE TABLE call.
* Can be used to specify a custom storage engine for specific database table. * Can be used to specify a custom storage engine for specific database table.
* All options have to be keyed for a specific database implementation, * All options have to be keyed for a specific database implementation,
* identified by their class name (extending from {@link Database}). * identified by their class name (extending from {@link SS_Database}).
* *
* <code> * <code>
* array( * array(
@ -3240,7 +3240,7 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity
/** /**
* If a field is in this array, then create a database index * If a field is in this array, then create a database index
* on that field. This is a map from fieldname to index type. * on that field. This is a map from fieldname to index type.
* See {@link Database->requireIndex()} and custom subclasses for details on the array notation. * See {@link SS_Database->requireIndex()} and custom subclasses for details on the array notation.
* *
* @var array * @var array
*/ */

View File

@ -5,7 +5,7 @@
* @package sapphire * @package sapphire
* @subpackage model * @subpackage model
*/ */
abstract class Database { abstract class SS_Database {
/** /**
* This constant was added in SilverStripe 2.4 to indicate that SQL-queries * This constant was added in SilverStripe 2.4 to indicate that SQL-queries
* should now use ANSI-compatible syntax. The most notable affect of this * should now use ANSI-compatible syntax. The most notable affect of this
@ -30,10 +30,10 @@ abstract class Database {
/** /**
* Execute the given SQL query. * Execute the given SQL query.
* This abstract function must be defined by subclasses as part of the actual implementation. * This abstract function must be defined by subclasses as part of the actual implementation.
* It should return a subclass of Query as the result. * It should return a subclass of SS_Query as the result.
* @param string $sql The SQL query to execute * @param string $sql The SQL query to execute
* @param int $errorLevel The level of error reporting to enable for the query * @param int $errorLevel The level of error reporting to enable for the query
* @return Query * @return SS_Query
*/ */
abstract function query($sql, $errorLevel = E_USER_ERROR); abstract function query($sql, $errorLevel = E_USER_ERROR);
@ -264,7 +264,7 @@ abstract class Database {
if(!isset($this->tableList[strtolower($table)])) { if(!isset($this->tableList[strtolower($table)])) {
$this->transCreateTable($table, $options, $extensions); $this->transCreateTable($table, $options, $extensions);
Database::alteration_message("Table $table: created","created"); SS_Database::alteration_message("Table $table: created","created");
} else { } else {
$this->checkAndRepairTable($table, $options); $this->checkAndRepairTable($table, $options);
@ -331,7 +331,7 @@ abstract class Database {
$suffix = $suffix ? ($suffix+1) : 2; $suffix = $suffix ? ($suffix+1) : 2;
} }
$this->renameTable($table, "_obsolete_{$table}$suffix"); $this->renameTable($table, "_obsolete_{$table}$suffix");
Database::alteration_message("Table $table: renamed to _obsolete_{$table}$suffix","obsolete"); SS_Database::alteration_message("Table $table: renamed to _obsolete_{$table}$suffix","obsolete");
} }
} }
@ -384,11 +384,11 @@ abstract class Database {
if($newTable || !isset($this->indexList[$table][$index_alt])) { if($newTable || !isset($this->indexList[$table][$index_alt])) {
$this->transCreateIndex($table, $index, $spec); $this->transCreateIndex($table, $index, $spec);
Database::alteration_message("Index $table.$index: created as $spec","created"); SS_Database::alteration_message("Index $table.$index: created as $spec","created");
} else if($array_spec != DB::getConn()->convertIndexSpec($spec)) { } else if($array_spec != DB::getConn()->convertIndexSpec($spec)) {
$this->transAlterIndex($table, $index, $spec); $this->transAlterIndex($table, $index, $spec);
$spec_msg=DB::getConn()->convertIndexSpec($spec); $spec_msg=DB::getConn()->convertIndexSpec($spec);
Database::alteration_message("Index $table.$index: changed to $spec_msg <i style=\"color: #AAA\">(from {$array_spec})</i>","changed"); SS_Database::alteration_message("Index $table.$index: changed to $spec_msg <i style=\"color: #AAA\">(from {$array_spec})</i>","changed");
} }
} }
@ -464,7 +464,7 @@ abstract class Database {
$this->transCreateField($table, $field, $spec_orig); $this->transCreateField($table, $field, $spec_orig);
Profiler::unmark('createField'); Profiler::unmark('createField');
Database::alteration_message("Field $table.$field: created as $spec_orig","created"); SS_Database::alteration_message("Field $table.$field: created as $spec_orig","created");
} else if($fieldValue != $specValue) { } else if($fieldValue != $specValue) {
// If enums are being modified, then we need to fix existing data in the table. // If enums are being modified, then we need to fix existing data in the table.
// Update any records where the enum is set to a legacy value to be set to the default. // Update any records where the enum is set to a legacy value to be set to the default.
@ -494,13 +494,13 @@ abstract class Database {
$query .= "'{$holder[$i]}')"; $query .= "'{$holder[$i]}')";
DB::query($query); DB::query($query);
$amount = DB::affectedRows(); $amount = DB::affectedRows();
Database::alteration_message("Changed $amount rows to default value of field $field (Value: $default)"); SS_Database::alteration_message("Changed $amount rows to default value of field $field (Value: $default)");
} }
} }
Profiler::mark('alterField'); Profiler::mark('alterField');
$this->transAlterField($table, $field, $spec_orig); $this->transAlterField($table, $field, $spec_orig);
Profiler::unmark('alterField'); Profiler::unmark('alterField');
Database::alteration_message("Field $table.$field: changed to $specValue <i style=\"color: #AAA\">(from {$fieldValue})</i>","changed"); SS_Database::alteration_message("Field $table.$field: changed to $specValue <i style=\"color: #AAA\">(from {$fieldValue})</i>","changed");
} }
Profiler::unmark('requireField'); Profiler::unmark('requireField');
} }
@ -519,7 +519,7 @@ abstract class Database {
$suffix = $suffix ? ($suffix+1) : 2; $suffix = $suffix ? ($suffix+1) : 2;
} }
$this->renameField($table, $fieldName, "_obsolete_{$fieldName}$suffix"); $this->renameField($table, $fieldName, "_obsolete_{$fieldName}$suffix");
Database::alteration_message("Field $table.$fieldName: renamed to $table._obsolete_{$fieldName}$suffix","obsolete"); SS_Database::alteration_message("Field $table.$fieldName: renamed to $table._obsolete_{$fieldName}$suffix","obsolete");
} }
} }
@ -540,7 +540,7 @@ abstract class Database {
$fieldList[] = "\"$fieldName\" = $fieldVal"; $fieldList[] = "\"$fieldName\" = $fieldVal";
$columnList[] = "\"$fieldName\""; $columnList[] = "\"$fieldName\"";
// Empty strings inserted as null in INSERTs. Replacement of Database::replace_with_null(). // Empty strings inserted as null in INSERTs. Replacement of SS_Database::replace_with_null().
if($fieldVal === "''") $valueList[] = "null"; if($fieldVal === "''") $valueList[] = "null";
else $valueList[] = $fieldVal; else $valueList[] = $fieldVal;
} }
@ -575,7 +575,7 @@ abstract class Database {
default: default:
$sql = null; $sql = null;
user_error("Database::manipulate() Can't recognise command '$writeInfo[command]'", E_USER_ERROR); user_error("SS_Database::manipulate() Can't recognise command '$writeInfo[command]'", E_USER_ERROR);
} }
} }
} }
@ -590,7 +590,7 @@ abstract class Database {
if(is_array($array)) { if(is_array($array)) {
foreach($array as $key => $value) { foreach($array as $key => $value) {
if(is_array($value)) { if(is_array($value)) {
array_walk($array, array(Database, 'replace_with_null')); array_walk($array, array(SS_Database, 'replace_with_null'));
} }
} }
} }
@ -614,11 +614,11 @@ abstract class Database {
* Enable supression of database messages. * Enable supression of database messages.
*/ */
function quiet() { function quiet() {
Database::$supressOutput = true; SS_Database::$supressOutput = true;
} }
static function alteration_message($message,$type=""){ static function alteration_message($message,$type=""){
if(!Database::$supressOutput) { if(!SS_Database::$supressOutput) {
$color = ""; $color = "";
switch ($type){ switch ($type){
case "created": case "created":
@ -692,15 +692,15 @@ abstract class Database {
/** /**
* Abstract query-result class. * Abstract query-result class.
* Once again, this should be subclassed by an actual database implementation. It will only * Once again, this should be subclassed by an actual database implementation. It will only
* ever be constructed by a subclass of Database. The result of a database query - an iteratable object that's returned by DB::Query * ever be constructed by a subclass of SS_Database. The result of a database query - an iteratable object that's returned by DB::SS_Query
* *
* Primarily, the Query class takes care of the iterator plumbing, letting the subclasses focusing * Primarily, the SS_Query class takes care of the iterator plumbing, letting the subclasses focusing
* on providing the specific data-access methods that are required: {@link nextRecord()}, {@link numRecords()} * on providing the specific data-access methods that are required: {@link nextRecord()}, {@link numRecords()}
* and {@link seek()} * and {@link seek()}
* @package sapphire * @package sapphire
* @subpackage model * @subpackage model
*/ */
abstract class Query implements Iterator { abstract class SS_Query implements Iterator {
/** /**
* The current record in the interator. * The current record in the interator.
* @var array * @var array

View File

@ -229,7 +229,7 @@ class DatabaseAdmin extends Controller {
/** /**
* Clear all data out of the database * Clear all data out of the database
* @todo Move this code into Database class, for DB abstraction * @todo Move this code into SS_Database class, for DB abstraction
*/ */
function clearAllData() { function clearAllData() {
$tables = DB::getConn()->tableList(); $tables = DB::getConn()->tableList();

View File

@ -25,22 +25,22 @@ class ErrorPage extends Page {
protected static $static_filepath = ASSETS_PATH; protected static $static_filepath = ASSETS_PATH;
/** /**
* Get a {@link HTTPResponse} to response to a HTTP error code if an {@link ErrorPage} for that code is present. * Get a {@link SS_HTTPResponse} to response to a HTTP error code if an {@link ErrorPage} for that code is present.
* *
* @param int $statusCode * @param int $statusCode
* @return HTTPResponse * @return SS_HTTPResponse
*/ */
public static function response_for($statusCode) { public static function response_for($statusCode) {
// first attempt to dynamically generate the error page // first attempt to dynamically generate the error page
if($errorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = $statusCode")) { if($errorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = $statusCode")) {
return ModelAsController::controller_for($errorPage)->handleRequest(new HTTPRequest('GET', '')); return ModelAsController::controller_for($errorPage)->handleRequest(new SS_HTTPRequest('GET', ''));
} }
// then fall back on a cached version // then fall back on a cached version
$cachedPath = self::get_filepath_for_errorcode($statusCode, Translatable::get_current_locale()); $cachedPath = self::get_filepath_for_errorcode($statusCode, Translatable::get_current_locale());
if(file_exists($cachedPath)) { if(file_exists($cachedPath)) {
$response = new HTTPResponse(); $response = new SS_HTTPResponse();
$response->setStatusCode($statusCode); $response->setStatusCode($statusCode);
$response->setBody(file_get_contents($cachedPath)); $response->setBody(file_get_contents($cachedPath));
@ -68,7 +68,7 @@ class ErrorPage extends Page {
$errorpage->Status = 'New page'; $errorpage->Status = 'New page';
$errorpage->write(); $errorpage->write();
Database::alteration_message('404 page created', 'created'); SS_Database::alteration_message('404 page created', 'created');
} }
} }

14
core/model/MySQLDatabase.php Normal file → Executable file
View File

@ -7,7 +7,7 @@
* @package sapphire * @package sapphire
* @subpackage model * @subpackage model
*/ */
class MySQLDatabase extends Database { class MySQLDatabase extends SS_Database {
/** /**
* Connection to the DBMS. * Connection to the DBMS.
* @var resource * @var resource
@ -261,7 +261,7 @@ class MySQLDatabase extends Database {
if($alteredOptions && isset($alteredOptions[get_class($this)])) { if($alteredOptions && isset($alteredOptions[get_class($this)])) {
$this->query(sprintf("ALTER TABLE \"%s\" %s", $tableName, $alteredOptions[get_class($this)])); $this->query(sprintf("ALTER TABLE \"%s\" %s", $tableName, $alteredOptions[get_class($this)]));
Database::alteration_message( SS_Database::alteration_message(
sprintf("Table %s options changed: %s", $tableName, $alteredOptions[get_class($this)]), sprintf("Table %s options changed: %s", $tableName, $alteredOptions[get_class($this)]),
"changed" "changed"
); );
@ -281,7 +281,7 @@ class MySQLDatabase extends Database {
*/ */
public function checkAndRepairTable($tableName) { public function checkAndRepairTable($tableName) {
if(!$this->runTableCheckCommand("CHECK TABLE \"$tableName\"")) { if(!$this->runTableCheckCommand("CHECK TABLE \"$tableName\"")) {
Database::alteration_message("Table $tableName: repaired","repaired"); SS_Database::alteration_message("Table $tableName: repaired","repaired");
return $this->runTableCheckCommand("REPAIR TABLE \"$tableName\" USE_FRM"); return $this->runTableCheckCommand("REPAIR TABLE \"$tableName\" USE_FRM");
} else { } else {
return true; return true;
@ -368,7 +368,7 @@ class MySQLDatabase extends Database {
* *
* @param string $tableName The name of the table. * @param string $tableName The name of the table.
* @param string $indexName The name of the index. * @param string $indexName The name of the index.
* @param string $indexSpec The specification of the index, see {@link Database::requireIndex()} for more details. * @param string $indexSpec The specification of the index, see {@link SS_Database::requireIndex()} for more details.
*/ */
public function createIndex($tableName, $indexName, $indexSpec) { public function createIndex($tableName, $indexName, $indexSpec) {
$this->query("ALTER TABLE \"$tableName\" ADD " . $this->getIndexSqlDefinition($indexName, $indexSpec)); $this->query("ALTER TABLE \"$tableName\" ADD " . $this->getIndexSqlDefinition($indexName, $indexSpec));
@ -442,7 +442,7 @@ class MySQLDatabase extends Database {
* Alter an index on a table. * Alter an index on a table.
* @param string $tableName The name of the table. * @param string $tableName The name of the table.
* @param string $indexName The name of the index. * @param string $indexName The name of the index.
* @param string $indexSpec The specification of the index, see {@link Database::requireIndex()} for more details. * @param string $indexSpec The specification of the index, see {@link SS_Database::requireIndex()} for more details.
*/ */
public function alterIndex($tableName, $indexName, $indexSpec) { public function alterIndex($tableName, $indexName, $indexSpec) {
@ -630,7 +630,7 @@ class MySQLDatabase extends Database {
* @param array $values Contains a tokenised list of info about this data type * @param array $values Contains a tokenised list of info about this data type
* @return string * @return string
*/ */
public function ssdatetime($values){ public function ss_datetime($values){
//For reference, this is what typically gets passed to this function: //For reference, this is what typically gets passed to this function:
//$parts=Array('datatype'=>'datetime'); //$parts=Array('datatype'=>'datetime');
//DB::requireField($this->tableName, $this->name, $values); //DB::requireField($this->tableName, $this->name, $values);
@ -923,7 +923,7 @@ class MySQLDatabase extends Database {
* @package sapphire * @package sapphire
* @subpackage model * @subpackage model
*/ */
class MySQLQuery extends Query { class MySQLQuery extends SS_Query {
/** /**
* The MySQLDatabase object that created this result set. * The MySQLDatabase object that created this result set.
* @var MySQLDatabase * @var MySQLDatabase

View File

@ -159,7 +159,7 @@ class RedirectorPage_Controller extends Page_Controller {
* If we ever get this far, it means that the redirection failed. * If we ever get this far, it means that the redirection failed.
*/ */
function index() { function index() {
return new HTTPResponse( return new SS_HTTPResponse(
"<p class=\"message-setupWithoutRedirect\">" . "<p class=\"message-setupWithoutRedirect\">" .
_t('RedirectorPage.HASBEENSETUP', 'A redirector page has been set up without anywhere to redirect to.') . _t('RedirectorPage.HASBEENSETUP', 'A redirector page has been set up without anywhere to redirect to.') .
"</p>" "</p>"

View File

@ -380,7 +380,7 @@ class SQLQuery {
/** /**
* Execute this query. * Execute this query.
* @return Query * @return SS_Query
*/ */
function execute() { function execute() {
return DB::query($this->sql(), E_USER_ERROR); return DB::query($this->sql(), E_USER_ERROR);

View File

@ -108,15 +108,15 @@ class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvid
); );
static $many_many_extraFields = array( static $many_many_extraFields = array(
"UsersCurrentlyEditing" => array("LastPing" => "SSDatetime"), "UsersCurrentlyEditing" => array("LastPing" => "SS_Datetime"),
"LinkTracking" => array("FieldName" => "Varchar"), "LinkTracking" => array("FieldName" => "Varchar"),
"ImageTracking" => array("FieldName" => "Varchar") "ImageTracking" => array("FieldName" => "Varchar")
); );
static $casting = array( static $casting = array(
"Breadcrumbs" => "HTMLText", "Breadcrumbs" => "HTMLText",
"LastEdited" => "SSDatetime", "LastEdited" => "SS_Datetime",
"Created" => "SSDatetime", "Created" => "SS_Datetime",
); );
static $defaults = array( static $defaults = array(
@ -1236,7 +1236,7 @@ class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvid
$homepage->write(); $homepage->write();
$homepage->publish("Stage", "Live"); $homepage->publish("Stage", "Live");
$homepage->flushCache(); $homepage->flushCache();
Database::alteration_message("Home page created","created"); SS_Database::alteration_message("Home page created","created");
} }
if(DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) { if(DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) {
@ -1247,7 +1247,7 @@ class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvid
$aboutus->Status = "Published"; $aboutus->Status = "Published";
$aboutus->write(); $aboutus->write();
$aboutus->publish("Stage", "Live"); $aboutus->publish("Stage", "Live");
Database::alteration_message("About Us created","created"); SS_Database::alteration_message("About Us created","created");
$contactus = new Page(); $contactus = new Page();
$contactus->Title = _t('SiteTree.DEFAULTCONTACTTITLE', 'Contact Us'); $contactus->Title = _t('SiteTree.DEFAULTCONTACTTITLE', 'Contact Us');
@ -1268,7 +1268,7 @@ class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvid
// only execute command if fields haven't been renamed to _obsolete_<fieldname> already by the task // only execute command if fields haven't been renamed to _obsolete_<fieldname> already by the task
if(array_key_exists('Viewers', $conn->fieldList('SiteTree'))) { if(array_key_exists('Viewers', $conn->fieldList('SiteTree'))) {
$task = new UpgradeSiteTreePermissionSchemaTask(); $task = new UpgradeSiteTreePermissionSchemaTask();
$task->run(new HTTPRequest('GET','/')); $task->run(new SS_HTTPRequest('GET','/'));
} }
} }
} }

View File

@ -618,7 +618,7 @@ class Translatable extends DataObjectDecorator implements PermissionProvider {
unset($obj); unset($obj);
} }
} }
Database::alteration_message(sprintf( SS_Database::alteration_message(sprintf(
"Added default locale '%s' to table %s","changed", "Added default locale '%s' to table %s","changed",
Translatable::default_locale(), Translatable::default_locale(),
$this->owner->class $this->owner->class

View File

@ -159,7 +159,7 @@ abstract class DBField extends ViewableData {
* gets you the default representations * gets you the default representations
* of all columns. * of all columns.
* *
* @param Query $query * @param SS_Query $query
*/ */
function addToQuery(&$query) { function addToQuery(&$query) {

View File

@ -7,16 +7,16 @@
* PHP's built-in date() and strtotime() function according to your system locale. * PHP's built-in date() and strtotime() function according to your system locale.
* *
* For all computations involving the current date and time, * For all computations involving the current date and time,
* please use {@link SSDatetime::now()} instead of PHP's built-in date() and time() * please use {@link SS_Datetime::now()} instead of PHP's built-in date() and time()
* methods. This ensures that all time-based computations are testable with mock dates * methods. This ensures that all time-based computations are testable with mock dates
* through {@link SSDatetime::set_mock_now()}. * through {@link SS_Datetime::set_mock_now()}.
* *
* @todo Add localization support, see http://open.silverstripe.com/ticket/2931 * @todo Add localization support, see http://open.silverstripe.com/ticket/2931
* *
* @package sapphire * @package sapphire
* @subpackage model * @subpackage model
*/ */
class SSDatetime extends Date { class SS_Datetime extends Date {
function setValue($value) { function setValue($value) {
// Default to NZ date format - strtotime expects a US date // Default to NZ date format - strtotime expects a US date
@ -49,7 +49,7 @@ class SSDatetime extends Date {
function requireField() { function requireField() {
$parts=Array('datatype'=>'datetime', 'arrayValue'=>$this->arrayValue); $parts=Array('datatype'=>'datetime', 'arrayValue'=>$this->arrayValue);
$values=Array('type'=>'SSDatetime', 'parts'=>$parts); $values=Array('type'=>'SS_Datetime', 'parts'=>$parts);
DB::requireField($this->tableName, $this->name, $values); DB::requireField($this->tableName, $this->name, $values);
} }
@ -70,13 +70,13 @@ class SSDatetime extends Date {
* Returns either the current system date as determined * Returns either the current system date as determined
* by date(), or a mocked date through {@link set_mock_now()}. * by date(), or a mocked date through {@link set_mock_now()}.
* *
* @return SSDatetime * @return SS_Datetime
*/ */
static function now() { static function now() {
if(self::$mock_now) { if(self::$mock_now) {
return self::$mock_now; return self::$mock_now;
} else { } else {
return DBField::create('SSDatetime', date('Y-m-d H:i:s')); return DBField::create('SS_Datetime', date('Y-m-d H:i:s'));
} }
} }
@ -85,15 +85,15 @@ class SSDatetime extends Date {
* Use {@link clear_mock_now()} to revert to the current system date. * Use {@link clear_mock_now()} to revert to the current system date.
* Caution: This sets a fixed date that doesn't increment with time. * Caution: This sets a fixed date that doesn't increment with time.
* *
* @param SSDatetime|string $datetime Either in object format, or as a SSDatetime compatible string. * @param SS_Datetime|string $datetime Either in object format, or as a SS_Datetime compatible string.
*/ */
static function set_mock_now($datetime) { static function set_mock_now($datetime) {
if($datetime instanceof SSDatetime) { if($datetime instanceof SS_Datetime) {
self::$mock_now = $datetime; self::$mock_now = $datetime;
} elseif(is_string($datetime)) { } elseif(is_string($datetime)) {
self::$mock_now = DBField::create('SSDatetime', $datetime); self::$mock_now = DBField::create('SS_Datetime', $datetime);
} else { } else {
throw new Exception('SSDatetime::set_mock_now(): Wrong format: ' . $datetime); throw new Exception('SS_Datetime::set_mock_now(): Wrong format: ' . $datetime);
} }
} }

View File

@ -3,7 +3,7 @@
* @package sapphire * @package sapphire
* @subpackage dev * @subpackage dev
*/ */
class SSBacktrace { class SS_Backtrace {
/** /**
* Return debug_backtrace() results with functions filtered * Return debug_backtrace() results with functions filtered
@ -26,9 +26,9 @@ class SSBacktrace {
*/ */
static function filter_backtrace($bt, $ignoredFunctions = null) { static function filter_backtrace($bt, $ignoredFunctions = null) {
$defaultIgnoredFunctions = array( $defaultIgnoredFunctions = array(
'SSLog::log', 'SS_Log::log',
'SSBacktrace::backtrace', 'SS_Backtrace::backtrace',
'SSBacktrace::filtered_backtrace', 'SS_Backtrace::filtered_backtrace',
'Zend_Log_Writer_Abstract->write', 'Zend_Log_Writer_Abstract->write',
'Zend_Log->log', 'Zend_Log->log',
'Zend_Log->__call', 'Zend_Log->__call',

View File

@ -6,7 +6,7 @@
* @package sapphire * @package sapphire
* @subpackage dev * @subpackage dev
*/ */
class SSCli extends Object { class SS_Cli extends Object {
/** /**
* Returns true if the current STDOUT supports the use of colour control codes. * Returns true if the current STDOUT supports the use of colour control codes.
*/ */

View File

@ -28,8 +28,8 @@ class CliDebugView extends DebugView {
*/ */
public function writeError($httpRequest, $errno, $errstr, $errfile, $errline, $errcontext) { public function writeError($httpRequest, $errno, $errstr, $errfile, $errline, $errcontext) {
$errorType = self::$error_types[$errno]; $errorType = self::$error_types[$errno];
echo SSCli::text("ERROR [" . $errorType['title'] . "]: $errstr\nIN $httpRequest\n", "red", null, true); echo SS_Cli::text("ERROR [" . $errorType['title'] . "]: $errstr\nIN $httpRequest\n", "red", null, true);
echo SSCli::text("Line $errline in $errfile\n\n", "red"); echo SS_Cli::text("Line $errline in $errfile\n\n", "red");
} }
/** /**
@ -50,7 +50,7 @@ class CliDebugView extends DebugView {
* Write a backtrace * Write a backtrace
*/ */
function writeTrace() { function writeTrace() {
SSBacktrace::backtrace(); SS_Backtrace::backtrace();
} }
/** /**

View File

@ -25,11 +25,11 @@ class CliTestReporter extends SapphireTestReporter {
echo "\n\n"; echo "\n\n";
if ($failCount == 0) { if ($failCount == 0) {
echo SSCli::text(" ALL TESTS PASS ", "white", "green"); echo SS_Cli::text(" ALL TESTS PASS ", "white", "green");
} else { } else {
echo SSCli::text(" AT LEAST ONE FAILURE ", "white", "red"); echo SS_Cli::text(" AT LEAST ONE FAILURE ", "white", "red");
} }
echo "\n\n$testCount tests run: " . SSCli::text("$passCount passes", null) . ", ". SSCli::text("$failCount fails", null) . ", and 0 exceptions\n"; echo "\n\n$testCount tests run: " . SS_Cli::text("$passCount passes", null) . ", ". SS_Cli::text("$failCount fails", null) . ", and 0 exceptions\n";
if(function_exists('memory_get_peak_usage')) { if(function_exists('memory_get_peak_usage')) {
echo "Maximum memory usage: " . number_format(memory_get_peak_usage()/(1024*1024), 1) . "M\n\n"; echo "Maximum memory usage: " . number_format(memory_get_peak_usage()/(1024*1024), 1) . "M\n\n";
@ -54,11 +54,11 @@ class CliTestReporter extends SapphireTestReporter {
public function endTest( PHPUnit_Framework_Test $test, $time) { public function endTest( PHPUnit_Framework_Test $test, $time) {
// Status indicator, a la PHPUnit // Status indicator, a la PHPUnit
switch($this->currentTest['status']) { switch($this->currentTest['status']) {
case TEST_FAILURE: echo SSCli::text("F","red", null, true); break; case TEST_FAILURE: echo SS_Cli::text("F","red", null, true); break;
case TEST_ERROR: echo SSCli::text("E","red", null, true); break; case TEST_ERROR: echo SS_Cli::text("E","red", null, true); break;
case TEST_INCOMPLETE: echo SSCli::text("I","yellow"); break; case TEST_INCOMPLETE: echo SS_Cli::text("I","yellow"); break;
case TEST_SUCCESS: echo SSCli::text(".","green"); break; case TEST_SUCCESS: echo SS_Cli::text(".","green"); break;
default: echo SSCli::text("?", "yellow"); break; default: echo SS_Cli::text("?", "yellow"); break;
} }
static $colCount = 0; static $colCount = 0;
@ -89,9 +89,9 @@ class CliTestReporter extends SapphireTestReporter {
} }
echo "\n\n" . SSCli::text($this->testNameToPhrase($test['name']) . "\n". $test['message'] . "\n", 'red', null, true); echo "\n\n" . SS_Cli::text($this->testNameToPhrase($test['name']) . "\n". $test['message'] . "\n", 'red', null, true);
echo SSCli::text("In line {$test['exception']['line']} of {$test['exception']['file']}" . "\n\n", 'red'); echo SS_Cli::text("In line {$test['exception']['line']} of {$test['exception']['file']}" . "\n\n", 'red');
echo SSBacktrace::get_rendered_backtrace($filteredTrace, true); echo SS_Backtrace::get_rendered_backtrace($filteredTrace, true);
echo "\n--------------------\n"; echo "\n--------------------\n";
} }
} }

View File

@ -113,7 +113,7 @@ class CodeViewer extends Controller {
))->renderWith('CodeViewer'); ))->renderWith('CodeViewer');
} }
public function viewClass(HTTPRequest $request) { public function viewClass(SS_HTTPRequest $request) {
$class = $request->param('Class'); $class = $request->param('Class');
if(!class_exists($class)) { if(!class_exists($class)) {

View File

@ -12,8 +12,8 @@
* Uncaught exceptions are currently passed to the debug * Uncaught exceptions are currently passed to the debug
* reporter as standard PHP errors. * reporter as standard PHP errors.
* *
* Errors handled by this class are passed along to {@link SSLog}. * Errors handled by this class are passed along to {@link SS_Log}.
* For configuration information, see the {@link SSLog} * For configuration information, see the {@link SS_Log}
* class documentation. * class documentation.
* *
* @todo add support for user defined config: Debug::die_on_notice(true | false) * @todo add support for user defined config: Debug::die_on_notice(true | false)
@ -207,7 +207,7 @@ class Debug {
if(error_reporting() == 0) return; if(error_reporting() == 0) return;
// Send out the error details to the logger for writing // Send out the error details to the logger for writing
SSLog::log( SS_Log::log(
array( array(
'errno' => $errno, 'errno' => $errno,
'errstr' => $errstr, 'errstr' => $errstr,
@ -215,7 +215,7 @@ class Debug {
'errline' => $errline, 'errline' => $errline,
'errcontext' => $errcontext 'errcontext' => $errcontext
), ),
SSLog::NOTICE SS_Log::NOTICE
); );
if(Director::isDev()) { if(Director::isDev()) {
@ -239,7 +239,7 @@ class Debug {
} }
// Send out the error details to the logger for writing // Send out the error details to the logger for writing
SSLog::log( SS_Log::log(
array( array(
'errno' => $errno, 'errno' => $errno,
'errstr' => $errstr, 'errstr' => $errstr,
@ -247,7 +247,7 @@ class Debug {
'errline' => $errline, 'errline' => $errline,
'errcontext' => $errcontext 'errcontext' => $errcontext
), ),
SSLog::WARN SS_Log::WARN
); );
if(self::$log_errors_to) { if(self::$log_errors_to) {
@ -276,7 +276,7 @@ class Debug {
} }
// Send out the error details to the logger for writing // Send out the error details to the logger for writing
SSLog::log( SS_Log::log(
array( array(
'errno' => $errno, 'errno' => $errno,
'errstr' => $errstr, 'errstr' => $errstr,
@ -284,7 +284,7 @@ class Debug {
'errline' => $errline, 'errline' => $errline,
'errcontext' => $errcontext 'errcontext' => $errcontext
), ),
SSLog::ERR SS_Log::ERR
); );
if(self::$log_errors_to) { if(self::$log_errors_to) {
@ -301,7 +301,7 @@ class Debug {
/** /**
* Render a user-facing error page, using the default HTML error template * Render a user-facing error page, using the default HTML error template
* rendered by {@link ErrorPage} if it exists. Doesn't use the standard {@link HTTPResponse} class * rendered by {@link ErrorPage} if it exists. Doesn't use the standard {@link SS_HTTPResponse} class
* the keep dependencies minimal. * the keep dependencies minimal.
* *
* @uses ErrorPage * @uses ErrorPage
@ -429,8 +429,8 @@ class Debug {
* @deprecated 2.5 * @deprecated 2.5
* To create error logs by email, use this code instead: * To create error logs by email, use this code instead:
* <code> * <code>
* $emailWriter = new SSLogEmailWriter('my@email.com'); * $emailWriter = new SS_LogEmailWriter('my@email.com');
* SSLog::add_writer($emailWriter, SSLog::ERR); * SS_Log::add_writer($emailWriter, SS_Log::ERR);
* </code> * </code>
* *
* @param string $emailAddress * @param string $emailAddress
@ -443,12 +443,12 @@ class Debug {
* @return boolean * @return boolean
*/ */
static function emailError($emailAddress, $errno, $errstr, $errfile, $errline, $errcontext, $errorType = "Error") { static function emailError($emailAddress, $errno, $errstr, $errfile, $errline, $errcontext, $errorType = "Error") {
user_error('Debug::send_errors_to() and Debug::emailError() is deprecated. Please use SSLog instead. user_error('Debug::send_errors_to() and Debug::emailError() is deprecated. Please use SS_Log instead.
See the class documentation in SSLog.php for more information.', E_USER_NOTICE); See the class documentation in SS_Log.php for more information.', E_USER_NOTICE);
$priority = ($errorType == 'Error') ? SSLog::ERR : SSLog::WARN; $priority = ($errorType == 'Error') ? SS_Log::ERR : SS_Log::WARN;
$writer = new SSLogEmailWriter($emailAddress); $writer = new SS_LogEmailWriter($emailAddress);
SSLog::add_writer($writer, $priority); SS_Log::add_writer($writer, $priority);
SSLog::log( SS_Log::log(
array( array(
'errno' => $errno, 'errno' => $errno,
'errstr' => $errstr, 'errstr' => $errstr,
@ -458,7 +458,7 @@ class Debug {
), ),
$priority $priority
); );
SSLog::remove_writer($writer); SS_Log::remove_writer($writer);
} }
/** /**
@ -469,15 +469,15 @@ class Debug {
* *
* @todo Detect script path for CLI errors * @todo Detect script path for CLI errors
* @todo Log detailed errors to full file * @todo Log detailed errors to full file
* @deprecated 2.5 See SSLog on setting up error file logging * @deprecated 2.5 See SS_Log on setting up error file logging
*/ */
protected static function log_error_if_necessary($errno, $errstr, $errfile, $errline, $errcontext, $errtype) { protected static function log_error_if_necessary($errno, $errstr, $errfile, $errline, $errcontext, $errtype) {
user_error('Debug::log_error_if_necessary() and Debug::log_errors_to() are deprecated. Please use SSLog instead. user_error('Debug::log_error_if_necessary() and Debug::log_errors_to() are deprecated. Please use SS_Log instead.
See the class documentation in SSLog.php for more information.', E_USER_NOTICE); See the class documentation in SS_Log.php for more information.', E_USER_NOTICE);
$priority = ($errtype == 'Error') ? SSLog::ERR : SSLog::WARN; $priority = ($errtype == 'Error') ? SS_Log::ERR : SS_Log::WARN;
$writer = new SSLogFileWriter('../' . self::$log_errors_to); $writer = new SS_LogFileWriter('../' . self::$log_errors_to);
SSLog::add_writer($writer, $priority); SS_Log::add_writer($writer, $priority);
SSLog::log( SS_Log::log(
array( array(
'errno' => $errno, 'errno' => $errno,
'errstr' => $errstr, 'errstr' => $errstr,
@ -487,12 +487,12 @@ class Debug {
), ),
$priority $priority
); );
SSLog::remove_writer($writer); SS_Log::remove_writer($writer);
} }
/** /**
* @param string $server IP-Address or domain * @param string $server IP-Address or domain
* @deprecated 2.5 See SSLog on setting up error email notification * @deprecated 2.5 See SS_Log on setting up error email notification
*/ */
static function set_custom_smtp_server($server) { static function set_custom_smtp_server($server) {
self::$custom_smtp_server = $server; self::$custom_smtp_server = $server;
@ -500,7 +500,7 @@ class Debug {
/** /**
* @return string * @return string
* @deprecated 2.5 See SSLog on setting up error email notification * @deprecated 2.5 See SS_Log on setting up error email notification
*/ */
static function get_custom_smtp_server() { static function get_custom_smtp_server() {
return self::$custom_smtp_server; return self::$custom_smtp_server;
@ -511,7 +511,7 @@ class Debug {
* Can be used like so: * Can be used like so:
* if(Director::isLive()) Debug::send_errors_to("sam@silverstripe.com"); * if(Director::isLive()) Debug::send_errors_to("sam@silverstripe.com");
* *
* @deprecated 2.5 See SSLog on setting up error email notification * @deprecated 2.5 See SS_Log on setting up error email notification
* *
* @param string $emailAddress The email address to send errors to * @param string $emailAddress The email address to send errors to
* @param string $sendWarnings Set to true to send warnings as well as errors (Default: false) * @param string $sendWarnings Set to true to send warnings as well as errors (Default: false)
@ -523,7 +523,7 @@ class Debug {
/** /**
* @return string * @return string
* @deprecated 2.5 See SSLog on setting up error email notification * @deprecated 2.5 See SS_Log on setting up error email notification
*/ */
static function get_send_errors_to() { static function get_send_errors_to() {
return self::$send_errors_to; return self::$send_errors_to;
@ -531,7 +531,7 @@ class Debug {
/** /**
* @param string $emailAddress * @param string $emailAddress
* @deprecated 2.5 See SSLog on setting up error email notification * @deprecated 2.5 See SS_Log on setting up error email notification
*/ */
static function send_warnings_to($emailAddress) { static function send_warnings_to($emailAddress) {
self::$send_warnings_to = $emailAddress; self::$send_warnings_to = $emailAddress;
@ -539,7 +539,7 @@ class Debug {
/** /**
* @return string * @return string
* @deprecated 2.5 See SSLog on setting up error email notification * @deprecated 2.5 See SS_Log on setting up error email notification
*/ */
static function get_send_warnings_to() { static function get_send_warnings_to() {
return self::$send_warnings_to; return self::$send_warnings_to;
@ -547,7 +547,7 @@ class Debug {
/** /**
* Call this to enable logging of errors. * Call this to enable logging of errors.
* @deprecated 2.5 See SSLog on setting up error file logging * @deprecated 2.5 See SS_Log on setting up error file logging
*/ */
static function log_errors_to($logFile = ".sserrors") { static function log_errors_to($logFile = ".sserrors") {
self::$log_errors_to = $logFile; self::$log_errors_to = $logFile;
@ -564,19 +564,19 @@ class Debug {
} }
/** /**
* @deprecated 2.5 Please use {@link SSBacktrace::backtrace()} * @deprecated 2.5 Please use {@link SS_Backtrace::backtrace()}
*/ */
static function backtrace($returnVal = false, $ignoreAjax = false) { static function backtrace($returnVal = false, $ignoreAjax = false) {
user_error('Debug::backtrace() is deprecated. Please use SSBacktrace::backtrace() instead', E_USER_NOTICE); user_error('Debug::backtrace() is deprecated. Please use SS_Backtrace::backtrace() instead', E_USER_NOTICE);
return SSBacktrace::backtrace($returnVal, $ignoreAjax); return SS_Backtrace::backtrace($returnVal, $ignoreAjax);
} }
/** /**
* @deprecated 2.5 Please use {@link SSBacktrace::get_rendered_backtrace()} * @deprecated 2.5 Please use {@link SS_Backtrace::get_rendered_backtrace()}
*/ */
static function get_rendered_backtrace($bt, $plainText = false) { static function get_rendered_backtrace($bt, $plainText = false) {
user_error('Debug::get_rendered_backtrace() is deprecated. Please use SSBacktrace::get_rendered_backtrace() instead', E_USER_NOTICE); user_error('Debug::get_rendered_backtrace() is deprecated. Please use SS_Backtrace::get_rendered_backtrace() instead', E_USER_NOTICE);
return SSBacktrace::get_rendered_backtrace($bt, $plainText); return SS_Backtrace::get_rendered_backtrace($bt, $plainText);
} }
/** /**

View File

@ -153,7 +153,7 @@ class DebugView {
*/ */
function writeTrace($trace) { function writeTrace($trace) {
echo '<h3>Trace</h3>'; echo '<h3>Trace</h3>';
echo SSBacktrace::get_rendered_backtrace($trace); echo SS_Backtrace::get_rendered_backtrace($trace);
echo '</div>'; echo '</div>';
} }

View File

@ -6,32 +6,32 @@
* subclasses for output. * subclasses for output.
* *
* These priorities are currently supported: * These priorities are currently supported:
* - SSLog::ERR * - SS_Log::ERR
* - SSLog::WARN * - SS_Log::WARN
* - SSLog::NOTICE * - SS_Log::NOTICE
* *
* You can add an error writer by calling {@link SSLog::add_writer()} * You can add an error writer by calling {@link SS_Log::add_writer()}
* *
* Example usage of logging errors by email notification: * Example usage of logging errors by email notification:
* <code> * <code>
* $logEmailWriter = new SSLogEmailWriter('my@email.com'); * $logEmailWriter = new SS_LogEmailWriter('my@email.com');
* SSLog::add_writer($logEmailWriter, SSLog::ERR); * SS_Log::add_writer($logEmailWriter, SS_Log::ERR);
* </code> * </code>
* *
* Example usage of logging errors by file: * Example usage of logging errors by file:
* <code> * <code>
* $logFileWriter = new SSLogFileWriter('/var/log/silverstripe/errors.log'); * $logFileWriter = new SS_LogFileWriter('/var/log/silverstripe/errors.log');
* SSLog::add_writer($logFileWriter, SSLog::ERR); * SS_Log::add_writer($logFileWriter, SS_Log::ERR);
* </code> * </code>
* *
* Each writer object can be assigned a formatter. The formatter is * Each writer object can be assigned a formatter. The formatter is
* responsible for formatting the message before giving it to the writer. * responsible for formatting the message before giving it to the writer.
* {@link SSLogErrorEmailFormatter} is such an example that formats errors * {@link SS_LogErrorEmailFormatter} is such an example that formats errors
* into HTML for human readability in an email client. * into HTML for human readability in an email client.
* *
* Formatters are added to writers like this: * Formatters are added to writers like this:
* <code> * <code>
* $logEmailWriter = new SSLogEmailWriter('my@email.com'); * $logEmailWriter = new SS_LogEmailWriter('my@email.com');
* $myEmailFormatter = new MyLogEmailFormatter(); * $myEmailFormatter = new MyLogEmailFormatter();
* $logEmailWriter->setFormatter($myEmailFormatter); * $logEmailWriter->setFormatter($myEmailFormatter);
* </code> * </code>
@ -42,7 +42,7 @@
require_once 'Zend/Log.php'; require_once 'Zend/Log.php';
class SSLog { class SS_Log {
const ERR = Zend_Log::ERR; const ERR = Zend_Log::ERR;
const WARN = Zend_Log::WARN; const WARN = Zend_Log::WARN;
@ -50,13 +50,13 @@ class SSLog {
/** /**
* Logger class to use. * Logger class to use.
* @see SSLog::get_logger() * @see SS_Log::get_logger()
* @var string * @var string
*/ */
public static $logger_class = 'SSZendLog'; public static $logger_class = 'SS_ZendLog';
/** /**
* @see SSLog::get_logger() * @see SS_Log::get_logger()
* @var object * @var object
*/ */
protected static $logger; protected static $logger;
@ -100,7 +100,7 @@ class SSLog {
/** /**
* Add a writer instance to the logger. * Add a writer instance to the logger.
* @param object $writer Zend_Log_Writer_Abstract instance * @param object $writer Zend_Log_Writer_Abstract instance
* @param const $priority Priority. Possible values: SSLog::ERR or SSLog::WARN * @param const $priority Priority. Possible values: SS_Log::ERR or SS_Log::WARN
* @param $comparison Priority comparison operator. Acts on the integer values of the error * @param $comparison Priority comparison operator. Acts on the integer values of the error
* levels, where more serious errors are lower numbers. By default this is "=", which means only * levels, where more serious errors are lower numbers. By default this is "=", which means only
* the given priority will be logged. Set to "<=" if you want to track errors of *at least* * the given priority will be logged. Set to "<=" if you want to track errors of *at least*
@ -120,7 +120,7 @@ class SSLog {
* error code, error line, error context (backtrace). * error code, error line, error context (backtrace).
* *
* @param string|array $message String of error message, or array of variables * @param string|array $message String of error message, or array of variables
* @param const $priority Priority. Possible values: SSLog::ERR or SSLog::WARN * @param const $priority Priority. Possible values: SS_Log::ERR or SS_Log::WARN
*/ */
public static function log($message, $priority) { public static function log($message, $priority) {
try { try {

View File

@ -3,7 +3,7 @@
* Sends an error message to an email whenever an error occurs * Sends an error message to an email whenever an error occurs
* in sapphire. * in sapphire.
* *
* @see SSLog for more information on using writers. * @see SS_Log for more information on using writers.
* *
* @package sapphire * @package sapphire
* @subpackage dev * @subpackage dev
@ -11,7 +11,7 @@
require_once 'Zend/Log/Writer/Abstract.php'; require_once 'Zend/Log/Writer/Abstract.php';
class SSLogEmailWriter extends Zend_Log_Writer_Abstract { class SS_LogEmailWriter extends Zend_Log_Writer_Abstract {
protected $emailAddress; protected $emailAddress;
@ -29,7 +29,7 @@ class SSLogEmailWriter extends Zend_Log_Writer_Abstract {
public function _write($event) { public function _write($event) {
// If no formatter set up, use the default // If no formatter set up, use the default
if(!$this->_formatter) { if(!$this->_formatter) {
$formatter = new SSLogErrorEmailFormatter(); $formatter = new SS_LogErrorEmailFormatter();
$this->setFormatter($formatter); $this->setFormatter($formatter);
} }

View File

@ -7,7 +7,7 @@
require_once 'Zend/Log/Formatter/Interface.php'; require_once 'Zend/Log/Formatter/Interface.php';
class SSLogErrorEmailFormatter implements Zend_Log_Formatter_Interface { class SS_LogErrorEmailFormatter implements Zend_Log_Formatter_Interface {
public function format($event) { public function format($event) {
switch($event['priorityName']) { switch($event['priorityName']) {
@ -39,9 +39,9 @@ class SSLogErrorEmailFormatter implements Zend_Log_Formatter_Interface {
$data .= "<p style=\"color: white; background-color: $colour; margin: 0\">$errorType: $errstr<br /> At line $errline in $errfile\n<br />\n<br />\n</p>\n"; $data .= "<p style=\"color: white; background-color: $colour; margin: 0\">$errorType: $errstr<br /> At line $errline in $errfile\n<br />\n<br />\n</p>\n";
// Get a backtrace, filtering out debug method calls // Get a backtrace, filtering out debug method calls
$data .= SSBacktrace::backtrace(true, false, array( $data .= SS_Backtrace::backtrace(true, false, array(
'SSLogErrorEmailFormatter->format', 'SS_LogErrorEmailFormatter->format',
'SSLogEmailWriter->_write' 'SS_LogEmailWriter->_write'
)); ));
$data .= "</div>\n"; $data .= "</div>\n";

View File

@ -8,7 +8,7 @@
require_once 'Zend/Log/Formatter/Interface.php'; require_once 'Zend/Log/Formatter/Interface.php';
class SSLogErrorFileFormatter implements Zend_Log_Formatter_Interface { class SS_LogErrorFileFormatter implements Zend_Log_Formatter_Interface {
public function format($event) { public function format($event) {
$errno = $event['message']['errno']; $errno = $event['message']['errno'];

View File

@ -8,7 +8,7 @@
* logs to. * logs to.
* *
* @uses error_log() built-in PHP function. * @uses error_log() built-in PHP function.
* @see SSLog for more information on using writers. * @see SS_Log for more information on using writers.
* *
* @package sapphire * @package sapphire
* @subpackage dev * @subpackage dev
@ -16,7 +16,7 @@
require_once 'Zend/Log/Writer/Abstract.php'; require_once 'Zend/Log/Writer/Abstract.php';
class SSLogFileWriter extends Zend_Log_Writer_Abstract { class SS_LogFileWriter extends Zend_Log_Writer_Abstract {
/** /**
* The path to the file that errors will be stored in. * The path to the file that errors will be stored in.
@ -52,7 +52,7 @@ class SSLogFileWriter extends Zend_Log_Writer_Abstract {
*/ */
public function _write($event) { public function _write($event) {
if(!$this->_formatter) { if(!$this->_formatter) {
$formatter = new SSLogErrorFileFormatter(); $formatter = new SS_LogErrorFileFormatter();
$this->setFormatter($formatter); $this->setFormatter($formatter);
} }
$message = $this->_formatter->format($event); $message = $this->_formatter->format($event);

View File

@ -44,10 +44,10 @@ class SapphireREPL extends Controller {
echo "Sapphire Interactive Command-line (REPL interface). Type help for hints.\n\n"; echo "Sapphire Interactive Command-line (REPL interface). Type help for hints.\n\n";
while(true) { while(true) {
echo SSCli::text("?> ", "cyan"); echo SS_Cli::text("?> ", "cyan");
echo SSCli::start_colour("yellow"); echo SS_Cli::start_colour("yellow");
$command = trim(fgets(STDIN, 4096)); $command = trim(fgets(STDIN, 4096));
echo SSCli::end_colour(); echo SS_Cli::end_colour();
if ( $command == 'help' || $command == '?' ) { if ( $command == 'help' || $command == '?' ) {
print "help or ? to exit\n" ; print "help or ? to exit\n" ;
@ -71,7 +71,7 @@ class SapphireREPL extends Controller {
echo "\n"; echo "\n";
} }
catch( Exception $__repl_exception ) { catch( Exception $__repl_exception ) {
echo SSCli::start_colour("red"); echo SS_Cli::start_colour("red");
printf( '%s (code: %d) got thrown'.PHP_EOL, get_class($__repl_exception), $__repl_exception->getCode() ); printf( '%s (code: %d) got thrown'.PHP_EOL, get_class($__repl_exception), $__repl_exception->getCode() );
print $__repl_exception; print $__repl_exception;
echo "\n"; echo "\n";

View File

@ -284,7 +284,7 @@ class SapphireTestReporter implements PHPUnit_Framework_TestListener {
if ($test['status'] != 1) { if ($test['status'] != 1) {
echo "<div class=\"failure\"><span>&otimes; ". $this->testNameToPhrase($test['name']) ."</span><br>"; echo "<div class=\"failure\"><span>&otimes; ". $this->testNameToPhrase($test['name']) ."</span><br>";
echo "<pre>".htmlentities($test['message'])."</pre><br>"; echo "<pre>".htmlentities($test['message'])."</pre><br>";
echo SSBacktrace::get_rendered_backtrace($test['trace']); echo SS_Backtrace::get_rendered_backtrace($test['trace']);
echo "</div>"; echo "</div>";
} }
} }

View File

@ -107,7 +107,7 @@ class TestSession {
} }
/** /**
* Get the most recent response, as an HTTPResponse object * Get the most recent response, as an SS_HTTPResponse object
*/ */
function lastResponse() { function lastResponse() {
return $this->lastResponse; return $this->lastResponse;
@ -153,12 +153,12 @@ class TestSession {
} }
/** /**
* Wrapper around HTTPResponse to make it look like a SimpleHTTPResposne * Wrapper around SS_HTTPResponse to make it look like a SimpleHTTPResposne
*/ */
class TestSession_STResponseWrapper { class TestSession_STResponseWrapper {
private $response; private $response;
function __construct(HTTPResponse $response) { function __construct(SS_HTTPResponse $response) {
$this->response = $response; $this->response = $response;
} }

View File

@ -1,9 +1,9 @@
<?php <?php
/** /**
* Extensions to Zend_Log to make it work nicer * Extensions to Zend_Log to make it work nicer
* with {@link SSLog}. * with {@link SS_Log}.
* *
* Please refer to {@link SSLog} for information on * Please refer to {@link SS_Log} for information on
* setting up logging for your projects. * setting up logging for your projects.
* *
* @package sapphire * @package sapphire
@ -12,7 +12,7 @@
require_once 'Zend/Log.php'; require_once 'Zend/Log.php';
class SSZendLog extends Zend_Log { class SS_ZendLog extends Zend_Log {
/** /**
* Get all writers in this logger. * Get all writers in this logger.

View File

@ -752,7 +752,7 @@ class Email_BounceHandler extends Controller {
class Email_BounceRecord extends DataObject { class Email_BounceRecord extends DataObject {
static $db = array( static $db = array(
'BounceEmail' => 'Varchar', 'BounceEmail' => 'Varchar',
'BounceTime' => 'SSDatetime', 'BounceTime' => 'SS_Datetime',
'BounceMessage' => 'Varchar' 'BounceMessage' => 'Varchar'
); );

View File

@ -7,7 +7,7 @@
class QueuedEmail extends DataObject { class QueuedEmail extends DataObject {
static $db = array( static $db = array(
'Send' => 'SSDatetime', 'Send' => 'SS_Datetime',
'Subject' => 'Varchar', 'Subject' => 'Varchar',
'From' => 'Varchar', 'From' => 'Varchar',
'Content' => 'Text' 'Content' => 'Text'

View File

@ -266,12 +266,12 @@ class Form extends RequestHandler {
$acceptType = $request->getHeader('Accept'); $acceptType = $request->getHeader('Accept');
if(strpos($acceptType, 'application/json') !== FALSE) { if(strpos($acceptType, 'application/json') !== FALSE) {
// Send validation errors back as JSON with a flag at the start // Send validation errors back as JSON with a flag at the start
$response = new HTTPResponse(Convert::array2json($this->validator->getErrors())); $response = new SS_HTTPResponse(Convert::array2json($this->validator->getErrors()));
$response->addHeader('Content-Type', 'application/json'); $response->addHeader('Content-Type', 'application/json');
} else { } else {
$this->setupFormErrors(); $this->setupFormErrors();
// Send the newly rendered form tag as HTML // Send the newly rendered form tag as HTML
$response = new HTTPResponse($this->forTemplate()); $response = new SS_HTTPResponse($this->forTemplate());
$response->addHeader('Content-Type', 'text/html'); $response->addHeader('Content-Type', 'text/html');
} }
@ -307,7 +307,7 @@ class Form extends RequestHandler {
* formfield with the same name, this method gives priority * formfield with the same name, this method gives priority
* to the formfield. * to the formfield.
* *
* @param HTTPRequest $request * @param SS_HTTPRequest $request
* @return FormField * @return FormField
*/ */
function handleField($request) { function handleField($request) {
@ -1246,7 +1246,7 @@ class Form extends RequestHandler {
/** /**
* Test a submission of this form. * Test a submission of this form.
* @return HTTPResponse the response object that the handling controller produces. You can interrogate this in your unit test. * @return SS_HTTPResponse the response object that the handling controller produces. You can interrogate this in your unit test.
*/ */
function testSubmission($action, $data) { function testSubmission($action, $data) {
$data['action_' . $action] = true; $data['action_' . $action] = true;
@ -1259,7 +1259,7 @@ class Form extends RequestHandler {
/** /**
* Test an ajax submission of this form. * Test an ajax submission of this form.
* @return HTTPResponse the response object that the handling controller produces. You can interrogate this in your unit test. * @return SS_HTTPResponse the response object that the handling controller produces. You can interrogate this in your unit test.
*/ */
function testAjaxSubmission($action, $data) { function testAjaxSubmission($action, $data) {
$data['ajax'] = 1; $data['ajax'] = 1;

View File

@ -32,7 +32,7 @@ class ScaffoldingComplexTableField_Popup extends ComplexTableField_Popup {
/** /**
* Handle a generic action passed in by the URL mapping. * Handle a generic action passed in by the URL mapping.
* *
* @param HTTPRequest $request * @param SS_HTTPRequest $request
*/ */
public function handleAction($request) { public function handleAction($request) {
$action = str_replace("-","_",$request->param('Action')); $action = str_replace("-","_",$request->param('Action'));
@ -63,7 +63,7 @@ class ScaffoldingComplexTableField_Popup extends ComplexTableField_Popup {
/** /**
* Action to render results for an autocomplete filter. * Action to render results for an autocomplete filter.
* *
* @param HTTPRequest $request * @param SS_HTTPRequest $request
* @return void * @return void
*/ */
function filter($request) { function filter($request) {

View File

@ -401,7 +401,7 @@ JS
* Caution: Other parameters such as {@sourceFilter} will be ignored. * Caution: Other parameters such as {@sourceFilter} will be ignored.
* Please use this only as a fallback for really complex queries (e.g. involving HAVING and GROUPBY). * Please use this only as a fallback for really complex queries (e.g. involving HAVING and GROUPBY).
* *
* @param $query Query * @param $query SS_Query
*/ */
function setCustomQuery($query) { function setCustomQuery($query) {
$this->customQuery = $query; $this->customQuery = $query;
@ -921,7 +921,7 @@ JS
$fileName = "export-$now.csv"; $fileName = "export-$now.csv";
if($fileData = $this->generateExportFileData($numColumns, $numRows)){ if($fileData = $this->generateExportFileData($numColumns, $numRows)){
return HTTPRequest::send_file($fileData, $fileName); return SS_HTTPRequest::send_file($fileData, $fileName);
}else{ }else{
user_error("No records found", E_USER_ERROR); user_error("No records found", E_USER_ERROR);
} }

View File

@ -117,10 +117,10 @@ class TreeDropdownField extends FormField {
/** /**
* Get the whole tree of a part of the tree via an AJAX request. * Get the whole tree of a part of the tree via an AJAX request.
* *
* @param HTTPRequest $request * @param SS_HTTPRequest $request
* @return string * @return string
*/ */
public function tree(HTTPRequest $request) { public function tree(SS_HTTPRequest $request) {
$isSubTree = false; $isSubTree = false;
if($ID = (int) $request->param('ID')) { if($ID = (int) $request->param('ID')) {

View File

@ -13,14 +13,14 @@ class Member extends DataObject {
'Password' => 'Varchar(64)', // support for up to SHA256! 'Password' => 'Varchar(64)', // support for up to SHA256!
'RememberLoginToken' => 'Varchar(50)', 'RememberLoginToken' => 'Varchar(50)',
'NumVisit' => 'Int', 'NumVisit' => 'Int',
'LastVisited' => 'SSDatetime', 'LastVisited' => 'SS_Datetime',
'Bounced' => 'Boolean', // Note: This does not seem to be used anywhere. 'Bounced' => 'Boolean', // Note: This does not seem to be used anywhere.
'AutoLoginHash' => 'Varchar(30)', 'AutoLoginHash' => 'Varchar(30)',
'AutoLoginExpired' => 'SSDatetime', 'AutoLoginExpired' => 'SS_Datetime',
'PasswordEncryption' => "Enum('none', 'none')", 'PasswordEncryption' => "Enum('none', 'none')",
'Salt' => 'Varchar(50)', 'Salt' => 'Varchar(50)',
'PasswordExpiry' => 'Date', 'PasswordExpiry' => 'Date',
'LockedOutUntil' => 'SSDatetime', 'LockedOutUntil' => 'SS_Datetime',
'Locale' => 'Varchar(6)', 'Locale' => 'Varchar(6)',
// handled in registerFailedLogin(), only used if $lock_out_after_incorrect_logins is set // handled in registerFailedLogin(), only used if $lock_out_after_incorrect_logins is set
'FailedLoginCount' => 'Int', 'FailedLoginCount' => 'Int',
@ -954,7 +954,7 @@ class Member extends DataObject {
if(!DB::query("SELECT * FROM \"Member\"")->value() && isset($_REQUEST['username']) && isset($_REQUEST['password'])) { if(!DB::query("SELECT * FROM \"Member\"")->value() && isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
Security::findAnAdministrator($_REQUEST['username'], $_REQUEST['password']); Security::findAnAdministrator($_REQUEST['username'], $_REQUEST['password']);
Database::alteration_message("Added admin account","created"); SS_Database::alteration_message("Added admin account","created");
} }
} }

View File

@ -146,7 +146,7 @@ class Security extends Controller {
if(!$controller) $controller = Controller::curr(); if(!$controller) $controller = Controller::curr();
if(Director::is_ajax()) { if(Director::is_ajax()) {
$response = ($controller) ? $controller->getResponse() : new HTTPResponse(); $response = ($controller) ? $controller->getResponse() : new SS_HTTPResponse();
$response->setStatusCode(403); $response->setStatusCode(403);
$response->setBody('NOTLOGGEDIN:'); $response->setBody('NOTLOGGEDIN:');
return $response; return $response;
@ -184,7 +184,7 @@ class Security extends Controller {
// Work out the right message to show // Work out the right message to show
if(Member::currentUser()) { if(Member::currentUser()) {
$response = ($controller) ? $controller->getResponse() : new HTTPResponse(); $response = ($controller) ? $controller->getResponse() : new SS_HTTPResponse();
$response->setStatusCode(403); $response->setStatusCode(403);
// Replace %s with the log in link // Replace %s with the log in link
@ -294,10 +294,10 @@ class Security extends Controller {
$eventResults = $this->extend('onBeforeSecurityLogin'); $eventResults = $this->extend('onBeforeSecurityLogin');
// If there was a redirection, return // If there was a redirection, return
if(Director::redirected_to()) return; if(Director::redirected_to()) return;
// If there was an HTTPResponse object returned, then return that // If there was an SS_HTTPResponse object returned, then return that
else if($eventResults) { else if($eventResults) {
foreach($eventResults as $result) { foreach($eventResults as $result) {
if($result instanceof HTTPResponse) return $result; if($result instanceof SS_HTTPResponse) return $result;
} }
} }
@ -446,7 +446,7 @@ class Security extends Controller {
* Show the "password sent" page, after a user has requested * Show the "password sent" page, after a user has requested
* to reset their password. * to reset their password.
* *
* @param HTTPRequest $request The HTTPRequest for this action. * @param SS_HTTPRequest $request The SS_HTTPRequest for this action.
* @return string Returns the "password sent" page as HTML code. * @return string Returns the "password sent" page as HTML code.
*/ */
public function passwordsent($request) { public function passwordsent($request) {

View File

@ -43,10 +43,10 @@ class ErrorPageTest extends FunctionalTest {
/* We have body text from the error page */ /* We have body text from the error page */
$this->assertNotNull($response->getBody(), 'We have body text from the error page'); $this->assertNotNull($response->getBody(), 'We have body text from the error page');
/* Status code of the HTTPResponse for error page is "404" */ /* Status code of the SS_HTTPResponse for error page is "404" */
$this->assertEquals($response->getStatusCode(), '404', 'Status code of the HTTPResponse for error page is "404"'); $this->assertEquals($response->getStatusCode(), '404', 'Status code of the SS_HTTPResponse for error page is "404"');
/* Status message of the HTTPResponse for error page is "Not Found" */ /* Status message of the SS_HTTPResponse for error page is "Not Found" */
$this->assertEquals($response->getStatusDescription(), 'Not Found', 'Status message of the HTTResponse for error page is "Not found"'); $this->assertEquals($response->getStatusDescription(), 'Not Found', 'Status message of the HTTResponse for error page is "Not found"');
} }

View File

@ -4,7 +4,7 @@ class HTTPRequestTest extends SapphireTest {
static $fixture_file = null; static $fixture_file = null;
function testMatch() { function testMatch() {
$request = new HTTPRequest("GET", "admin/crm/add"); $request = new SS_HTTPRequest("GET", "admin/crm/add");
/* When a rule matches, but has no variables, array("_matched" => true) is returned. */ /* When a rule matches, but has no variables, array("_matched" => true) is returned. */
$this->assertEquals(array("_matched" => true), $request->match('admin/crm', true)); $this->assertEquals(array("_matched" => true), $request->match('admin/crm', true));
@ -16,7 +16,7 @@ class HTTPRequestTest extends SapphireTest {
} }
public function testHttpMethodOverrides() { public function testHttpMethodOverrides() {
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'GET', 'GET',
'admin/crm' 'admin/crm'
); );
@ -25,7 +25,7 @@ class HTTPRequestTest extends SapphireTest {
'GET with no method override' 'GET with no method override'
); );
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'POST', 'POST',
'admin/crm' 'admin/crm'
); );
@ -34,7 +34,7 @@ class HTTPRequestTest extends SapphireTest {
'POST with no method override' 'POST with no method override'
); );
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'GET', 'GET',
'admin/crm', 'admin/crm',
array('_method' => 'DELETE') array('_method' => 'DELETE')
@ -44,7 +44,7 @@ class HTTPRequestTest extends SapphireTest {
'GET with invalid POST method override' 'GET with invalid POST method override'
); );
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'POST', 'POST',
'admin/crm', 'admin/crm',
array(), array(),
@ -55,7 +55,7 @@ class HTTPRequestTest extends SapphireTest {
'POST with valid method override to DELETE' 'POST with valid method override to DELETE'
); );
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'POST', 'POST',
'admin/crm', 'admin/crm',
array(), array(),
@ -66,7 +66,7 @@ class HTTPRequestTest extends SapphireTest {
'POST with valid method override to PUT' 'POST with valid method override to PUT'
); );
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'POST', 'POST',
'admin/crm', 'admin/crm',
array(), array(),
@ -77,7 +77,7 @@ class HTTPRequestTest extends SapphireTest {
'POST with valid method override to HEAD ' 'POST with valid method override to HEAD '
); );
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'POST', 'POST',
'admin/crm', 'admin/crm',
array(), array(),
@ -88,7 +88,7 @@ class HTTPRequestTest extends SapphireTest {
'POST with valid method override to HEAD' 'POST with valid method override to HEAD'
); );
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'POST', 'POST',
'admin/crm', 'admin/crm',
array('_method' => 'head') array('_method' => 'head')

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* Tests for RequestHandler and HTTPRequest. * Tests for RequestHandler and SS_HTTPRequest.
* We've set up a simple URL handling model based on * We've set up a simple URL handling model based on
*/ */
class RequestHandlingTest extends SapphireTest { class RequestHandlingTest extends SapphireTest {
@ -195,11 +195,11 @@ class RequestHandlingTest_Controller extends Controller {
} }
public function throwexception() { public function throwexception() {
throw new HTTPResponse_Exception('This request was invalid.', 400); throw new SS_HTTPResponse_Exception('This request was invalid.', 400);
} }
public function throwresponseexception() { public function throwresponseexception() {
throw new HTTPResponse_Exception(new HTTPResponse('There was an internal server error.', 500)); throw new SS_HTTPResponse_Exception(new SS_HTTPResponse('There was an internal server error.', 500));
} }
public function throwhttperror() { public function throwhttperror() {

View File

@ -203,7 +203,7 @@ class SearchContextTest_Project extends DataObject implements TestOnly {
class SearchContextTest_Deadline extends DataObject implements TestOnly { class SearchContextTest_Deadline extends DataObject implements TestOnly {
static $db = array( static $db = array(
"CompletionDate" => "SSDatetime" "CompletionDate" => "SS_Datetime"
); );
static $has_one = array( static $has_one = array(

View File

@ -17,7 +17,7 @@ class ModelAsControllerTest extends SapphireTest {
$page->publish('Stage', 'Live'); $page->publish('Stage', 'Live');
$router = new ModelAsController(); $router = new ModelAsController();
$request = new HTTPRequest( $request = new SS_HTTPRequest(
'GET', 'test-page/action/id/otherid' 'GET', 'test-page/action/id/otherid'
); );
$request->match('$URLSegment/$Action/$ID/$OtherID'); $request->match('$URLSegment/$Action/$ID/$OtherID');

36
tests/dev/LogTest.php Normal file
View File

@ -0,0 +1,36 @@
<?php
/**
* @package sapphire
* @subpackage tests
*/
class SS_LogTest extends SapphireTest {
protected $testEmailWriter;
function setUp() {
parent::setUp();
SS_Log::clear_writers(); // this test will break if existing writers are available!
$this->testEmailWriter = new SS_LogEmailWriter('sean@silverstripe.com');
$this->testFileWriter = new SS_LogFileWriter('../test.log');
SS_Log::add_writer($this->testEmailWriter, SS_Log::ERR);
SS_Log::add_writer($this->testFileWriter, SS_Log::WARN);
}
function testExistingWriter() {
$writers = SS_Log::get_writers();
$this->assertType('array', $writers);
$this->assertEquals(2, count($writers));
}
function testRemoveWriter() {
SS_Log::remove_writer($this->testEmailWriter);
$writers = SS_Log::get_writers();
$this->assertType('array', $writers);
$this->assertEquals(1, count($writers));
SS_Log::remove_writer($this->testFileWriter);
$writers = SS_Log::get_writers();
$this->assertType('array', $writers);
$this->assertEquals(0, count($writers));
}
}

View File

@ -1,36 +0,0 @@
<?php
/**
* @package sapphire
* @subpackage tests
*/
class SSLogTest extends SapphireTest {
protected $testEmailWriter;
function setUp() {
parent::setUp();
SSLog::clear_writers(); // this test will break if existing writers are available!
$this->testEmailWriter = new SSLogEmailWriter('sean@silverstripe.com');
$this->testFileWriter = new SSLogFileWriter('../test.log');
SSLog::add_writer($this->testEmailWriter, SSLog::ERR);
SSLog::add_writer($this->testFileWriter, SSLog::WARN);
}
function testExistingWriter() {
$writers = SSLog::get_writers();
$this->assertType('array', $writers);
$this->assertEquals(2, count($writers));
}
function testRemoveWriter() {
SSLog::remove_writer($this->testEmailWriter);
$writers = SSLog::get_writers();
$this->assertType('array', $writers);
$this->assertEquals(1, count($writers));
SSLog::remove_writer($this->testFileWriter);
$writers = SSLog::get_writers();
$this->assertType('array', $writers);
$this->assertEquals(0, count($writers));
}
}

View File

@ -1,6 +1,6 @@
<?php <?php
/** /**
* Tests for {@link SSDatetime} class. * Tests for {@link SS_Datetime} class.
* *
* @todo Current date comparisons are slightly dodgy, as they only compare * @todo Current date comparisons are slightly dodgy, as they only compare
* the current date (not hour, minute, second) and assume that the date * the current date (not hour, minute, second) and assume that the date
@ -10,10 +10,10 @@
* @package sapphire * @package sapphire
* @subpackage tests * @subpackage tests
*/ */
class SSDatetimeTest extends SapphireTest { class SS_DatetimeTest extends SapphireTest {
function testNowWithSystemDate() { function testNowWithSystemDate() {
$systemDatetime = DBField::create('SSDatetime', date('Y-m-d H:i:s')); $systemDatetime = DBField::create('SS_Datetime', date('Y-m-d H:i:s'));
$nowDatetime = SSDatetime::now(); $nowDatetime = SS_Datetime::now();
$this->assertEquals($systemDatetime->Date(), $nowDatetime->Date()); $this->assertEquals($systemDatetime->Date(), $nowDatetime->Date());
} }
@ -21,16 +21,16 @@ class SSDatetimeTest extends SapphireTest {
function testNowWithMockDate() { function testNowWithMockDate() {
// Test setting // Test setting
$mockDate = '2001-12-31 22:10:59'; $mockDate = '2001-12-31 22:10:59';
SSDatetime::set_mock_now($mockDate); SS_Datetime::set_mock_now($mockDate);
$systemDatetime = DBField::create('SSDatetime', date('Y-m-d H:i:s')); $systemDatetime = DBField::create('SS_Datetime', date('Y-m-d H:i:s'));
$nowDatetime = SSDatetime::now(); $nowDatetime = SS_Datetime::now();
$this->assertNotEquals($systemDatetime->Date(), $nowDatetime->Date()); $this->assertNotEquals($systemDatetime->Date(), $nowDatetime->Date());
$this->assertEquals($nowDatetime->getValue(), $mockDate); $this->assertEquals($nowDatetime->getValue(), $mockDate);
// Test clearing // Test clearing
SSDatetime::clear_mock_now(); SS_Datetime::clear_mock_now();
$systemDatetime = DBField::create('SSDatetime', date('Y-m-d H:i:s')); $systemDatetime = DBField::create('SS_Datetime', date('Y-m-d H:i:s'));
$nowDatetime = SSDatetime::now(); $nowDatetime = SS_Datetime::now();
$this->assertEquals($systemDatetime->Date(), $nowDatetime->Date()); $this->assertEquals($systemDatetime->Date(), $nowDatetime->Date());
} }
} }