Converted to PSR-2

This commit is contained in:
helpfulrobot 2015-11-21 19:18:35 +13:00
parent d6a65e1614
commit 5f1f1fcd53
24 changed files with 1429 additions and 1293 deletions

View File

@ -1,6 +1,7 @@
<?php
class DevCheckController extends Controller {
class DevCheckController extends Controller
{
/**
* @var array
*/
@ -22,7 +23,8 @@ class DevCheckController extends Controller {
*
* @throws SS_HTTPResponse_Exception
*/
function index($request) {
public function index($request)
{
$suite = 'check';
if ($name = $request->param('Suite')) {

View File

@ -1,6 +1,7 @@
<?php
class DevHealthController extends Controller {
class DevHealthController extends Controller
{
/**
* @var array
*/
@ -13,7 +14,8 @@ class DevHealthController extends Controller {
*
* @throws SS_HTTPResponse_Exception
*/
function index() {
public function index()
{
// health check does not require permission to run
$checker = new EnvironmentChecker('health', 'Site health');

View File

@ -14,7 +14,8 @@
* - Are the right PHP modules installed?
* - Are the file permissions correct?
*/
interface EnvironmentCheck {
interface EnvironmentCheck
{
/**
* @var int
*/
@ -35,5 +36,5 @@ interface EnvironmentCheck {
*
* Status is EnvironmentCheck::ERROR, EnvironmentCheck::WARNING, or EnvironmentCheck::OK.
*/
function check();
public function check();
}

View File

@ -19,7 +19,8 @@
*
* $result = EnvironmentCheckSuite::inst('health')->run();
*/
class EnvironmentCheckSuite extends Object {
class EnvironmentCheckSuite extends Object
{
/**
* Name of this suite.
*
@ -56,7 +57,8 @@ class EnvironmentCheckSuite extends Object {
*
* @param string $suiteName The name of this suite.
*/
public function __construct($suiteName) {
public function __construct($suiteName)
{
parent::__construct();
if (empty($this->config()->registered_suites[$suiteName])) {
@ -75,7 +77,9 @@ class EnvironmentCheckSuite extends Object {
// 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;
if (!empty($check['state']) && $check['state']==='disabled') {
continue;
}
// Add the check to this suite.
$this->push($check['definition'], $check['title']);
@ -87,15 +91,16 @@ class EnvironmentCheckSuite extends Object {
*
* @return int
*/
public function run() {
public function run()
{
$result = new EnvironmentCheckSuiteResult();
foreach($this->checkInstances() as $check) {
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) {
} catch (Exception $e) {
$status = EnvironmentCheck::ERROR;
$message = $e->getMessage();
}
@ -110,18 +115,19 @@ class EnvironmentCheckSuite extends Object {
*
* @return array
*/
protected function checkInstances() {
protected function checkInstances()
{
$output = array();
foreach($this->checks as $check) {
foreach ($this->checks as $check) {
list($checkClass, $checkTitle) = $check;
if(is_string($checkClass)) {
if (is_string($checkClass)) {
$checkInst = Object::create_from_string($checkClass);
if($checkInst instanceof EnvironmentCheck) {
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) {
} elseif ($checkClass instanceof EnvironmentCheck) {
$output[] = array($checkClass, $checkTitle);
} else {
throw new InvalidArgumentException("Bad EnvironmentCheck: " . var_export($check, true));
@ -136,8 +142,9 @@ class EnvironmentCheckSuite extends Object {
* @param mixed $check
* @param string $title
*/
public function push($check, $title = null) {
if(!$title) {
public function push($check, $title = null)
{
if (!$title) {
$title = is_string($check) ? $check : get_class($check);
}
$this->checks[] = array($check, $title);
@ -157,8 +164,11 @@ class EnvironmentCheckSuite extends Object {
*
* @return EnvironmentCheckSuite
*/
static function inst($name) {
if(!isset(self::$instances[$name])) self::$instances[$name] = new EnvironmentCheckSuite($name);
public static function inst($name)
{
if (!isset(self::$instances[$name])) {
self::$instances[$name] = new EnvironmentCheckSuite($name);
}
return self::$instances[$name];
}
@ -169,15 +179,21 @@ class EnvironmentCheckSuite extends Object {
* @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);
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() {
public static function reset()
{
self::$instances = array();
}
}
@ -185,7 +201,8 @@ class EnvironmentCheckSuite extends Object {
/**
* A single set of results from running an EnvironmentCheckSuite
*/
class EnvironmentCheckSuiteResult extends ViewableData {
class EnvironmentCheckSuiteResult extends ViewableData
{
/**
* @var ArrayList
*/
@ -196,7 +213,8 @@ class EnvironmentCheckSuiteResult extends ViewableData {
*/
protected $worst = 0;
function __construct() {
public function __construct()
{
parent::__construct();
$this->details = new ArrayList();
}
@ -206,7 +224,8 @@ class EnvironmentCheckSuiteResult extends ViewableData {
* @param string $message
* @param string $checkIdentifier
*/
function addResult($status, $message, $checkIdentifier) {
public function addResult($status, $message, $checkIdentifier)
{
$this->details->push(new ArrayData(array(
'Check' => $checkIdentifier,
'Status' => $this->statusText($status),
@ -222,7 +241,8 @@ class EnvironmentCheckSuiteResult extends ViewableData {
*
* @return bool
*/
public function ShouldPass() {
public function ShouldPass()
{
return $this->worst <= EnvironmentCheck::WARNING;
}
@ -231,7 +251,8 @@ class EnvironmentCheckSuiteResult extends ViewableData {
*
* @return string
*/
function Status() {
public function Status()
{
return $this->statusText($this->worst);
}
@ -240,7 +261,8 @@ class EnvironmentCheckSuiteResult extends ViewableData {
*
* @return ArrayList
*/
function Details() {
public function Details()
{
return $this->details;
}
@ -249,13 +271,14 @@ class EnvironmentCheckSuiteResult extends ViewableData {
*
* @return string
*/
function toJSON() {
public function toJSON()
{
$result = array(
'Status' => $this->Status(),
'ShouldPass' => $this->ShouldPass(),
'Checks' => array()
);
foreach($this->details as $detail) {
foreach ($this->details as $detail) {
$result['Checks'][] = $detail->toMap();
}
return json_encode($result);
@ -266,8 +289,9 @@ class EnvironmentCheckSuiteResult extends ViewableData {
*
* @return string
*/
protected function statusText($status) {
switch($status) {
protected function statusText($status)
{
switch ($status) {
case EnvironmentCheck::ERROR: return "ERROR";
case EnvironmentCheck::WARNING: return "WARNING";
case EnvironmentCheck::OK: return "OK";

View File

@ -3,7 +3,8 @@
/**
* Provides an interface for checking the given EnvironmentCheckSuite.
*/
class EnvironmentChecker extends RequestHandler {
class EnvironmentChecker extends RequestHandler
{
/**
* @var array
*/
@ -65,7 +66,8 @@ class EnvironmentChecker extends RequestHandler {
* @param string $checkSuiteName
* @param string $title
*/
function __construct($checkSuiteName, $title) {
public function __construct($checkSuiteName, $title)
{
parent::__construct();
$this->checkSuiteName = $checkSuiteName;
@ -77,12 +79,13 @@ class EnvironmentChecker extends RequestHandler {
*
* @throws SS_HTTPResponse_Exception
*/
function init($permission = 'ADMIN') {
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'])) {
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(
if (
!(
$_SERVER['PHP_AUTH_USER'] == ENVCHECK_BASICAUTH_USERNAME
&& $_SERVER['PHP_AUTH_PW'] == ENVCHECK_BASICAUTH_PASSWORD
@ -104,7 +107,9 @@ class EnvironmentChecker extends RequestHandler {
throw $e;
}
} else {
if(!$this->canAccess(null, $permission)) return $this->httpError(403);
if (!$this->canAccess(null, $permission)) {
return $this->httpError(403);
}
}
}
@ -116,18 +121,19 @@ class EnvironmentChecker extends RequestHandler {
*
* @throws SS_HTTPResponse_Exception
*/
function canAccess($member = null, $permission = "ADMIN") {
if(!$member) {
public function canAccess($member = null, $permission = "ADMIN")
{
if (!$member) {
$member = Member::currentUser();
}
if(!$member) {
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(
if (
Director::isDev()
|| Director::is_cli()
|| empty($permission)
@ -140,9 +146,12 @@ class EnvironmentChecker extends RequestHandler {
// "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;
if ($results && is_array($results)) {
if (!min($results)) {
return false;
} else {
return true;
}
}
return false;
@ -151,11 +160,12 @@ class EnvironmentChecker extends RequestHandler {
/**
* @return SS_HTTPResponse
*/
function index() {
public function index()
{
$response = new SS_HTTPResponse;
$result = EnvironmentCheckSuite::inst($this->checkSuiteName)->run();
if(!$result->ShouldPass()) {
if (!$result->ShouldPass()) {
$response->setStatusCode($this->errorCode);
}
@ -172,13 +182,13 @@ class EnvironmentChecker extends RequestHandler {
}
// Optionally log errors and warnings individually
foreach($result->Details() as $detail) {
if($this->config()->log_results_warning && $detail->StatusCode == EnvironmentCheck::WARNING) {
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) {
} 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
@ -187,7 +197,7 @@ class EnvironmentChecker extends RequestHandler {
}
// output the result as JSON if requested
if(
if (
$this->getRequest()->getExtension() == 'json'
|| strpos($this->getRequest()->getHeader('Accept'), 'application/json') !== false
) {
@ -205,7 +215,8 @@ class EnvironmentChecker extends RequestHandler {
* @param string $message
* @param int $level
*/
public function log($message, $level) {
public function log($message, $level)
{
SS_Log::log($message, $level);
}
@ -214,7 +225,8 @@ class EnvironmentChecker extends RequestHandler {
*
* @param int $errorCode
*/
function setErrorCode($errorCode) {
public function setErrorCode($errorCode)
{
$this->errorCode = $errorCode;
}
@ -222,7 +234,8 @@ class EnvironmentChecker extends RequestHandler {
* @deprecated
* @param string $from
*/
public static function set_from_email_address($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);
}
@ -231,7 +244,8 @@ class EnvironmentChecker extends RequestHandler {
* @deprecated
* @return null|string
*/
public static function get_from_email_address() {
public static function get_from_email_address()
{
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'from_email_address');
}
@ -240,7 +254,8 @@ class EnvironmentChecker extends RequestHandler {
* @deprecated
* @param string $to
*/
public static function set_to_email_address($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);
}
@ -249,7 +264,8 @@ class EnvironmentChecker extends RequestHandler {
* @deprecated
* @return null|string
*/
public static function get_to_email_address() {
public static function get_to_email_address()
{
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'to_email_address');
}
@ -258,7 +274,8 @@ class EnvironmentChecker extends RequestHandler {
* @deprecated
* @param bool $results
*/
public static function set_email_results($results) {
public static function set_email_results($results)
{
Deprecation::notice('2.0', 'Use config API instead');
Config::inst()->update('EnvironmentChecker', 'email_results', $results);
}
@ -267,7 +284,8 @@ class EnvironmentChecker extends RequestHandler {
* @deprecated
* @return bool
*/
public static function get_email_results() {
public static function get_email_results()
{
Deprecation::notice('2.0', 'Use config API instead');
return Config::inst()->get('EnvironmentChecker', 'email_results');
}

View File

@ -4,7 +4,8 @@
* 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 {
class DatabaseCheck implements EnvironmentCheck
{
protected $checkTable;
/**
@ -12,7 +13,8 @@ class DatabaseCheck implements EnvironmentCheck {
*
* @param string $checkTable
*/
function __construct($checkTable = "Member") {
public function __construct($checkTable = "Member")
{
$this->checkTable = $checkTable;
}
@ -21,14 +23,15 @@ class DatabaseCheck implements EnvironmentCheck {
*
* @return array
*/
function check() {
if(!DB::getConn()->hasTable($this->checkTable)) {
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) {
if ($count > 0) {
return array(EnvironmentCheck::OK, "");
} else {
return array(EnvironmentCheck::WARNING, "$this->checkTable queried ok but has no records");

View File

@ -8,7 +8,8 @@
* 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 {
class ExternalURLCheck implements EnvironmentCheck
{
/**
* @var array
*/
@ -23,8 +24,11 @@ class ExternalURLCheck implements EnvironmentCheck {
* @param string $urls Space-separated list of absolute URLs.
* @param int $timeout
*/
function __construct($urls, $timeout = 15) {
if($urls) $this->urls = explode(' ', $urls);
public function __construct($urls, $timeout = 15)
{
if ($urls) {
$this->urls = explode(' ', $urls);
}
$this->timeout = $timeout;
}
@ -33,18 +37,21 @@ class ExternalURLCheck implements EnvironmentCheck {
*
* @return array
*/
function check() {
public function check()
{
$urls = $this->getURLs();
$chs = array();
foreach($urls as $url) {
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);
foreach ($chs as $ch) {
curl_multi_add_handle($mh, $ch);
}
$active = null;
// Execute the handles
@ -63,10 +70,10 @@ class ExternalURLCheck implements EnvironmentCheck {
$hasError = false;
$msgs = array();
foreach($chs as $ch) {
foreach ($chs as $ch) {
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch) || $code >= 400) {
if (curl_errno($ch) || $code >= 400) {
$hasError = true;
$msgs[] = sprintf(
'Error retrieving "%s": %s (Code: %s)',
@ -84,10 +91,12 @@ class ExternalURLCheck implements EnvironmentCheck {
}
// Close the handles
foreach($chs as $ch) curl_multi_remove_handle($mh, $ch);
foreach ($chs as $ch) {
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
if($hasError) {
if ($hasError) {
return array(EnvironmentCheck::ERROR, implode(', ', $msgs));
} else {
return array(EnvironmentCheck::OK, implode(', ', $msgs));
@ -97,7 +106,8 @@ class ExternalURLCheck implements EnvironmentCheck {
/**
* @return array
*/
protected function getCurlOpts($url) {
protected function getCurlOpts($url)
{
return array(
CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
@ -110,7 +120,8 @@ class ExternalURLCheck implements EnvironmentCheck {
/**
* @return array
*/
protected function getURLs() {
protected function getURLs()
{
return $this->urls;
}
}

View File

@ -19,7 +19,8 @@
* 'Check a calculator.json exists only'
* );
*/
class FileAccessibilityAndValidationCheck implements EnvironmentCheck {
class FileAccessibilityAndValidationCheck implements EnvironmentCheck
{
/**
* @var int
*/
@ -56,7 +57,8 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck {
* @param string $fileTypeValidateFunc
* @param null|int $checkType
*/
function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null) {
public function __construct($path, $fileTypeValidateFunc = 'noVidation', $checkType = null)
{
$this->path = $path;
$this->fileTypeValidateFunc = ($fileTypeValidateFunc)? $fileTypeValidateFunc:'noVidation';
$this->checkType = ($checkType) ? $checkType : self::CHECK_SINGLE;
@ -67,72 +69,72 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck {
*
* @return array
*/
function check() {
public function check()
{
$origStage = Versioned::get_reading_mode();
Versioned::set_reading_mode('Live');
$files = $this->getFiles();
if($files){
if ($files) {
$fileTypeValidateFunc = $this->fileTypeValidateFunc;
if(method_exists ($this, $fileTypeValidateFunc)){
if (method_exists($this, $fileTypeValidateFunc)) {
$invalidFiles = array();
$validFiles = array();
foreach($files as $file){
if($this->$fileTypeValidateFunc($file)){
foreach ($files as $file) {
if ($this->$fileTypeValidateFunc($file)) {
$validFiles[] = $file;
}else{
} else {
$invalidFiles[] = $file;
}
}
// If at least one file was valid, count as passed
if($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
if ($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
$validFileList = "\n";
foreach($validFiles as $vf){
foreach ($validFiles as $vf) {
$validFileList .= $vf."\n";
}
if($fileTypeValidateFunc == 'noVidation') {
if ($fileTypeValidateFunc == 'noVidation') {
$checkReturn = array(
EnvironmentCheck::OK,
sprintf('At least these file(s) accessible: %s', $validFileList)
);
}else{
} 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 {
if (count($invalidFiles) == 0) {
$checkReturn = array(EnvironmentCheck::OK, 'All files valideted');
} else {
$invalidFileList = "\n";
foreach($invalidFiles as $vf){
foreach ($invalidFiles as $vf) {
$invalidFileList .= $vf."\n";
}
if($fileTypeValidateFunc == 'noVidation'){
if ($fileTypeValidateFunc == 'noVidation') {
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf('File(s) not accessible: %s', $invalidFileList)
);
}else{
} else {
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf('File(s) not passing the file type validate function "%s": %s', $fileTypeValidateFunc, $invalidFileList)
);
}
}
}
}else{
} else {
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf("Invalid file type validation method name passed: %s ", $fileTypeValidateFunc)
);
}
}else{
} else {
$checkReturn = array(
EnvironmentCheck::ERROR,
sprintf("No files accessible at path %s", $this->path)
@ -149,11 +151,12 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck {
*
* @return bool
*/
private function jsonValidate($file){
private function jsonValidate($file)
{
$json = json_decode(file_get_contents($file));
if(!$json) {
if (!$json) {
return false;
}else{
} else {
return true;
}
}
@ -163,7 +166,8 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck {
*
* @return bool
*/
protected function noVidation($file) {
protected function noVidation($file)
{
return true;
}
@ -172,7 +176,8 @@ class FileAccessibilityAndValidationCheck implements EnvironmentCheck {
*
* @return array
*/
protected function getFiles() {
protected function getFiles()
{
return glob($this->path);
}
}

View File

@ -19,7 +19,8 @@
* 'FileAgeCheck("' . BASE_PATH . '/../backups/*' . '", "-1 day", '>', " . FileAgeCheck::CHECK_SINGLE) . "'
* );
*/
class FileAgeCheck implements EnvironmentCheck {
class FileAgeCheck implements EnvironmentCheck
{
/**
* @var int
*/
@ -72,7 +73,8 @@ class FileAgeCheck implements EnvironmentCheck {
* @param null|int $checkType
* @param string $checkFn
*/
function __construct($path, $relativeAge, $compareOperand = '>', $checkType = null, $checkFn = 'filemtime') {
public function __construct($path, $relativeAge, $compareOperand = '>', $checkType = null, $checkFn = 'filemtime')
{
$this->path = $path;
$this->relativeAge = $relativeAge;
$this->checkFn = $checkFn;
@ -85,21 +87,23 @@ class FileAgeCheck implements EnvironmentCheck {
*
* @return array
*/
function check() {
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) {
if ($files) {
foreach ($files as $file) {
$fileTime = $checkFn($file);
$valid = ($this->compareOperand == '>') ? ($fileTime >= $cutoffTime) : ($fileTime <= $cutoffTime);
if($valid) {
if ($valid) {
$validFiles[] = $file;
} else {
$invalidFiles[] = $file;
if($this->checkType == self::CHECK_ALL) {
if ($this->checkType == self::CHECK_ALL) {
return array(
EnvironmentCheck::ERROR,
sprintf(
@ -110,18 +114,21 @@ class FileAgeCheck implements EnvironmentCheck {
}
}
}
}
// If at least one file was valid, count as passed
if($this->checkType == self::CHECK_SINGLE && count($invalidFiles) < count($files)) {
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(
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))
);
}
}
}
/**
@ -129,7 +136,8 @@ class FileAgeCheck implements EnvironmentCheck {
*
* @return array
*/
protected function getFiles() {
protected function getFiles()
{
return glob($this->path);
}
}

View File

@ -3,7 +3,8 @@
/**
* Check that the given file is writable.
*/
class FileWriteableCheck implements EnvironmentCheck {
class FileWriteableCheck implements EnvironmentCheck
{
/**
* @var string
*/
@ -12,7 +13,8 @@ class FileWriteableCheck implements EnvironmentCheck {
/**
* @param string $path The full path. If a relative path, it will relative to the BASE_PATH.
*/
function __construct($path) {
public function __construct($path)
{
$this->path = $path;
}
@ -21,41 +23,48 @@ class FileWriteableCheck implements EnvironmentCheck {
*
* @return array
*/
function check() {
if($this->path[0] == '/') $filename = $this->path;
else $filename = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $this->path);
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 (file_exists($filename)) {
$isWriteable = is_writeable($filename);
} else {
$isWriteable = is_writeable(dirname($filename));
}
if(!$isWriteable) {
if(function_exists('posix_getgroups')) {
if (!$isWriteable) {
if (function_exists('posix_getgroups')) {
$userID = posix_geteuid();
$user = posix_getpwuid($userID);
$currentOwnerID = fileowner(file_exists($filename) ? $filename : dirname($filename) );
$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]'. ";
if($user['name'] == $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) {
foreach ($groups as $group) {
$groupInfo = posix_getgrgid($group);
if(in_array($currentOwner['name'], $groupInfo['members'])) $groupList[] = $groupInfo['name'];
if (in_array($currentOwner['name'], $groupInfo['members'])) {
$groupList[] = $groupInfo['name'];
}
if($groupList) {
}
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";
}

View File

@ -3,7 +3,8 @@
/**
* Check that the given class exists.
*/
class HasClassCheck implements EnvironmentCheck {
class HasClassCheck implements EnvironmentCheck
{
/**
* @var string
*/
@ -12,7 +13,8 @@ class HasClassCheck implements EnvironmentCheck {
/**
* @param string $className The name of the class to look for.
*/
function __construct($className) {
public function __construct($className)
{
$this->className = $className;
}
@ -21,8 +23,12 @@ class HasClassCheck implements EnvironmentCheck {
*
* @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');
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,7 +3,8 @@
/**
* Check that the given function exists.
*/
class HasFunctionCheck implements EnvironmentCheck {
class HasFunctionCheck implements EnvironmentCheck
{
/**
* @var string
*/
@ -12,7 +13,8 @@ class HasFunctionCheck implements EnvironmentCheck {
/**
* @param string $functionName The name of the function to look for.
*/
function __construct($functionName) {
public function __construct($functionName)
{
$this->functionName = $functionName;
}
@ -21,8 +23,12 @@ class HasFunctionCheck implements EnvironmentCheck {
*
* @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');
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,7 +5,8 @@
*
* Only checks socket connection with HELO command, not actually sending the email.
*/
class SMTPConnectCheck implements EnvironmentCheck {
class SMTPConnectCheck implements EnvironmentCheck
{
/**
* @var string
*/
@ -28,12 +29,17 @@ class SMTPConnectCheck implements EnvironmentCheck {
* @param null|int $port
* @param int $timeout
*/
function __construct($host = null, $port = null, $timeout = 15) {
public function __construct($host = null, $port = null, $timeout = 15)
{
$this->host = ($host) ? $host : ini_get('SMTP');
if(!$this->host) $this->host = 'localhost';
if (!$this->host) {
$this->host = 'localhost';
}
$this->port = ($port) ? $port : ini_get('smtp_port');
if(!$this->port) $this->port = 25;
if (!$this->port) {
$this->port = 25;
}
$this->timeout = $timeout;
}
@ -43,9 +49,10 @@ class SMTPConnectCheck implements EnvironmentCheck {
*
* @return array
*/
function check() {
public function check()
{
$f = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
if(!$f) {
if (!$f) {
return array(
EnvironmentCheck::ERROR,
sprintf("Couldn't connect to SMTP on %s:%s (Error: %s %s)", $this->host, $this->port, $errno, $errstr)
@ -54,7 +61,7 @@ class SMTPConnectCheck implements EnvironmentCheck {
fwrite($f, "HELO its_me\r\n");
$response = fread($f, 26);
if(substr($response, 0, 3) != '220') {
if (substr($response, 0, 3) != '220') {
return array(
EnvironmentCheck::ERROR,
sprintf("Invalid mail server response: %s", $response)

View File

@ -5,7 +5,8 @@
*
* If there are no indexes of given class found, the returned status will still be "OK".
*/
class SolrIndexCheck implements EnvironmentCheck {
class SolrIndexCheck implements EnvironmentCheck
{
/**
* @var null|string
*/
@ -14,7 +15,8 @@ class SolrIndexCheck implements EnvironmentCheck {
/**
* @param string $indexClass Limit the index checks to the specified class and all its subclasses.
*/
function __construct($indexClass = null) {
public function __construct($indexClass = null)
{
$this->indexClass = $indexClass;
}
@ -23,7 +25,8 @@ class SolrIndexCheck implements EnvironmentCheck {
*
* @return array
*/
function check() {
public function check()
{
$brokenCores = array();
if (!class_exists('Solr')) {

View File

@ -5,7 +5,8 @@
*
* Note that Director::test() will be used rather than a CURL check.
*/
class URLCheck implements EnvironmentCheck {
class URLCheck implements EnvironmentCheck
{
/**
* @var string
*/
@ -20,7 +21,8 @@ class URLCheck implements EnvironmentCheck {
* @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 = '') {
public function __construct($url = '', $testString = '')
{
$this->url = $url;
$this->testString = $testString;
}
@ -32,21 +34,20 @@ class URLCheck implements EnvironmentCheck {
*
* @throws SS_HTTPResponse_Exception
*/
function check() {
public function check()
{
$response = Director::test($this->url);
if($response->getStatusCode() != 200) {
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)) {
} 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,

View File

@ -3,8 +3,10 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class DevCheckControllerTest extends SapphireTest {
public function testIndexCreatesChecker() {
class DevCheckControllerTest extends SapphireTest
{
public function testIndexCreatesChecker()
{
$controller = new DevCheckController();
$request = new SS_HTTPRequest('GET', 'example.com');

View File

@ -3,8 +3,10 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class DevHealthControllerTest extends SapphireTest {
public function testIndexCreatesChecker() {
class DevHealthControllerTest extends SapphireTest
{
public function testIndexCreatesChecker()
{
$controller = new DevHealthController();
$request = new SS_HTTPRequest('GET', 'example.com');

View File

@ -1,25 +1,29 @@
<?php
class EnvironmentCheckerTest extends SapphireTest {
public function setUpOnce() {
class EnvironmentCheckerTest extends SapphireTest
{
public function setUpOnce()
{
parent::setUpOnce();
Phockito::include_hamcrest();
}
public function setUp() {
public function setUp()
{
parent::setUp();
Config::nest();
}
public function tearDown() {
public function tearDown()
{
Config::unnest();
parent::tearDown();
}
public function testOnlyLogsWithErrors() {
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());
@ -34,7 +38,8 @@ class EnvironmentCheckerTest extends SapphireTest {
EnvironmentCheckSuite::reset();
}
public function testLogsWithWarnings() {
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());
@ -51,7 +56,8 @@ class EnvironmentCheckerTest extends SapphireTest {
EnvironmentCheckSuite::reset();
}
public function testLogsWithErrors() {
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());
@ -67,23 +73,28 @@ class EnvironmentCheckerTest extends SapphireTest {
Phockito::verify($checker, 1)->log(containsString('error'), anything());
EnvironmentCheckSuite::reset();
}
}
class EnvironmentCheckerTest_CheckNoErrors implements EnvironmentCheck, TestOnly{
public function check() {
class EnvironmentCheckerTest_CheckNoErrors implements EnvironmentCheck, TestOnly
{
public function check()
{
return array(EnvironmentCheck::OK, '');
}
}
class EnvironmentCheckerTest_CheckWarnings implements EnvironmentCheck, TestOnly{
public function check() {
class EnvironmentCheckerTest_CheckWarnings implements EnvironmentCheck, TestOnly
{
public function check()
{
return array(EnvironmentCheck::WARNING, "test warning");
}
}
class EnvironmentCheckerTest_CheckErrors implements EnvironmentCheck, TestOnly{
public function check() {
class EnvironmentCheckerTest_CheckErrors implements EnvironmentCheck, TestOnly
{
public function check()
{
return array(EnvironmentCheck::ERROR, "test error");
}
}

View File

@ -3,8 +3,10 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class DatabaseCheckTest extends SapphireTest {
public function testCheckReportsValidConnection() {
class DatabaseCheckTest extends SapphireTest
{
public function testCheckReportsValidConnection()
{
$check = new DatabaseCheck();
$expected = array(

View File

@ -3,8 +3,10 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class ExternalURLCheckTest extends SapphireTest {
public function testCheckReportsMissingPages() {
class ExternalURLCheckTest extends SapphireTest
{
public function testCheckReportsMissingPages()
{
$this->markTestSkipped('ExternalURLCheck seems faulty on some systems');
$check = new ExternalURLCheck('http://missing-site/');

View File

@ -3,8 +3,10 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class FileWritableCheckTest extends SapphireTest {
public function testCheckReportsWritablePaths() {
class FileWritableCheckTest extends SapphireTest
{
public function testCheckReportsWritablePaths()
{
$check = new FileWriteableCheck(TEMP_FOLDER);
$expected = array(
@ -15,7 +17,8 @@ class FileWritableCheckTest extends SapphireTest {
$this->assertEquals($expected, $check->check());
}
public function testCheckReportsNonWritablePaths() {
public function testCheckReportsNonWritablePaths()
{
$check = new FileWriteableCheck('/var');
$result = $check->check();

View File

@ -3,8 +3,10 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class HasClassCheckTest extends SapphireTest {
public function testCheckReportsMissingClasses() {
class HasClassCheckTest extends SapphireTest
{
public function testCheckReportsMissingClasses()
{
$check = new HasClassCheck('foo');
$expected = array(
@ -15,7 +17,8 @@ class HasClassCheckTest extends SapphireTest {
$this->assertEquals($expected, $check->check());
}
public function testCheckReportsFoundClasses() {
public function testCheckReportsFoundClasses()
{
$check = new HasClassCheck('stdClass');
$expected = array(

View File

@ -3,8 +3,10 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class HasFunctionCheckTest extends SapphireTest {
public function testCheckReportsMissingFunctions() {
class HasFunctionCheckTest extends SapphireTest
{
public function testCheckReportsMissingFunctions()
{
$check = new HasFunctionCheck('foo');
$expected = array(
@ -15,7 +17,8 @@ class HasFunctionCheckTest extends SapphireTest {
$this->assertEquals($expected, $check->check());
}
public function testCheckReportsFoundFunctions() {
public function testCheckReportsFoundFunctions()
{
$check = new HasFunctionCheck('class_exists');
$expected = array(

View File

@ -3,8 +3,10 @@
/**
* @mixin PHPUnit_Framework_TestCase
*/
class URLCheckTest extends SapphireTest {
public function testCheckReportsMissingPages() {
class URLCheckTest extends SapphireTest
{
public function testCheckReportsMissingPages()
{
$check = new URLCheck('foo', 'bar');
$expected = array(