Skip to content

Instantly share code, notes, and snippets.

@jyokyoku
Created October 8, 2011 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyokyoku/1271972 to your computer and use it in GitHub Desktop.
Save jyokyoku/1271972 to your computer and use it in GitHub Desktop.
CakePHP MaintenanceComponent
<?php
class MaintenanceComponent extends Object
{
public $components = array('RequestHandler');
public $level = 0;
public $allowedCIDR = array();
public $baseURL = null;
public $errorMethod = 'error404';
public $errorParams = array();
protected $_allowed = false;
protected $_redirect = false;
private $__debug = 0;
public function __construct()
{
$this->__debug = Configure::read('debug');
$debug = Configure::read('Maintenance.debug');
if (!is_int($debug)) {
$debug = 1;
}
Configure::write('debug', $debug);
parent::__construct();
}
public function initialize(Controller $Controller, $settings = array())
{
$isErrorOrTests = (
strtolower($Controller->name) == 'cakeerror' ||
(strtolower($Controller->name) == 'tests' && Configure::read() > 0)
);
$settings = array_merge((array)Configure::read('Maintenance'), $settings);
$this->_set($settings);
if ($isErrorOrTests || (int)$this->level == 0 || !$this->allowedCIDR) {
Configure::write('debug', $this->__debug);
$this->enabled = false;
return true;
}
$clientIP = $this->RequestHandler->getClientIP();
foreach ((array)$this->allowedCIDR as $CIDR) {
if ($this->_inCIDR($clientIP, $CIDR)) {
$this->_allowed = true;
break;
}
}
if (!$this->isAllowed()) {
Configure::write('debug', $this->__debug);
}
}
public function startup(Controller $Controller)
{
if (!$this->isAllowed() && $this->level >= 2) {
if ($this->baseURL) {
$baseURL = Router::normalize($this->baseURL);
if ($baseURL != Router::normalize($Controller->here)) {
$this->_redirect = true;
}
}
$this->cakeError($this->errorMethod, $this->errorParams);
}
}
public function isAllowed()
{
return $this->_allowed;
}
protected function _inCIDR($ipAddress, $CIDR) {
list($network, $maskBitLength) = explode('/', (string)$CIDR) + array('0.0.0.0', 32);
$host = 32 - (int)$maskBitLength;
$maxkedNetwork = ip2long($network) >> $host << $host;
$maskedIpAddress = ip2long($ipAddress) >> $host << $host;
return $maxkedNetwork === $maskedIpAddress;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment