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

Converted to PSR-2
This commit is contained in:
Damian Mooyman 2015-11-23 10:28:12 +13:00
commit 18d79e1b12
24 changed files with 1429 additions and 1293 deletions

View File

@ -1,37 +1,39 @@
<?php
class DevCheckController extends Controller {
/**
* @var array
*/
public static $allowed_actions = array(
'index'
);
class DevCheckController extends Controller
{
/**
* @var array
*/
public static $allowed_actions = array(
'index'
);
/**
* Permission code to check for access to this controller.
*
* @var string
*/
private static $permission = 'ADMIN';
/**
* Permission code to check for access to this controller.
*
* @var string
*/
private static $permission = 'ADMIN';
/**
* @param SS_HTTPRequest $request
*
* @return EnvironmentChecker
*
* @throws SS_HTTPResponse_Exception
*/
function index($request) {
$suite = 'check';
/**
* @param SS_HTTPRequest $request
*
* @return EnvironmentChecker
*
* @throws SS_HTTPResponse_Exception
*/
public function index($request)
{
$suite = 'check';
if ($name = $request->param('Suite')) {
$suite = $name;
}
if ($name = $request->param('Suite')) {
$suite = $name;
}
$checker = new EnvironmentChecker($suite, 'Environment status');
$checker->init($this->config()->permission);
$checker = new EnvironmentChecker($suite, 'Environment status');
$checker->init($this->config()->permission);
return $checker;
}
return $checker;
}
}

View File

@ -1,25 +1,27 @@
<?php
class DevHealthController extends Controller {
/**
* @var array
*/
public static $allowed_actions = array(
'index'
);
class DevHealthController extends Controller
{
/**
* @var array
*/
public static $allowed_actions = array(
'index'
);
/**
* @return EnvironmentChecker
*
* @throws SS_HTTPResponse_Exception
*/
function index() {
// health check does not require permission to run
/**
* @return EnvironmentChecker
*
* @throws SS_HTTPResponse_Exception
*/
public function index()
{
// health check does not require permission to run
$checker = new EnvironmentChecker('health', 'Site health');
$checker->init('');
$checker->setErrorCode(404);
$checker = new EnvironmentChecker('health', 'Site health');
$checker->init('');
$checker->setErrorCode(404);
return $checker;
}
return $checker;
}
}

View File

@ -14,26 +14,27 @@
* - Are the right PHP modules installed?
* - Are the file permissions correct?
*/
interface EnvironmentCheck {
/**
* @var int
*/
const ERROR = 3;
interface EnvironmentCheck
{
/**
* @var int
*/
const ERROR = 3;
/**
* @var int
*/
const WARNING = 2;
/**
* @var int
*/
const WARNING = 2;
/**
* @var int
*/
const OK = 1;
/**
* @var int
*/
const OK = 1;
/**
* @return array Result with 'status' and 'message' keys.
*
* Status is EnvironmentCheck::ERROR, EnvironmentCheck::WARNING, or EnvironmentCheck::OK.
*/
function check();
}
/**
* @return array Result with 'status' and 'message' keys.
*
* Status is EnvironmentCheck::ERROR, EnvironmentCheck::WARNING, or EnvironmentCheck::OK.
*/
public function check();
}

View File

@ -19,260 +19,284 @@
*
* $result = EnvironmentCheckSuite::inst('health')->run();
*/
class EnvironmentCheckSuite extends Object {
/**
* Name of this suite.
*
* @var string
*/
protected $name;
class EnvironmentCheckSuite extends Object
{
/**
* Name of this suite.
*
* @var string
*/
protected $name;
/**
* @var array
*/
protected $checks = array();
/**
* @var array
*/
protected $checks = array();
/**
* Associative array of named checks registered via the config system. Each check should specify:
* - definition (e.g. 'MyHealthCheck("my param")')
* - title (e.g. 'Is my feature working?')
* - state (setting this to 'disabled' will cause suites to skip this check entirely.
*
* @var array
*/
private static $registered_checks = array();
/**
* Associative array of named checks registered via the config system. Each check should specify:
* - definition (e.g. 'MyHealthCheck("my param")')
* - title (e.g. 'Is my feature working?')
* - state (setting this to 'disabled' will cause suites to skip this check entirely.
*
* @var array
*/
private static $registered_checks = array();
/**
* Associative array of named suites registered via the config system. Each suite should enumerate
* named checks that have been configured in 'registered_checks'.
*
* @var array
*/
private static $registered_suites = array();
/**
* Associative array of named suites registered via the config system. Each suite should enumerate
* named checks that have been configured in 'registered_checks'.
*
* @var array
*/
private static $registered_suites = array();
/**
* Load checks for this suite from the configuration system. This is an alternative to the
* EnvironmentCheckSuite::register - both can be used, checks will be appended to the suite.
*
* @param string $suiteName The name of this suite.
*/
public function __construct($suiteName) {
parent::__construct();
/**
* Load checks for this suite from the configuration system. This is an alternative to the
* EnvironmentCheckSuite::register - both can be used, checks will be appended to the suite.
*
* @param string $suiteName The name of this suite.
*/
public function __construct($suiteName)
{
parent::__construct();
if (empty($this->config()->registered_suites[$suiteName])) {
// Not registered via config system, but it still may be configured later via self::register.
return;
}
if (empty($this->config()->registered_suites[$suiteName])) {
// Not registered via config system, but it still may be configured later via self::register.
return;
}
foreach ($this->config()->registered_suites[$suiteName] as $checkName) {
if (empty($this->config()->registered_checks[$checkName])) {
throw new InvalidArgumentException(
"Bad EnvironmentCheck: '$checkName' - the named check has not been registered."
);
}
foreach ($this->config()->registered_suites[$suiteName] as $checkName) {
if (empty($this->config()->registered_checks[$checkName])) {
throw new InvalidArgumentException(
"Bad EnvironmentCheck: '$checkName' - the named check has not been registered."
);
}
$check = $this->config()->registered_checks[$checkName];
$check = $this->config()->registered_checks[$checkName];
// Existing named checks can be disabled by setting their 'state' to 'disabled'.
// This is handy for disabling checks mandated by modules.
if (!empty($check['state']) && $check['state']==='disabled') continue;
// Add the check to this suite.
$this->push($check['definition'], $check['title']);
}
}
// Existing named checks can be disabled by setting their 'state' to 'disabled'.
// This is handy for disabling checks mandated by modules.
if (!empty($check['state']) && $check['state']==='disabled') {
continue;
}
// Add the check to this suite.
$this->push($check['definition'], $check['title']);
}
}
/**
* Run this test suite and return the result code of the worst result.
*
* @return int
*/
public function run() {
$result = new EnvironmentCheckSuiteResult();
/**
* Run this test suite and return the result code of the worst result.
*
* @return int
*/
public function run()
{
$result = new EnvironmentCheckSuiteResult();
foreach($this->checkInstances() as $check) {
list($checkClass, $checkTitle) = $check;
try {
list($status, $message) = $checkClass->check();
// If the check fails, register that as an error
} catch(Exception $e) {
$status = EnvironmentCheck::ERROR;
$message = $e->getMessage();
}
$result->addResult($status, $message, $checkTitle);
}
foreach ($this->checkInstances() as $check) {
list($checkClass, $checkTitle) = $check;
try {
list($status, $message) = $checkClass->check();
// If the check fails, register that as an error
} catch (Exception $e) {
$status = EnvironmentCheck::ERROR;
$message = $e->getMessage();
}
$result->addResult($status, $message, $checkTitle);
}
return $result;
}
return $result;
}
/**
* Get instances of all the environment checks.
*
* @return array
*/
protected function checkInstances() {
$output = array();
foreach($this->checks as $check) {
list($checkClass, $checkTitle) = $check;
if(is_string($checkClass)) {
$checkInst = Object::create_from_string($checkClass);
if($checkInst instanceof EnvironmentCheck) {
$output[] = array($checkInst, $checkTitle);
} else {
throw new InvalidArgumentException("Bad EnvironmentCheck: '$checkClass' - the named class doesn't implement EnvironmentCheck");
}
} else if($checkClass instanceof EnvironmentCheck) {
$output[] = array($checkClass, $checkTitle);
} else {
throw new InvalidArgumentException("Bad EnvironmentCheck: " . var_export($check, true));
}
}
return $output;
}
/**
* Get instances of all the environment checks.
*
* @return array
*/
protected function checkInstances()
{
$output = array();
foreach ($this->checks as $check) {
list($checkClass, $checkTitle) = $check;
if (is_string($checkClass)) {
$checkInst = Object::create_from_string($checkClass);
if ($checkInst instanceof EnvironmentCheck) {
$output[] = array($checkInst, $checkTitle);
} else {
throw new InvalidArgumentException("Bad EnvironmentCheck: '$checkClass' - the named class doesn't implement EnvironmentCheck");
}
} elseif ($checkClass instanceof EnvironmentCheck) {
$output[] = array($checkClass, $checkTitle);
} else {
throw new InvalidArgumentException("Bad EnvironmentCheck: " . var_export($check, true));
}
}
return $output;
}
/**
* Add a check to this suite.
*
* @param mixed $check
* @param string $title
*/
public function push($check, $title = null) {
if(!$title) {
$title = is_string($check) ? $check : get_class($check);
}
$this->checks[] = array($check, $title);
}
/**
* Add a check to this suite.
*
* @param mixed $check
* @param string $title
*/
public function push($check, $title = null)
{
if (!$title) {
$title = is_string($check) ? $check : get_class($check);
}
$this->checks[] = array($check, $title);
}
/////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////
/**
* @var array
*/
protected static $instances = array();
/**
* @var array
*/
protected static $instances = array();
/**
* Return a named instance of EnvironmentCheckSuite.
*
* @param string $name
*
* @return EnvironmentCheckSuite
*/
static function inst($name) {
if(!isset(self::$instances[$name])) self::$instances[$name] = new EnvironmentCheckSuite($name);
return self::$instances[$name];
}
/**
* Return a named instance of EnvironmentCheckSuite.
*
* @param string $name
*
* @return EnvironmentCheckSuite
*/
public static function inst($name)
{
if (!isset(self::$instances[$name])) {
self::$instances[$name] = new EnvironmentCheckSuite($name);
}
return self::$instances[$name];
}
/**
* Register a check against the named check suite.
*
* @param string|array $names
* @param EnvironmentCheck $check
* @param string|array
*/
static function register($names, $check, $title = null) {
if(!is_array($names)) $names = array($names);
foreach($names as $name) self::inst($name)->push($check, $title);
}
/**
* Register a check against the named check suite.
*
* @param string|array $names
* @param EnvironmentCheck $check
* @param string|array
*/
public static function register($names, $check, $title = null)
{
if (!is_array($names)) {
$names = array($names);
}
foreach ($names as $name) {
self::inst($name)->push($check, $title);
}
}
/**
* Unregisters all checks.
*/
static function reset() {
self::$instances = array();
}
/**
* Unregisters all checks.
*/
public static function reset()
{
self::$instances = array();
}
}
/**
* A single set of results from running an EnvironmentCheckSuite
*/
class EnvironmentCheckSuiteResult extends ViewableData {
/**
* @var ArrayList
*/
protected $details;
class EnvironmentCheckSuiteResult extends ViewableData
{
/**
* @var ArrayList
*/
protected $details;
/**
* @var int
*/
protected $worst = 0;
/**
* @var int
*/
protected $worst = 0;
function __construct() {
parent::__construct();
$this->details = new ArrayList();
}
public function __construct()
{
parent::__construct();
$this->details = new ArrayList();
}
/**
* @param int $status
* @param string $message
* @param string $checkIdentifier
*/
function addResult($status, $message, $checkIdentifier) {
$this->details->push(new ArrayData(array(
'Check' => $checkIdentifier,
'Status' => $this->statusText($status),
'StatusCode' => $status,
'Message' => $message,
)));
/**
* @param int $status
* @param string $message
* @param string $checkIdentifier
*/
public function addResult($status, $message, $checkIdentifier)
{
$this->details->push(new ArrayData(array(
'Check' => $checkIdentifier,
'Status' => $this->statusText($status),
'StatusCode' => $status,
'Message' => $message,
)));
$this->worst = max($this->worst, $status);
}
$this->worst = max($this->worst, $status);
}
/**
* Returns true if there are no errors.
*
* @return bool
*/
public function ShouldPass() {
return $this->worst <= EnvironmentCheck::WARNING;
}
/**
* Returns true if there are no errors.
*
* @return bool
*/
public function ShouldPass()
{
return $this->worst <= EnvironmentCheck::WARNING;
}
/**
* Returns overall (i.e. worst) status as a string.
*
* @return string
*/
function Status() {
return $this->statusText($this->worst);
}
/**
* Returns overall (i.e. worst) status as a string.
*
* @return string
*/
public function Status()
{
return $this->statusText($this->worst);
}
/**
* Returns detailed status information about each check.
*
* @return ArrayList
*/
function Details() {
return $this->details;
}
/**
* Returns detailed status information about each check.
*
* @return ArrayList
*/
public function Details()
{
return $this->details;
}
/**
* Convert the final result status and details to JSON.
*
* @return string
*/
function toJSON() {
$result = array(
'Status' => $this->Status(),
'ShouldPass' => $this->ShouldPass(),
'Checks' => array()
);
foreach($this->details as $detail) {
$result['Checks'][] = $detail->toMap();
}
return json_encode($result);
}
/**
* Convert the final result status and details to JSON.
*
* @return string
*/
public function toJSON()
{
$result = array(
'Status' => $this->Status(),
'ShouldPass' => $this->ShouldPass(),
'Checks' => array()
);
foreach ($this->details as $detail) {
$result['Checks'][] = $detail->toMap();
}
return json_encode($result);
}
/**
* Return a text version of a status code.
*
* @return string
*/
protected function statusText($status) {
switch($status) {
case EnvironmentCheck::ERROR: return "ERROR";
case EnvironmentCheck::WARNING: return "WARNING";
case EnvironmentCheck::OK: return "OK";
case 0: return "NO CHECKS";
default: throw new InvalidArgumentException("Bad environment check status '$status'");
}
}
/**
* Return a text version of a status code.
*
* @return string
*/
protected function statusText($status)
{
switch ($status) {
case EnvironmentCheck::ERROR: return "ERROR";
case EnvironmentCheck::WARNING: return "WARNING";
case EnvironmentCheck::OK: return "OK";
case 0: return "NO CHECKS";
default: throw new InvalidArgumentException("Bad environment check status '$status'");
}
}
}

View File

@ -3,272 +3,290 @@
/**
* Provides an interface for checking the given EnvironmentCheckSuite.
*/
class EnvironmentChecker extends RequestHandler {
/**
* @var array
*/
private static $url_handlers = array(
'' => 'index',
);
class EnvironmentChecker extends RequestHandler
{
/**
* @var array
*/
private static $url_handlers = array(
'' => 'index',
);
/**
* @var string
*/
protected $checkSuiteName;
/**
* @var string
*/
protected $checkSuiteName;
/**
* @var string
*/
protected $title;
/**
* @var string
*/
protected $title;
/**
* @var int
*/
protected $errorCode = 500;
/**
* @var int
*/
protected $errorCode = 500;
/**
* @var null|string
*/
private static $to_email_address = null;
/**
* @var null|string
*/
private static $to_email_address = null;
/**
* @var null|string
*/
private static $from_email_address = null;
/**
* @var null|string
*/
private static $from_email_address = null;
/**
* @var bool
*/
private static $email_results = false;
/**
* @var bool
*/
private static $email_results = false;
/**
* @var bool Log results via {@link SS_Log}
*/
private static $log_results_warning = false;
/**
* @var bool Log results via {@link SS_Log}
*/
private static $log_results_warning = false;
/**
* @var int Maps to {@link Zend_Log} levels. Defaults to Zend_Log::WARN
*/
private static $log_results_warning_level = 4;
/**
* @var int Maps to {@link Zend_Log} levels. Defaults to Zend_Log::WARN
*/
private static $log_results_warning_level = 4;
/**
* @var bool Log results via {@link SS_Log}
*/
private static $log_results_error = false;
/**
* @var bool Log results via {@link SS_Log}
*/
private static $log_results_error = false;
/**
* @var int Maps to {@link Zend_Log} levels. Defaults to Zend_Log::ALERT
*/
private static $log_results_error_level = 1;
/**
* @var int Maps to {@link Zend_Log} levels. Defaults to Zend_Log::ALERT
*/
private static $log_results_error_level = 1;
/**
* @param string $checkSuiteName
* @param string $title
*/
function __construct($checkSuiteName, $title) {
parent::__construct();
$this->checkSuiteName = $checkSuiteName;
$this->title = $title;
}
/**
* @param string $checkSuiteName
* @param string $title
*/
public function __construct($checkSuiteName, $title)
{
parent::__construct();
$this->checkSuiteName = $checkSuiteName;
$this->title = $title;
}
/**
* @param string $permission
*
* @throws SS_HTTPResponse_Exception
*/
function init($permission = 'ADMIN') {
// if the environment supports it, provide a basic auth challenge and see if it matches configured credentials
if(defined('ENVCHECK_BASICAUTH_USERNAME') && defined('ENVCHECK_BASICAUTH_PASSWORD')) {
if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
// authenticate the input user/pass with the configured credentials
if(
!(
$_SERVER['PHP_AUTH_USER'] == ENVCHECK_BASICAUTH_USERNAME
&& $_SERVER['PHP_AUTH_PW'] == ENVCHECK_BASICAUTH_PASSWORD
)
) {
$response = new SS_HTTPResponse(null, 401);
$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
// Exception is caught by RequestHandler->handleRequest() and will halt further execution
$e = new SS_HTTPResponse_Exception(null, 401);
$e->setResponse($response);
throw $e;
}
} else {
$response = new SS_HTTPResponse(null, 401);
$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
// Exception is caught by RequestHandler->handleRequest() and will halt further execution
$e = new SS_HTTPResponse_Exception(null, 401);
$e->setResponse($response);
throw $e;
}
} else {
if(!$this->canAccess(null, $permission)) return $this->httpError(403);
}
}
/**
* @param string $permission
*
* @throws SS_HTTPResponse_Exception
*/
public function init($permission = 'ADMIN')
{
// if the environment supports it, provide a basic auth challenge and see if it matches configured credentials
if (defined('ENVCHECK_BASICAUTH_USERNAME') && defined('ENVCHECK_BASICAUTH_PASSWORD')) {
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
// authenticate the input user/pass with the configured credentials
if (
!(
$_SERVER['PHP_AUTH_USER'] == ENVCHECK_BASICAUTH_USERNAME
&& $_SERVER['PHP_AUTH_PW'] == ENVCHECK_BASICAUTH_PASSWORD
)
) {
$response = new SS_HTTPResponse(null, 401);
$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
// Exception is caught by RequestHandler->handleRequest() and will halt further execution
$e = new SS_HTTPResponse_Exception(null, 401);
$e->setResponse($response);
throw $e;
}
} else {
$response = new SS_HTTPResponse(null, 401);
$response->addHeader('WWW-Authenticate', "Basic realm=\"Environment check\"");
// Exception is caught by RequestHandler->handleRequest() and will halt further execution
$e = new SS_HTTPResponse_Exception(null, 401);
$e->setResponse($response);
throw $e;
}
} else {
if (!$this->canAccess(null, $permission)) {
return $this->httpError(403);
}
}
}
/**
* @param null|int|Member $member
* @param string $permission
*
* @return bool
*
* @throws SS_HTTPResponse_Exception
*/
function canAccess($member = null, $permission = "ADMIN") {
if(!$member) {
$member = Member::currentUser();
}
/**
* @param null|int|Member $member
* @param string $permission
*
* @return bool
*
* @throws SS_HTTPResponse_Exception
*/
public function canAccess($member = null, $permission = "ADMIN")
{
if (!$member) {
$member = Member::currentUser();
}
if(!$member) {
$member = BasicAuth::requireLogin('Environment Checker', $permission, false);
}
if (!$member) {
$member = BasicAuth::requireLogin('Environment Checker', $permission, false);
}
// We allow access to this controller regardless of live-status or ADMIN permission only
// if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
if(
Director::isDev()
|| Director::is_cli()
|| empty($permission)
|| Permission::checkMember($member, $permission)
) {
return true;
}
// We allow access to this controller regardless of live-status or ADMIN permission only
// if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
if (
Director::isDev()
|| Director::is_cli()
|| empty($permission)
|| Permission::checkMember($member, $permission)
) {
return true;
}
// Extended access checks.
// "Veto" style, return NULL to abstain vote.
$canExtended = null;
$results = $this->extend('canAccess', $member);
if($results && is_array($results)) {
if(!min($results)) return false;
else return true;
}
// Extended access checks.
// "Veto" style, return NULL to abstain vote.
$canExtended = null;
$results = $this->extend('canAccess', $member);
if ($results && is_array($results)) {
if (!min($results)) {
return false;
} else {
return true;
}
}
return false;
}
return false;
}
/**
* @return SS_HTTPResponse
*/
function index() {
$response = new SS_HTTPResponse;
$result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
/**
* @return SS_HTTPResponse
*/
public function index()
{
$response = new SS_HTTPResponse;
$result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
if(!$result->ShouldPass()) {
$response->setStatusCode($this->errorCode);
}
if (!$result->ShouldPass()) {
$response->setStatusCode($this->errorCode);
}
$resultText = $result->customise(array(
"URL" => Director::absoluteBaseURL(),
"Title" => $this->title,
"Name" => $this->checkSuiteName,
"ErrorCode" => $this->errorCode,
))->renderWith("EnvironmentChecker");
$resultText = $result->customise(array(
"URL" => Director::absoluteBaseURL(),
"Title" => $this->title,
"Name" => $this->checkSuiteName,
"ErrorCode" => $this->errorCode,
))->renderWith("EnvironmentChecker");
if ($this->config()->email_results && !$result->ShouldPass()) {
$email = new Email($this->config()->from_email_address, $this->config()->to_email_address, $this->title, $resultText);
$email->send();
}
if ($this->config()->email_results && !$result->ShouldPass()) {
$email = new Email($this->config()->from_email_address, $this->config()->to_email_address, $this->title, $resultText);
$email->send();
}
// Optionally log errors and warnings individually
foreach($result->Details() as $detail) {
if($this->config()->log_results_warning && $detail->StatusCode == EnvironmentCheck::WARNING) {
$this->log(
sprintf('EnvironmentChecker warning at "%s" check. Message: %s', $detail->Check, $detail->Message),
$this->config()->log_results_warning_level
);
} elseif($this->config()->log_results_error && $detail->StatusCode == EnvironmentCheck::ERROR) {
$this->log(
sprintf('EnvironmentChecker error at "%s" check. Message: %s', $detail->Check, $detail->Message),
$this->config()->log_results_error_level
);
}
}
// Optionally log errors and warnings individually
foreach ($result->Details() as $detail) {
if ($this->config()->log_results_warning && $detail->StatusCode == EnvironmentCheck::WARNING) {
$this->log(
sprintf('EnvironmentChecker warning at "%s" check. Message: %s', $detail->Check, $detail->Message),
$this->config()->log_results_warning_level
);
} elseif ($this->config()->log_results_error && $detail->StatusCode == EnvironmentCheck::ERROR) {
$this->log(
sprintf('EnvironmentChecker error at "%s" check. Message: %s', $detail->Check, $detail->Message),
$this->config()->log_results_error_level
);
}
}
// output the result as JSON if requested
if(
$this->getRequest()->getExtension() == 'json'
|| strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
) {
$response->setBody($result->toJSON());
$response->addHeader('Content-Type', 'application/json');
return $response;
}
// output the result as JSON if requested
if (
$this->getRequest()->getExtension() == 'json'
|| strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
) {
$response->setBody($result->toJSON());
$response->addHeader('Content-Type', 'application/json');
return $response;
}
$response->setBody($resultText);
return $response;
}
$response->setBody($resultText);
return $response;
}
/**
* @param string $message
* @param int $level
*/
public function log($message, $level) {
SS_Log::log($message, $level);
}
/**
* @param string $message
* @param int $level
*/
public function log($message, $level)
{
SS_Log::log($message, $level);
}
/**
* Set the HTTP status code that should be returned when there's an error.
*
* @param int $errorCode
*/
function setErrorCode($errorCode) {
$this->errorCode = $errorCode;
}
/**
* Set the HTTP status code that should be returned when there's an error.
*
* @param int $errorCode
*/
public function setErrorCode($errorCode)
{
$this->errorCode = $errorCode;
}
/**
* @deprecated
* @param string $from
*/
public static function set_from_email_address($from) {
Deprecation::notice('2.0', 'Use config API instead');
Config::inst()->update('EnvironmentChecker', 'from_email_address', $from);
}
/**
* @deprecated
* @param string $from
*/
public static function set_from_email_address($from)
{
Deprecation::notice('2.0', 'Use config API instead');
Config::inst()->update('EnvironmentChecker', 'from_email_address', $from);
}
/**
* @deprecated
* @return null|string
*/
public static function get_from_email_address() {
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'from_email_address');
}
/**
* @deprecated
* @return null|string
*/
public static function get_from_email_address()
{
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'from_email_address');
}
/**
* @deprecated
* @param string $to
*/
public static function set_to_email_address($to) {
Deprecation::notice('2.0', 'Use config API instead');
Config::inst()->update('EnvironmentChecker', 'to_email_address', $to);
}
/**
* @deprecated
* @param string $to
*/
public static function set_to_email_address($to)
{
Deprecation::notice('2.0', 'Use config API instead');
Config::inst()->update('EnvironmentChecker', 'to_email_address', $to);
}
/**
* @deprecated
* @return null|string
*/
public static function get_to_email_address() {
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'to_email_address');
}
/**
* @deprecated
* @return null|string
*/
public static function get_to_email_address()
{
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'to_email_address');
}
/**
* @deprecated
* @param bool $results
*/
public static function set_email_results($results) {
Deprecation::notice('2.0', 'Use config API instead');
Config::inst()->update('EnvironmentChecker', 'email_results', $results);
}
/**
* @deprecated
* @param bool $results
*/
public static function set_email_results($results)
{
Deprecation::notice('2.0', 'Use config API instead');
Config::inst()->update('EnvironmentChecker', 'email_results', $results);
}
/**
* @deprecated
* @return bool
*/
public static function get_email_results() {
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'email_results');
}
/**
* @deprecated
* @return bool
*/
public static function get_email_results()
{
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'email_results');
}
}

View File

@ -4,34 +4,37 @@
* Check that the connection to the database is working, by ensuring that the table exists and that
* the table contains some records.
*/
class DatabaseCheck implements EnvironmentCheck {
protected $checkTable;
class DatabaseCheck implements EnvironmentCheck
{
protected $checkTable;
/**
* By default, Member will be checked.
*
* @param string $checkTable
*/
function __construct($checkTable = "Member") {
$this->checkTable = $checkTable;
}
/**
* By default, Member will be checked.
*
* @param string $checkTable
*/
public function __construct($checkTable = "Member")
{
$this->checkTable = $checkTable;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
if(!DB::getConn()->hasTable($this->checkTable)) {
return array(EnvironmentCheck::ERROR, "$this->checkTable not present in the database");
}
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
if (!DB::getConn()->hasTable($this->checkTable)) {
return array(EnvironmentCheck::ERROR, "$this->checkTable not present in the database");
}
$count = DB::query("SELECT COUNT(*) FROM \"$this->checkTable\"")->value();
if($count > 0) {
return array(EnvironmentCheck::OK, "");
} else {
return array(EnvironmentCheck::WARNING, "$this->checkTable queried ok but has no records");
}
}
$count = DB::query("SELECT COUNT(*) FROM \"$this->checkTable\"")->value();
if ($count > 0) {
return array(EnvironmentCheck::OK, "");
} else {
return array(EnvironmentCheck::WARNING, "$this->checkTable queried ok but has no records");
}
}
}

View File

@ -8,109 +8,120 @@
* Requires curl to present, so ensure to check it before with the following:
* <code>EnvironmentCheckSuite::register('check', 'HasFunctionCheck("curl_init")', "Does PHP have CURL support?");</code>
*/
class ExternalURLCheck implements EnvironmentCheck {
/**
* @var array
*/
protected $urls = array();
class ExternalURLCheck implements EnvironmentCheck
{
/**
* @var array
*/
protected $urls = array();
/**
* @var Int Timeout in seconds.
*/
protected $timeout;
/**
* @var Int Timeout in seconds.
*/
protected $timeout;
/**
* @param string $urls Space-separated list of absolute URLs.
* @param int $timeout
*/
function __construct($urls, $timeout = 15) {
if($urls) $this->urls = explode(' ', $urls);
$this->timeout = $timeout;
}
/**
* @param string $urls Space-separated list of absolute URLs.
* @param int $timeout
*/
public function __construct($urls, $timeout = 15)
{
if ($urls) {
$this->urls = explode(' ', $urls);
}
$this->timeout = $timeout;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
$urls = $this->getURLs();
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
$urls = $this->getURLs();
$chs = array();
foreach($urls as $url) {
$ch = curl_init();
$chs[] = $ch;
curl_setopt_array($ch, $this->getCurlOpts($url));
}
// Parallel execution for faster performance
$mh = curl_multi_init();
foreach($chs as $ch) curl_multi_add_handle($mh,$ch);
$active = null;
// Execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
curl_multi_select($mh);
} while ($active > 0);
$chs = array();
foreach ($urls as $url) {
$ch = curl_init();
$chs[] = $ch;
curl_setopt_array($ch, $this->getCurlOpts($url));
}
// Parallel execution for faster performance
$mh = curl_multi_init();
foreach ($chs as $ch) {
curl_multi_add_handle($mh, $ch);
}
$active = null;
// Execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
curl_multi_select($mh);
} while ($active > 0);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
$hasError = false;
$msgs = array();
foreach($chs as $ch) {
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch) || $code >= 400) {
$hasError = true;
$msgs[] = sprintf(
'Error retrieving "%s": %s (Code: %s)',
$url,
curl_error($ch),
$code
);
} else {
$msgs[] = sprintf(
'Success retrieving "%s" (Code: %s)',
$url,
$code
);
}
}
$hasError = false;
$msgs = array();
foreach ($chs as $ch) {
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch) || $code >= 400) {
$hasError = true;
$msgs[] = sprintf(
'Error retrieving "%s": %s (Code: %s)',
$url,
curl_error($ch),
$code
);
} else {
$msgs[] = sprintf(
'Success retrieving "%s" (Code: %s)',
$url,
$code
);
}
}
// Close the handles
foreach($chs as $ch) curl_multi_remove_handle($mh, $ch);
curl_multi_close($mh);
if($hasError) {
return array(EnvironmentCheck::ERROR, implode(', ', $msgs));
} else {
return array(EnvironmentCheck::OK, implode(', ', $msgs));
}
}
// Close the handles
foreach ($chs as $ch) {
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
if ($hasError) {
return array(EnvironmentCheck::ERROR, implode(', ', $msgs));
} else {
return array(EnvironmentCheck::OK, implode(', ', $msgs));
}
}
/**
* @return array
*/
protected function getCurlOpts($url) {
return array(
CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FAILONERROR => 1,
CURLOPT_TIMEOUT => $this->timeout,
);
}
/**
* @return array
*/
protected function getCurlOpts($url)
{
return array(
CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FAILONERROR => 1,
CURLOPT_TIMEOUT => $this->timeout,
);
}
/**
* @return array
*/
protected function getURLs() {
return $this->urls;
}
/**
* @return array
*/
protected function getURLs()
{
return $this->urls;
}
}

View File

@ -19,160 +19,165 @@
* 'Check a calculator.json exists only'
* );
*/
class FileAccessibilityAndValidationCheck implements EnvironmentCheck {
/**
* @var int
*/
const CHECK_SINGLE = 1;
class FileAccessibilityAndValidationCheck implements EnvironmentCheck
{
/**
* @var int
*/
const CHECK_SINGLE = 1;
/**
* @var int
*/
const CHECK_ALL = 2;
/**
* @var int
*/
const CHECK_ALL = 2;
/**
* Absolute path to a file or folder, compatible with glob().
*
* @var string
*/
protected $path;
/**
* Absolute path to a file or folder, compatible with glob().
*
* @var string
*/
protected $path;
/**
* Constant, check for a single file to match age criteria, or all of them.
*
* @var int
*/
protected $fileTypeValidateFunc;
/**
* Constant, check for a single file to match age criteria, or all of them.
*
* @var int
*/
protected $fileTypeValidateFunc;
/**
* Constant, check for a single file to match age criteria, or all of them.
*
* @var int
*/
protected $checkType;
/**
* Constant, check for a single file to match age criteria, or all of them.
*
* @var int
*/
protected $checkType;
/**
* @param string $path
* @param string $fileTypeValidateFunc
* @param null|int $checkType
*/
function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null) {
$this->path = $path;
$this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc:'noVidation';
$this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
}
/**
* @param string $path
* @param string $fileTypeValidateFunc
* @param null|int $checkType
*/
public function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null)
{
$this->path = $path;
$this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc:'noVidation';
$this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
$origStage = Versioned::get_reading_mode();
Versioned::set_reading_mode('Live');
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
$origStage = Versioned::get_reading_mode();
Versioned::set_reading_mode('Live');
$files = $this->getFiles();
if($files){
$fileTypeValidateFunc = $this->fileTypeValidateFunc;
if(method_exists ($this, $fileTypeValidateFunc)){
$invalidFiles = array();
$validFiles = array();
$files = $this->getFiles();
if ($files) {
$fileTypeValidateFunc = $this->fileTypeValidateFunc;
if (method_exists($this, $fileTypeValidateFunc)) {
$invalidFiles = array();
$validFiles = array();
foreach($files as $file){
if($this->$fileTypeValidateFunc($file)){
$validFiles[] = $file;
}else{
$invalidFiles[] = $file;
}
}
foreach ($files as $file) {
if ($this->$fileTypeValidateFunc($file)) {
$validFiles[] = $file;
} else {
$invalidFiles[] = $file;
}
}
// If at least one file was valid, count as passed
if($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
$validFileList = "\n";
foreach($validFiles as $vf){
$validFileList .= $vf."\n";
}
if($fileTypeValidateFunc == 'noVidation') {
$checkReturn = array(
EnvironmentCheck::OK,
sprintf('At least these file(s) accessible: %s', $validFileList)
);
}else{
$checkReturn = array(
EnvironmentCheck::OK,
sprintf('At least these file(s) passed file type validate function "%s": %s', $fileTypeValidateFunc, $validFileList)
);
}
} else {
if (count($invalidFiles) == 0) $checkReturn = array(EnvironmentCheck::OK, 'All files valideted');
else {
$invalidFileList = "\n";
foreach($invalidFiles as $vf){
$invalidFileList .= $vf."\n";
}
// If at least one file was valid, count as passed
if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
$validFileList = "\n";
foreach ($validFiles as $vf) {
$validFileList .= $vf."\n";
}
if ($fileTypeValidateFunc == 'noVidation') {
$checkReturn = array(
EnvironmentCheck::OK,
sprintf('At least these file(s) accessible: %s', $validFileList)
);
} else {
$checkReturn = array(
EnvironmentCheck::OK,
sprintf('At least these file(s) passed file type validate function "%s": %s', $fileTypeValidateFunc, $validFileList)
);
}
} else {
if (count($invalidFiles) == 0) {
$checkReturn = array(EnvironmentCheck::OK, 'All files valideted');
} else {
$invalidFileList = "\n";
foreach ($invalidFiles as $vf) {
$invalidFileList .= $vf."\n";
}
if($fileTypeValidateFunc == 'noVidation'){
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf('File(s) not accessible: %s', $invalidFileList)
);
}else{
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf('File(s) not passing the file type validate function "%s": %s', $fileTypeValidateFunc, $invalidFileList)
);
}
}
}
}else{
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf("Invalid file type validation method name passed: %s ", $fileTypeValidateFunc)
);
}
if ($fileTypeValidateFunc == 'noVidation') {
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf('File(s) not accessible: %s', $invalidFileList)
);
} else {
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf('File(s) not passing the file type validate function "%s": %s', $fileTypeValidateFunc, $invalidFileList)
);
}
}
}
} else {
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf("Invalid file type validation method name passed: %s ", $fileTypeValidateFunc)
);
}
} else {
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf("No files accessible at path %s", $this->path)
);
}
}else{
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf("No files accessible at path %s", $this->path)
);
}
Versioned::set_reading_mode($origStage);
Versioned::set_reading_mode($origStage);
return $checkReturn;
}
return $checkReturn;
}
/**
* @param string $file
*
* @return bool
*/
private function jsonValidate($file)
{
$json = json_decode(file_get_contents($file));
if (!$json) {
return false;
} else {
return true;
}
}
/**
* @param string $file
*
* @return bool
*/
private function jsonValidate($file){
$json = json_decode(file_get_contents($file));
if(!$json) {
return false;
}else{
return true;
}
}
/**
* @param string $file
*
* @return bool
*/
protected function noVidation($file)
{
return true;
}
/**
* @param string $file
*
* @return bool
*/
protected function noVidation($file) {
return true;
}
/**
* Gets a list of absolute file paths.
*
* @return array
*/
protected function getFiles() {
return glob($this->path);
}
/**
* Gets a list of absolute file paths.
*
* @return array
*/
protected function getFiles()
{
return glob($this->path);
}
}

View File

@ -19,117 +19,125 @@
* 'FileAgeCheck("' . BASE_PATH . '/../backups/*' . '", "-1 day", '>', " . FileAgeCheck::CHECK_SINGLE) . "'
* );
*/
class FileAgeCheck implements EnvironmentCheck {
/**
* @var int
*/
const CHECK_SINGLE = 1;
class FileAgeCheck implements EnvironmentCheck
{
/**
* @var int
*/
const CHECK_SINGLE = 1;
/**
* @var int
*/
const CHECK_ALL = 2;
/**
* Absolute path to a file or folder, compatible with glob().
*
* @var string
*/
protected $path;
/**
* @var int
*/
const CHECK_ALL = 2;
/**
* Absolute path to a file or folder, compatible with glob().
*
* @var string
*/
protected $path;
/**
* Relative date specification, compatible with strtotime().
*
* @var string
*/
protected $relativeAge;
/**
* Relative date specification, compatible with strtotime().
*
* @var string
*/
protected $relativeAge;
/**
* The function to use for checking file age: so filemtime(), filectime(), or fileatime().
*
* @var string
*/
protected $checkFn;
/**
* The function to use for checking file age: so filemtime(), filectime(), or fileatime().
*
* @var string
*/
protected $checkFn;
/**
* Constant, check for a single file to match age criteria, or all of them.
*
* @var int
*/
protected $checkType;
/**
* Constant, check for a single file to match age criteria, or all of them.
*
* @var int
*/
protected $checkType;
/**
* Type of comparison (either > or <).
*
* @var string
*/
protected $compareOperand;
/**
* Type of comparison (either > or <).
*
* @var string
*/
protected $compareOperand;
/**
* @param string $path
* @param string $relativeAge
* @param string $compareOperand
* @param null|int $checkType
* @param string $checkFn
*/
function __construct($path, $relativeAge, $compareOperand = '>', $checkType = null, $checkFn = 'filemtime') {
$this->path = $path;
$this->relativeAge = $relativeAge;
$this->checkFn = $checkFn;
$this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
$this->compareOperand = $compareOperand;
}
/**
* @param string $path
* @param string $relativeAge
* @param string $compareOperand
* @param null|int $checkType
* @param string $checkFn
*/
public function __construct($path, $relativeAge, $compareOperand = '>', $checkType = null, $checkFn = 'filemtime')
{
$this->path = $path;
$this->relativeAge = $relativeAge;
$this->checkFn = $checkFn;
$this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
$this->compareOperand = $compareOperand;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
$cutoffTime = strtotime($this->relativeAge, SS_Datetime::now()->Format('U'));
$files = $this->getFiles();
$invalidFiles = array();
$validFiles = array();
$checkFn = $this->checkFn;
$allValid = true;
if($files) foreach($files as $file) {
$fileTime = $checkFn($file);
$valid = ($this->compareOperand == '>') ? ($fileTime >= $cutoffTime) : ($fileTime <= $cutoffTime);
if($valid) {
$validFiles[] = $file;
} else {
$invalidFiles[] = $file;
if($this->checkType == self::CHECK_ALL) {
return array(
EnvironmentCheck::ERROR,
sprintf(
'File "%s" doesn\'t match age check (compare %s: %s, actual: %s)',
$file, $this->compareOperand, date('c', $cutoffTime), date('c', $fileTime)
)
);
}
}
}
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
$cutoffTime = strtotime($this->relativeAge, SS_Datetime::now()->Format('U'));
$files = $this->getFiles();
$invalidFiles = array();
$validFiles = array();
$checkFn = $this->checkFn;
$allValid = true;
if ($files) {
foreach ($files as $file) {
$fileTime = $checkFn($file);
$valid = ($this->compareOperand == '>') ? ($fileTime >= $cutoffTime) : ($fileTime <= $cutoffTime);
if ($valid) {
$validFiles[] = $file;
} else {
$invalidFiles[] = $file;
if ($this->checkType == self::CHECK_ALL) {
return array(
EnvironmentCheck::ERROR,
sprintf(
'File "%s" doesn\'t match age check (compare %s: %s, actual: %s)',
$file, $this->compareOperand, date('c', $cutoffTime), date('c', $fileTime)
)
);
}
}
}
}
// If at least one file was valid, count as passed
if($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
return array(EnvironmentCheck::OK, '');
} else {
if (count($invalidFiles) == 0) return array(EnvironmentCheck::OK, '');
else return array(
EnvironmentCheck::ERROR,
sprintf('No files matched criteria (%s %s)', $this->compareOperand, date('c', $cutoffTime))
);
}
}
// If at least one file was valid, count as passed
if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
return array(EnvironmentCheck::OK, '');
} else {
if (count($invalidFiles) == 0) {
return array(EnvironmentCheck::OK, '');
} else {
return array(
EnvironmentCheck::ERROR,
sprintf('No files matched criteria (%s %s)', $this->compareOperand, date('c', $cutoffTime))
);
}
}
}
/**
* Gets a list of absolute file paths.
*
* @return array
*/
protected function getFiles() {
return glob($this->path);
}
/**
* Gets a list of absolute file paths.
*
* @return array
*/
protected function getFiles()
{
return glob($this->path);
}
}

View File

@ -3,66 +3,75 @@
/**
* Check that the given file is writable.
*/
class FileWriteableCheck implements EnvironmentCheck {
/**
* @var string
*/
protected $path;
class FileWriteableCheck implements EnvironmentCheck
{
/**
* @var string
*/
protected $path;
/**
* @param string $path The full path. If a relative path, it will relative to the BASE_PATH.
*/
function __construct($path) {
$this->path = $path;
}
/**
* @param string $path The full path. If a relative path, it will relative to the BASE_PATH.
*/
public function __construct($path)
{
$this->path = $path;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
if($this->path[0] == '/') $filename = $this->path;
else $filename = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $this->path);
if(file_exists($filename)) $isWriteable = is_writeable($filename);
else $isWriteable = is_writeable(dirname($filename));
if(!$isWriteable) {
if(function_exists('posix_getgroups')) {
$userID = posix_geteuid();
$user = posix_getpwuid($userID);
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
if ($this->path[0] == '/') {
$filename = $this->path;
} else {
$filename = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $this->path);
}
if (file_exists($filename)) {
$isWriteable = is_writeable($filename);
} else {
$isWriteable = is_writeable(dirname($filename));
}
if (!$isWriteable) {
if (function_exists('posix_getgroups')) {
$userID = posix_geteuid();
$user = posix_getpwuid($userID);
$currentOwnerID = fileowner(file_exists($filename) ? $filename : dirname($filename) );
$currentOwner = posix_getpwuid($currentOwnerID);
$currentOwnerID = fileowner(file_exists($filename) ? $filename : dirname($filename));
$currentOwner = posix_getpwuid($currentOwnerID);
$message = "User '$user[name]' needs to be able to write to this file:\n$filename\n\nThe file is currently owned by '$currentOwner[name]'. ";
$message = "User '$user[name]' needs to be able to write to this file:\n$filename\n\nThe file is currently owned by '$currentOwner[name]'. ";
if($user['name'] == $currentOwner['name']) {
$message .= "We recommend that you make the file writeable.";
} else {
$groups = posix_getgroups();
$groupList = array();
foreach($groups as $group) {
$groupInfo = posix_getgrgid($group);
if(in_array($currentOwner['name'], $groupInfo['members'])) $groupList[] = $groupInfo['name'];
}
if($groupList) {
$message .= " We recommend that you make the file group-writeable and change the group to one of these groups:\n - ". implode("\n - ", $groupList)
. "\n\nFor example:\nchmod g+w $filename\nchgrp " . $groupList[0] . " $filename";
} else {
$message .= " There is no user-group that contains both the web-server user and the owner of this file. Change the ownership of the file, create a new group, or temporarily make the file writeable by everyone during the install process.";
}
}
if ($user['name'] == $currentOwner['name']) {
$message .= "We recommend that you make the file writeable.";
} else {
$groups = posix_getgroups();
$groupList = array();
foreach ($groups as $group) {
$groupInfo = posix_getgrgid($group);
if (in_array($currentOwner['name'], $groupInfo['members'])) {
$groupList[] = $groupInfo['name'];
}
}
if ($groupList) {
$message .= " We recommend that you make the file group-writeable and change the group to one of these groups:\n - ". implode("\n - ", $groupList)
. "\n\nFor example:\nchmod g+w $filename\nchgrp " . $groupList[0] . " $filename";
} else {
$message .= " There is no user-group that contains both the web-server user and the owner of this file. Change the ownership of the file, create a new group, or temporarily make the file writeable by everyone during the install process.";
}
}
} else {
$message = "The webserver user needs to be able to write to this file:\n$filename";
}
return array(EnvironmentCheck::ERROR, $message);
}
} else {
$message = "The webserver user needs to be able to write to this file:\n$filename";
}
return array(EnvironmentCheck::ERROR, $message);
}
return array(EnvironmentCheck::OK,'');
}
return array(EnvironmentCheck::OK,'');
}
}

View File

@ -3,26 +3,32 @@
/**
* Check that the given class exists.
*/
class HasClassCheck implements EnvironmentCheck {
/**
* @var string
*/
protected $className;
class HasClassCheck implements EnvironmentCheck
{
/**
* @var string
*/
protected $className;
/**
* @param string $className The name of the class to look for.
*/
function __construct($className) {
$this->className = $className;
}
/**
* @param string $className The name of the class to look for.
*/
public function __construct($className)
{
$this->className = $className;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
if(class_exists($this->className)) return array(EnvironmentCheck::OK, 'Class ' . $this->className.' exists');
else return array(EnvironmentCheck::ERROR, 'Class ' . $this->className.' doesn\'t exist');
}
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
if (class_exists($this->className)) {
return array(EnvironmentCheck::OK, 'Class ' . $this->className.' exists');
} else {
return array(EnvironmentCheck::ERROR, 'Class ' . $this->className.' doesn\'t exist');
}
}
}

View File

@ -3,26 +3,32 @@
/**
* Check that the given function exists.
*/
class HasFunctionCheck implements EnvironmentCheck {
/**
* @var string
*/
protected $functionName;
class HasFunctionCheck implements EnvironmentCheck
{
/**
* @var string
*/
protected $functionName;
/**
* @param string $functionName The name of the function to look for.
*/
function __construct($functionName) {
$this->functionName = $functionName;
}
/**
* @param string $functionName The name of the function to look for.
*/
public function __construct($functionName)
{
$this->functionName = $functionName;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
if(function_exists($this->functionName)) return array(EnvironmentCheck::OK, $this->functionName.'() exists');
else return array(EnvironmentCheck::ERROR, $this->functionName.'() doesn\'t exist');
}
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
if (function_exists($this->functionName)) {
return array(EnvironmentCheck::OK, $this->functionName.'() exists');
} else {
return array(EnvironmentCheck::ERROR, $this->functionName.'() doesn\'t exist');
}
}
}

View File

@ -5,62 +5,69 @@
*
* Only checks socket connection with HELO command, not actually sending the email.
*/
class SMTPConnectCheck implements EnvironmentCheck {
/**
* @var string
*/
protected $host;
class SMTPConnectCheck implements EnvironmentCheck
{
/**
* @var string
*/
protected $host;
/**
* @var int
*/
protected $port;
/**
* @var int
*/
protected $port;
/**
* Timeout (in seconds).
*
* @var int
*/
protected $timeout;
/**
* Timeout (in seconds).
*
* @var int
*/
protected $timeout;
/**
* @param null|string $host
* @param null|int $port
* @param int $timeout
*/
function __construct($host = null, $port = null, $timeout = 15) {
$this->host = ($host) ? $host : ini_get('SMTP');
if(!$this->host) $this->host = 'localhost';
$this->port = ($port) ? $port : ini_get('smtp_port');
if(!$this->port) $this->port = 25;
/**
* @param null|string $host
* @param null|int $port
* @param int $timeout
*/
public function __construct($host = null, $port = null, $timeout = 15)
{
$this->host = ($host) ? $host : ini_get('SMTP');
if (!$this->host) {
$this->host = 'localhost';
}
$this->port = ($port) ? $port : ini_get('smtp_port');
if (!$this->port) {
$this->port = 25;
}
$this->timeout = $timeout;
}
$this->timeout = $timeout;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
$f = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
if(!$f) {
return array(
EnvironmentCheck::ERROR,
sprintf("Couldn't connect to SMTP on %s:%s (Error: %s %s)", $this->host, $this->port, $errno, $errstr)
);
}
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
$f = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
if (!$f) {
return array(
EnvironmentCheck::ERROR,
sprintf("Couldn't connect to SMTP on %s:%s (Error: %s %s)", $this->host, $this->port, $errno, $errstr)
);
}
fwrite($f, "HELO its_me\r\n");
$response = fread($f, 26);
if(substr($response, 0, 3) != '220') {
return array(
EnvironmentCheck::ERROR,
sprintf("Invalid mail server response: %s", $response)
);
}
fwrite($f, "HELO its_me\r\n");
$response = fread($f, 26);
if (substr($response, 0, 3) != '220') {
return array(
EnvironmentCheck::ERROR,
sprintf("Invalid mail server response: %s", $response)
);
}
return array(EnvironmentCheck::OK, '');
}
return array(EnvironmentCheck::OK, '');
}
}

View File

@ -5,49 +5,52 @@
*
* If there are no indexes of given class found, the returned status will still be "OK".
*/
class SolrIndexCheck implements EnvironmentCheck {
/**
* @var null|string
*/
protected $indexClass;
class SolrIndexCheck implements EnvironmentCheck
{
/**
* @var null|string
*/
protected $indexClass;
/**
* @param string $indexClass Limit the index checks to the specified class and all its subclasses.
*/
function __construct($indexClass = null) {
$this->indexClass = $indexClass;
}
/**
* @param string $indexClass Limit the index checks to the specified class and all its subclasses.
*/
public function __construct($indexClass = null)
{
$this->indexClass = $indexClass;
}
/**
* @inheritdoc
*
* @return array
*/
function check() {
$brokenCores = array();
/**
* @inheritdoc
*
* @return array
*/
public function check()
{
$brokenCores = array();
if (!class_exists('Solr')) {
return array(
EnvironmentCheck::ERROR,
'Class `Solr` not found. Is the fulltextsearch module installed?'
);
}
if (!class_exists('Solr')) {
return array(
EnvironmentCheck::ERROR,
'Class `Solr` not found. Is the fulltextsearch module installed?'
);
}
$service = Solr::service();
foreach (Solr::get_indexes($this->indexClass) as $index) {
$core = $index->getIndexName();
if (!$service->coreIsActive($core)) {
$brokenCores[] = $core;
}
}
$service = Solr::service();
foreach (Solr::get_indexes($this->indexClass) as $index) {
$core = $index->getIndexName();
if (!$service->coreIsActive($core)) {
$brokenCores[] = $core;
}
}
if (!empty($brokenCores)) {
return array(
EnvironmentCheck::ERROR,
'The following indexes are unavailable: ' . implode($brokenCores, ', ')
);
}
if (!empty($brokenCores)) {
return array(
EnvironmentCheck::ERROR,
'The following indexes are unavailable: ' . implode($brokenCores, ', ')
);
}
return array(EnvironmentCheck::OK, 'Expected indexes are available.');
}
return array(EnvironmentCheck::OK, 'Expected indexes are available.');
}
}

View File

@ -5,53 +5,54 @@
*
* Note that Director::test() will be used rather than a CURL check.
*/
class URLCheck implements EnvironmentCheck {
/**
* @var string
*/
protected $url;
class URLCheck implements EnvironmentCheck
{
/**
* @var string
*/
protected $url;
/**
* @var string
*/
protected $testString;
/*
* @param string $url The URL to check, relative to the site (homepage is '').
* @param string $testString An optional piece of text to search for on the homepage.
*/
function __construct($url = '', $testString = '') {
$this->url = $url;
$this->testString = $testString;
}
/**
* @var string
*/
protected $testString;
/*
* @param string $url The URL to check, relative to the site (homepage is '').
* @param string $testString An optional piece of text to search for on the homepage.
*/
public function __construct($url = '', $testString = '')
{
$this->url = $url;
$this->testString = $testString;
}
/**
* @inheritdoc
*
* @return array
*
* @throws SS_HTTPResponse_Exception
*/
function check() {
$response = Director::test($this->url);
/**
* @inheritdoc
*
* @return array
*
* @throws SS_HTTPResponse_Exception
*/
public function check()
{
$response = Director::test($this->url);
if($response->getStatusCode() != 200) {
return array(
EnvironmentCheck::ERROR,
sprintf('Error retrieving "%s" (Code: %d)', $this->url, $response->getStatusCode())
);
} else if($this->testString && (strpos($response->getBody(), $this->testString) === false)) {
return array(
EnvironmentCheck::WARNING,
sprintf('Success retrieving "%s", but string "%s" not found', $this->url, $this->testString)
);
} else {
return array(
EnvironmentCheck::OK,
sprintf('Success retrieving "%s"', $this->url)
);
}
}
if ($response->getStatusCode() != 200) {
return array(
EnvironmentCheck::ERROR,
sprintf('Error retrieving "%s" (Code: %d)', $this->url, $response->getStatusCode())
);
} elseif ($this->testString && (strpos($response->getBody(), $this->testString) === false)) {
return array(
EnvironmentCheck::WARNING,
sprintf('Success retrieving "%s", but string "%s" not found', $this->url, $this->testString)
);
} else {
return array(
EnvironmentCheck::OK,
sprintf('Success retrieving "%s"', $this->url)
);
}
}
}

View File

@ -3,12 +3,14 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class DevCheckControllerTest extends SapphireTest {
public function testIndexCreatesChecker() {
$controller = new DevCheckController();
class DevCheckControllerTest extends SapphireTest
{
public function testIndexCreatesChecker()
{
$controller = new DevCheckController();
$request = new SS_HTTPRequest('GET', 'example.com');
$request = new SS_HTTPRequest('GET', 'example.com');
$this->assertInstanceOf('EnvironmentChecker', $controller->index($request));
}
$this->assertInstanceOf('EnvironmentChecker', $controller->index($request));
}
}

View File

@ -3,21 +3,23 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class DevHealthControllerTest extends SapphireTest {
public function testIndexCreatesChecker() {
$controller = new DevHealthController();
class DevHealthControllerTest extends SapphireTest
{
public function testIndexCreatesChecker()
{
$controller = new DevHealthController();
$request = new SS_HTTPRequest('GET', 'example.com');
$request = new SS_HTTPRequest('GET', 'example.com');
// we need to fake authenticated access as BasicAuth::requireLogin doesn't like empty
// permission type strings, which is what health check uses.
// we need to fake authenticated access as BasicAuth::requireLogin doesn't like empty
// permission type strings, which is what health check uses.
define('ENVCHECK_BASICAUTH_USERNAME', 'foo');
define('ENVCHECK_BASICAUTH_PASSWORD', 'bar');
define('ENVCHECK_BASICAUTH_USERNAME', 'foo');
define('ENVCHECK_BASICAUTH_PASSWORD', 'bar');
$_SERVER['PHP_AUTH_USER'] = 'foo';
$_SERVER['PHP_AUTH_PW'] = 'bar';
$_SERVER['PHP_AUTH_USER'] = 'foo';
$_SERVER['PHP_AUTH_PW'] = 'bar';
$this->assertInstanceOf('EnvironmentChecker', $controller->index($request));
}
$this->assertInstanceOf('EnvironmentChecker', $controller->index($request));
}
}

View File

@ -1,89 +1,100 @@
<?php
class EnvironmentCheckerTest extends SapphireTest {
class EnvironmentCheckerTest extends SapphireTest
{
public function setUpOnce()
{
parent::setUpOnce();
public function setUpOnce() {
parent::setUpOnce();
Phockito::include_hamcrest();
}
Phockito::include_hamcrest();
}
public function setUp()
{
parent::setUp();
public function setUp() {
parent::setUp();
Config::nest();
}
Config::nest();
}
public function tearDown()
{
Config::unnest();
public function tearDown() {
Config::unnest();
parent::tearDown();
}
parent::tearDown();
}
public function testOnlyLogsWithErrors()
{
Config::inst()->update('EnvironmentChecker', 'log_results_warning', true);
Config::inst()->update('EnvironmentChecker', 'log_results_error', true);
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckNoErrors());
$checker = Phockito::spy(
'EnvironmentChecker',
'test suite',
'test'
);
public function testOnlyLogsWithErrors() {
Config::inst()->update('EnvironmentChecker', 'log_results_warning', true);
Config::inst()->update('EnvironmentChecker', 'log_results_error', true);
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckNoErrors());
$checker = Phockito::spy(
'EnvironmentChecker',
'test suite',
'test'
);
$response = $checker->index();
Phockito::verify($checker, 0)->log(anything(), anything());
EnvironmentCheckSuite::reset();
}
$response = $checker->index();
Phockito::verify($checker, 0)->log(anything(), anything());
EnvironmentCheckSuite::reset();
}
public function testLogsWithWarnings()
{
Config::inst()->update('EnvironmentChecker', 'log_results_warning', true);
Config::inst()->update('EnvironmentChecker', 'log_results_error', false);
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckWarnings());
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckErrors());
$checker = Phockito::spy(
'EnvironmentChecker',
'test suite',
'test'
);
public function testLogsWithWarnings() {
Config::inst()->update('EnvironmentChecker', 'log_results_warning', true);
Config::inst()->update('EnvironmentChecker', 'log_results_error', false);
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckWarnings());
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckErrors());
$checker = Phockito::spy(
'EnvironmentChecker',
'test suite',
'test'
);
$response = $checker->index();
Phockito::verify($checker, 1)->log(containsString('warning'), anything());
Phockito::verify($checker, 0)->log(containsString('error'), anything());
EnvironmentCheckSuite::reset();
}
$response = $checker->index();
Phockito::verify($checker, 1)->log(containsString('warning'), anything());
Phockito::verify($checker, 0)->log(containsString('error'), anything());
EnvironmentCheckSuite::reset();
}
public function testLogsWithErrors() {
Config::inst()->update('EnvironmentChecker', 'log_results_error', false);
Config::inst()->update('EnvironmentChecker', 'log_results_error', true);
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckWarnings());
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckErrors());
$checker = Phockito::spy(
'EnvironmentChecker',
'test suite',
'test'
);
$response = $checker->index();
Phockito::verify($checker, 0)->log(containsString('warning'), anything());
Phockito::verify($checker, 1)->log(containsString('error'), anything());
EnvironmentCheckSuite::reset();
}
public function testLogsWithErrors()
{
Config::inst()->update('EnvironmentChecker', 'log_results_error', false);
Config::inst()->update('EnvironmentChecker', 'log_results_error', true);
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckWarnings());
EnvironmentCheckSuite::register('test suite', new EnvironmentCheckerTest_CheckErrors());
$checker = Phockito::spy(
'EnvironmentChecker',
'test suite',
'test'
);
$response = $checker->index();
Phockito::verify($checker, 0)->log(containsString('warning'), anything());
Phockito::verify($checker, 1)->log(containsString('error'), anything());
EnvironmentCheckSuite::reset();
}
}
class EnvironmentCheckerTest_CheckNoErrors implements EnvironmentCheck, TestOnly{
public function check() {
return array(EnvironmentCheck::OK, '');
}
class EnvironmentCheckerTest_CheckNoErrors implements EnvironmentCheck, TestOnly
{
public function check()
{
return array(EnvironmentCheck::OK, '');
}
}
class EnvironmentCheckerTest_CheckWarnings implements EnvironmentCheck, TestOnly{
public function check() {
return array(EnvironmentCheck::WARNING, "test warning");
}
class EnvironmentCheckerTest_CheckWarnings implements EnvironmentCheck, TestOnly
{
public function check()
{
return array(EnvironmentCheck::WARNING, "test warning");
}
}
class EnvironmentCheckerTest_CheckErrors implements EnvironmentCheck, TestOnly{
public function check() {
return array(EnvironmentCheck::ERROR, "test error");
}
}
class EnvironmentCheckerTest_CheckErrors implements EnvironmentCheck, TestOnly
{
public function check()
{
return array(EnvironmentCheck::ERROR, "test error");
}
}

View File

@ -3,15 +3,17 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class DatabaseCheckTest extends SapphireTest {
public function testCheckReportsValidConnection() {
$check = new DatabaseCheck();
class DatabaseCheckTest extends SapphireTest
{
public function testCheckReportsValidConnection()
{
$check = new DatabaseCheck();
$expected = array(
EnvironmentCheck::OK,
'',
);
$expected = array(
EnvironmentCheck::OK,
'',
);
$this->assertEquals($expected, $check->check());
}
$this->assertEquals($expected, $check->check());
}
}

View File

@ -3,17 +3,19 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class ExternalURLCheckTest extends SapphireTest {
public function testCheckReportsMissingPages() {
$this->markTestSkipped('ExternalURLCheck seems faulty on some systems');
class ExternalURLCheckTest extends SapphireTest
{
public function testCheckReportsMissingPages()
{
$this->markTestSkipped('ExternalURLCheck seems faulty on some systems');
$check = new ExternalURLCheck('http://missing-site/');
$check = new ExternalURLCheck('http://missing-site/');
$expected = array(
EnvironmentCheck::ERROR,
'Success retrieving "http://missing-site/" (Code: 404)',
);
$expected = array(
EnvironmentCheck::ERROR,
'Success retrieving "http://missing-site/" (Code: 404)',
);
$this->assertEquals($expected, $check->check());
}
$this->assertEquals($expected, $check->check());
}
}

View File

@ -3,23 +3,26 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class FileWritableCheckTest extends SapphireTest {
public function testCheckReportsWritablePaths() {
$check = new FileWriteableCheck(TEMP_FOLDER);
class FileWritableCheckTest extends SapphireTest
{
public function testCheckReportsWritablePaths()
{
$check = new FileWriteableCheck(TEMP_FOLDER);
$expected = array(
EnvironmentCheck::OK,
'',
);
$expected = array(
EnvironmentCheck::OK,
'',
);
$this->assertEquals($expected, $check->check());
}
$this->assertEquals($expected, $check->check());
}
public function testCheckReportsNonWritablePaths() {
$check = new FileWriteableCheck('/var');
public function testCheckReportsNonWritablePaths()
{
$check = new FileWriteableCheck('/var');
$result = $check->check();
$result = $check->check();
$this->assertEquals(EnvironmentCheck::ERROR, $result[0]);
}
$this->assertEquals(EnvironmentCheck::ERROR, $result[0]);
}
}

View File

@ -3,26 +3,29 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class HasClassCheckTest extends SapphireTest {
public function testCheckReportsMissingClasses() {
$check = new HasClassCheck('foo');
class HasClassCheckTest extends SapphireTest
{
public function testCheckReportsMissingClasses()
{
$check = new HasClassCheck('foo');
$expected = array(
EnvironmentCheck::ERROR,
'Class foo doesn\'t exist',
);
$expected = array(
EnvironmentCheck::ERROR,
'Class foo doesn\'t exist',
);
$this->assertEquals($expected, $check->check());
}
$this->assertEquals($expected, $check->check());
}
public function testCheckReportsFoundClasses() {
$check = new HasClassCheck('stdClass');
public function testCheckReportsFoundClasses()
{
$check = new HasClassCheck('stdClass');
$expected = array(
EnvironmentCheck::OK,
'Class stdClass exists',
);
$expected = array(
EnvironmentCheck::OK,
'Class stdClass exists',
);
$this->assertEquals($expected, $check->check());
}
$this->assertEquals($expected, $check->check());
}
}

View File

@ -3,26 +3,29 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class HasFunctionCheckTest extends SapphireTest {
public function testCheckReportsMissingFunctions() {
$check = new HasFunctionCheck('foo');
class HasFunctionCheckTest extends SapphireTest
{
public function testCheckReportsMissingFunctions()
{
$check = new HasFunctionCheck('foo');
$expected = array(
EnvironmentCheck::ERROR,
'foo() doesn\'t exist',
);
$expected = array(
EnvironmentCheck::ERROR,
'foo() doesn\'t exist',
);
$this->assertEquals($expected, $check->check());
}
$this->assertEquals($expected, $check->check());
}
public function testCheckReportsFoundFunctions() {
$check = new HasFunctionCheck('class_exists');
public function testCheckReportsFoundFunctions()
{
$check = new HasFunctionCheck('class_exists');
$expected = array(
EnvironmentCheck::OK,
'class_exists() exists',
);
$expected = array(
EnvironmentCheck::OK,
'class_exists() exists',
);
$this->assertEquals($expected, $check->check());
}
$this->assertEquals($expected, $check->check());
}
}

View File

@ -3,15 +3,17 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class URLCheckTest extends SapphireTest {
public function testCheckReportsMissingPages() {
$check = new URLCheck('foo', 'bar');
class URLCheckTest extends SapphireTest
{
public function testCheckReportsMissingPages()
{
$check = new URLCheck('foo', 'bar');
$expected = array(
EnvironmentCheck::ERROR,
'Error retrieving "foo" (Code: 404)',
);
$expected = array(
EnvironmentCheck::ERROR,
'Error retrieving "foo" (Code: 404)',
);
$this->assertEquals($expected, $check->check());
}
$this->assertEquals($expected, $check->check());
}
}