Fix PSR compliance

Alter files to follow PSR standards.

refs #4246
This commit is contained in:
Marius Hein 2013-06-07 13:29:11 +02:00
parent 172c699c47
commit e05ca449ae
28 changed files with 1924 additions and 573 deletions

View File

@ -1,4 +1,6 @@
<?php <?php
// @codingStandardsIgnoreStart
// {{{ICINGA_LICENSE_HEADER}}} // {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}} // {{{ICINGA_LICENSE_HEADER}}}
@ -91,3 +93,4 @@ class Zend_View_Helper_Qlink extends Zend_View_Helper_Abstract
return is_null($baseUrl) ? $this->view->baseUrl($url) : $baseUrl . $url; return is_null($baseUrl) ? $this->view->baseUrl($url) : $baseUrl . $url;
} }
} }
// @codingStandardsIgnoreEnd

View File

@ -1,9 +1,13 @@
#!/usr/bin/php #!/usr/bin/php
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
require_once dirname(__FILE__) . '/../library/Icinga/Application/Cli.php'; require_once dirname(__FILE__) . '/../library/Icinga/Application/Cli.php';
use Icinga\Application\Cli,
Icinga\Application\TranslationHelper; use Icinga\Application\Cli;
use Icinga\Application\TranslationHelper;
$bootstrap = Cli::start(); $bootstrap = Cli::start();
if (count($argv) < 2) { if (count($argv) < 2) {

View File

@ -1,15 +1,19 @@
#!/usr/bin/php #!/usr/bin/php
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
set_include_path( set_include_path(
realpath(dirname(__FILE__) . '/../library/') realpath(dirname(__FILE__) . '/../library/')
. ':' . get_include_path() . ':'
. get_include_path()
); );
require_once 'Icinga/Application/Cli.php'; require_once 'Icinga/Application/Cli.php';
use Icinga\Application\Cli,
Icinga\Util\Format; use Icinga\Application\Cli;
use Icinga\Util\Format;
$app = Cli::start(); $app = Cli::start();
echo Format::bytes(10930423) . "\n"; echo Format::bytes(10930423) . "\n";

View File

@ -1,50 +1,105 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol; namespace Icinga\Protocol;
/**
* Class AbstractQuery
* @package Icinga\Protocol
*/
abstract class AbstractQuery abstract class AbstractQuery
{ {
const SORT_ASC = 1; /**
*
*/
const SORT_ASC = 1;
/**
*
*/
const SORT_DESC = -1; const SORT_DESC = -1;
/**
* @param $key
* @param null $val
* @return mixed
*/
abstract public function where($key, $val = null); abstract public function where($key, $val = null);
/**
* @param $col
* @return mixed
*/
abstract public function order($col); abstract public function order($col);
/**
* @param null $count
* @param null $offset
* @return mixed
*/
abstract public function limit($count = null, $offset = null); abstract public function limit($count = null, $offset = null);
/**
* @param $table
* @param null $columns
* @return mixed
*/
abstract public function from($table, $columns = null); abstract public function from($table, $columns = null);
public function hasOrder() /**
* @return bool
*/
public function hasOrder()
{ {
return false; return false;
} }
public function hasColumns() /**
* @return bool
*/
public function hasColumns()
{ {
return false; return false;
} }
public function getColumns() /**
* @return array
*/
public function getColumns()
{ {
return array(); return array();
} }
public function hasLimit() /**
* @return bool
*/
public function hasLimit()
{ {
return false; return false;
} }
public function hasOffset() /**
* @return bool
*/
public function hasOffset()
{ {
return false; return false;
} }
/**
* @return null
*/
public function getLimit() public function getLimit()
{ {
return null; return null;
} }
/**
* @return null
*/
public function getOffset() public function getOffset()
{ {
return null; return null;
} }
} }

View File

@ -12,19 +12,59 @@ use Icinga\Application\Logger as IcingaLogger;
*/ */
class CommandPipe class CommandPipe
{ {
/**
* @var mixed
*/
private $path; private $path;
/**
* @var mixed
*/
private $name; private $name;
/**
* @var bool|mixed
*/
private $user = false; private $user = false;
/**
* @var bool|mixed
*/
private $host = false; private $host = false;
/**
* @var int|mixed
*/
private $port = 22; private $port = 22;
/**
* @var string
*/
public $fopen_mode = "w"; public $fopen_mode = "w";
/**
*
*/
const TYPE_HOST = "HOST"; const TYPE_HOST = "HOST";
/**
*
*/
const TYPE_SERVICE = "SVC"; const TYPE_SERVICE = "SVC";
/**
*
*/
const TYPE_HOSTGROUP = "HOSTGROUP"; const TYPE_HOSTGROUP = "HOSTGROUP";
/**
*
*/
const TYPE_SERVICEGROUP = "SERVICEGROUP"; const TYPE_SERVICEGROUP = "SERVICEGROUP";
/**
* @param \Zend_Config $config
*/
public function __construct(\Zend_Config $config) public function __construct(\Zend_Config $config)
{ {
$this->path = $config->path; $this->path = $config->path;
@ -40,6 +80,10 @@ class CommandPipe
} }
} }
/**
* @param $command
* @throws \RuntimeException
*/
public function send($command) public function send($command)
{ {
if (!$this->host) { if (!$this->host) {
@ -94,6 +138,10 @@ class CommandPipe
} }
} }
/**
* @param $objects
* @param IComment $acknowledgementOrComment
*/
public function acknowledge($objects, IComment $acknowledgementOrComment) public function acknowledge($objects, IComment $acknowledgementOrComment)
{ {
if (is_a($acknowledgementOrComment, 'Icinga\Protocol\Commandpipe\Comment')) { if (is_a($acknowledgementOrComment, 'Icinga\Protocol\Commandpipe\Comment')) {
@ -111,6 +159,9 @@ class CommandPipe
} }
} }
/**
* @param $objects
*/
public function removeAcknowledge($objects) public function removeAcknowledge($objects)
{ {
foreach ($objects as $object) { foreach ($objects as $object) {
@ -122,6 +173,11 @@ class CommandPipe
} }
} }
/**
* @param $objects
* @param $state
* @param $output
*/
public function submitCheckResult($objects, $state, $output) public function submitCheckResult($objects, $state, $output)
{ {
foreach ($objects as $object) { foreach ($objects as $object) {
@ -133,6 +189,11 @@ class CommandPipe
} }
} }
/**
* @param $objects
* @param bool $time
* @param bool $withChilds
*/
public function scheduleForcedCheck($objects, $time = false, $withChilds = false) public function scheduleForcedCheck($objects, $time = false, $withChilds = false)
{ {
if (!$time) { if (!$time) {
@ -148,6 +209,11 @@ class CommandPipe
} }
} }
/**
* @param $objects
* @param bool $time
* @param bool $withChilds
*/
public function scheduleCheck($objects, $time = false, $withChilds = false) public function scheduleCheck($objects, $time = false, $withChilds = false)
{ {
if (!$time) { if (!$time) {
@ -163,6 +229,10 @@ class CommandPipe
} }
} }
/**
* @param array $objects
* @param Comment $comment
*/
public function addComment(array $objects, Comment $comment) public function addComment(array $objects, Comment $comment)
{ {
foreach ($objects as $object) { foreach ($objects as $object) {
@ -177,6 +247,9 @@ class CommandPipe
} }
/**
* @param $objectsOrComments
*/
public function removeComment($objectsOrComments) public function removeComment($objectsOrComments)
{ {
foreach ($objectsOrComments as $object) { foreach ($objectsOrComments as $object) {
@ -202,16 +275,26 @@ class CommandPipe
} }
} }
/**
*
*/
public function enableGlobalNotifications() public function enableGlobalNotifications()
{ {
$this->send("ENABLE_NOTIFICATIONS"); $this->send("ENABLE_NOTIFICATIONS");
} }
/**
*
*/
public function disableGlobalNotifications() public function disableGlobalNotifications()
{ {
$this->send("DISABLE_NOTIFICATIONS"); $this->send("DISABLE_NOTIFICATIONS");
} }
/**
* @param $object
* @return string
*/
private function getObjectType($object) private function getObjectType($object)
{ {
//@TODO: This must be refactored once more commands are supported //@TODO: This must be refactored once more commands are supported
@ -221,6 +304,10 @@ class CommandPipe
return self::TYPE_HOST; return self::TYPE_HOST;
} }
/**
* @param $objects
* @param Downtime $downtime
*/
public function scheduleDowntime($objects, Downtime $downtime) public function scheduleDowntime($objects, Downtime $downtime)
{ {
foreach ($objects as $object) { foreach ($objects as $object) {
@ -235,6 +322,10 @@ class CommandPipe
} }
} }
/**
* @param $objects
* @param int $starttime
*/
public function removeDowntime($objects, $starttime = 0) public function removeDowntime($objects, $starttime = 0)
{ {
foreach ($objects as $object) { foreach ($objects as $object) {
@ -254,11 +345,18 @@ class CommandPipe
} }
} }
/**
*
*/
public function restartIcinga() public function restartIcinga()
{ {
$this->send("RESTART_PROCESS"); $this->send("RESTART_PROCESS");
} }
/**
* @param $objects
* @param PropertyModifier $flags
*/
public function setMonitoringProperties($objects, PropertyModifier $flags) public function setMonitoringProperties($objects, PropertyModifier $flags)
{ {
foreach ($objects as $object) { foreach ($objects as $object) {
@ -273,6 +371,9 @@ class CommandPipe
} }
} }
/**
* @param $objects
*/
public function enableActiveChecks($objects) public function enableActiveChecks($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -285,6 +386,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function disableActiveChecks($objects) public function disableActiveChecks($objects)
{ {
$this->modifyMonitoringProperties( $this->modifyMonitoringProperties(
@ -297,6 +401,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function enablePassiveChecks($objects) public function enablePassiveChecks($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -309,6 +416,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function disablePassiveChecks($objects) public function disablePassiveChecks($objects)
{ {
$this->modifyMonitoringProperties( $this->modifyMonitoringProperties(
@ -321,6 +431,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function enableFlappingDetection($objects) public function enableFlappingDetection($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -333,6 +446,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function disableFlappingDetection($objects) public function disableFlappingDetection($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -345,6 +461,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function enableNotifications($objects) public function enableNotifications($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -357,6 +476,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function disableNotifications($objects) public function disableNotifications($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -369,6 +491,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function enableFreshnessChecks($objects) public function enableFreshnessChecks($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -381,6 +506,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function disableFreshnessChecks($objects) public function disableFreshnessChecks($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -393,6 +521,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function enableEventHandler($objects) public function enableEventHandler($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -405,6 +536,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function disableEventHandler($objects) public function disableEventHandler($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(
@ -417,6 +551,9 @@ class CommandPipe
); );
} }
/**
* @param $objects
*/
public function enablePerfdata($objects) public function enablePerfdata($objects)
{ {
$this->setMonitoringProperties( $this->setMonitoringProperties(

View File

@ -1,37 +1,63 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Commandpipe; namespace Icinga\Protocol\Commandpipe;
/**
* Class Comment
* @package Icinga\Protocol\Commandpipe
*/
class Comment implements IComment class Comment implements IComment
{ {
/**
* @var bool
*/
public $persistent = false; public $persistent = false;
/**
* @var string
*/
public $author = ""; public $author = "";
/**
* @var string
*/
public $comment = ""; public $comment = "";
public function __construct($author,$comment,$persistent=false) /**
* @param $author
* @param $comment
* @param bool $persistent
*/
public function __construct($author, $comment, $persistent = false)
{ {
$this->author = $author; $this->author = $author;
$this->comment = $comment; $this->comment = $comment;
$this->persistent = $persistent; $this->persistent = $persistent;
} }
public function getFormatString($type) { /**
$params = ';'.($this->persistent ? '1' : '0').';'.$this->author.';'.$this->comment; * @param $type
* @return string
* @throws InvalidCommandException
*/
public function getFormatString($type)
{
$params = ';' . ($this->persistent ? '1' : '0') . ';' . $this->author . ';' . $this->comment;
switch($type) { switch ($type) {
case CommandPipe::TYPE_HOST: case CommandPipe::TYPE_HOST:
$typeVar = "HOST"; $typeVar = "HOST";
$params = ";%s".$params; $params = ";%s" . $params;
break; break;
case CommandPipe::TYPE_SERVICE: case CommandPipe::TYPE_SERVICE:
$typeVar = "SVC"; $typeVar = "SVC";
$params = ";%s;%s".$params; $params = ";%s;%s" . $params;
break; break;
default: default:
throw new InvalidCommandException("Acknowledgements can only apply on hosts and services "); throw new InvalidCommandException("Acknowledgements can only apply on hosts and services ");
} }
return "ADD_{$typeVar}_COMMENT$params"; return "ADD_{$typeVar}_COMMENT$params";
} }
}
}

View File

@ -1,29 +1,67 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Commandpipe; namespace Icinga\Protocol\Commandpipe;
/**
* Class Downtime
* @package Icinga\Protocol\Commandpipe
*/
class Downtime class Downtime
{ {
/**
* @var mixed
*/
public $startTime; public $startTime;
/**
* @var mixed
*/
public $endTime; public $endTime;
/**
* @var mixed
*/
private $fixed = false; private $fixed = false;
/**
* @var mixed
*/
public $duration; public $duration;
/**
* @var mixed
*/
public $comment; public $comment;
public function __construct($start,$end,Comment $comment,$duration=0) /**
* @param $start
* @param $end
* @param Comment $comment
* @param int $duration
*/
public function __construct($start, $end, Comment $comment, $duration = 0)
{ {
$this->startTime = $start; $this->startTime = $start;
$this->endTime = $end; $this->endTime = $end;
$this->comment = $comment; $this->comment = $comment;
if($duration != 0) if ($duration != 0) {
$this->fixed = true; $this->fixed = true;
}
$this->duration = intval($duration); $this->duration = intval($duration);
} }
public function getFormatString($type) { /**
return 'SCHEDULE_'.$type.'_DOWNTIME;%s' * @param $type
.($type == CommandPipe::TYPE_SERVICE ? ';%s;' : ';') * @return string
.$this->startTime.';'.$this->endTime */
.';'.($this->fixed ? '1' : '0').';'.$this->duration.';0;' public function getFormatString($type)
.$this->comment->author.';'.$this->comment->comment; {
return 'SCHEDULE_' . $type . '_DOWNTIME;%s'
. ($type == CommandPipe::TYPE_SERVICE ? ';%s;' : ';')
. $this->startTime . ';' . $this->endTime
. ';' . ($this->fixed ? '1' : '0') . ';' . $this->duration . ';0;'
. $this->comment->author . ';' . $this->comment->comment;
} }
} }

View File

@ -1,7 +1,13 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Commandpipe; namespace Icinga\Protocol\Commandpipe;
/**
* Class IComment
* @package Icinga\Protocol\Commandpipe
*/
interface IComment interface IComment
{ {
} }

View File

@ -1,52 +1,104 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Commandpipe; namespace Icinga\Protocol\Commandpipe;
class PropertyModifier { /**
* Class PropertyModifier
* @package Icinga\Protocol\Commandpipe
*/
class PropertyModifier
{
/**
*
*/
const STATE_ENABLE = 1; const STATE_ENABLE = 1;
/**
*
*/
const STATE_DISABLE = 0; const STATE_DISABLE = 0;
/**
*
*/
const STATE_KEEP = -1; const STATE_KEEP = -1;
/**
*
*/
const FLAPPING = "%s_FLAP_DETECTION"; const FLAPPING = "%s_FLAP_DETECTION";
/**
*
*/
const ACTIVE = "%s_CHECK"; const ACTIVE = "%s_CHECK";
/**
*
*/
const PASSIVE = "PASSIVE_%s_CHECKS"; const PASSIVE = "PASSIVE_%s_CHECKS";
/**
*
*/
const NOTIFICATIONS = "%s_NOTIFICATIONS"; const NOTIFICATIONS = "%s_NOTIFICATIONS";
/**
*
*/
const FRESHNESS = "%s_FRESHNESS_CHECKS"; const FRESHNESS = "%s_FRESHNESS_CHECKS";
/**
*
*/
const EVENTHANDLER = "%s_EVENT_HANDLER"; const EVENTHANDLER = "%s_EVENT_HANDLER";
/**
* @var array
*/
public $flags = array( public $flags = array(
self::FLAPPING => self::STATE_KEEP, self::FLAPPING => self::STATE_KEEP,
self::ACTIVE => self::STATE_KEEP, self::ACTIVE => self::STATE_KEEP,
self::PASSIVE => self::STATE_KEEP, self::PASSIVE => self::STATE_KEEP,
self::NOTIFICATIONS => self::STATE_KEEP, self::NOTIFICATIONS => self::STATE_KEEP,
self::FRESHNESS => self::STATE_KEEP, self::FRESHNESS => self::STATE_KEEP,
self::EVENTHANDLER => self::STATE_KEEP self::EVENTHANDLER => self::STATE_KEEP
); );
/**
* @param array $flags
*/
public function __construct(array $flags) public function __construct(array $flags)
{ {
foreach ($flags as $type=>$value) { foreach ($flags as $type => $value) {
if (isset($this->flags[$type])) { if (isset($this->flags[$type])) {
$this->flags[$type] = $value; $this->flags[$type] = $value;
} }
} }
} }
public function getFormatString($type) { /**
* @param $type
* @return array
*/
public function getFormatString($type)
{
$cmd = array(); $cmd = array();
foreach($this->flags as $cmdTemplate=>$setting) { foreach ($this->flags as $cmdTemplate => $setting) {
if($setting == self::STATE_KEEP) if ($setting == self::STATE_KEEP) {
continue; continue;
}
$commandString = ($setting == self::STATE_ENABLE ? "ENABLE_" : "DISABLE_"); $commandString = ($setting == self::STATE_ENABLE ? "ENABLE_" : "DISABLE_");
$targetString = $type; $targetString = $type;
if($type == CommandPipe::TYPE_SERVICE && $cmdTemplate == self::FRESHNESS) { if ($type == CommandPipe::TYPE_SERVICE && $cmdTemplate == self::FRESHNESS) {
// the external command definition is inconsistent here.. // the external command definition is inconsistent here..
$targetString = "SERVICE"; $targetString = "SERVICE";
} }
$commandString .= sprintf($cmdTemplate,$targetString); $commandString .= sprintf($cmdTemplate, $targetString);
$cmd[] = $commandString; $cmd[] = $commandString;
} }
return $cmd; return $cmd;
} }
} }

View File

@ -1,15 +1,13 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Ldap; namespace Icinga\Protocol\Ldap;
use Icinga\Application\Platform; use Icinga\Application\Platform;
use Icinga\Application\Config; use Icinga\Application\Config;
use Icinga\Application\Logger as Log; use Icinga\Application\Logger as Log;
/**
* Connection class
*
* @package Icinga\Protocol\Ldap
*/
/** /**
* Backend class managing all the LDAP stuff for you. * Backend class managing all the LDAP stuff for you.
* *
@ -31,12 +29,39 @@ use Icinga\Application\Logger as Log;
*/ */
class Connection class Connection
{ {
/**
* @var string
*/
protected $ds; protected $ds;
/**
* @var string
*/
protected $hostname; protected $hostname;
/**
* @var string
*/
protected $bind_dn; protected $bind_dn;
/**
* @var string
*/
protected $bind_pw; protected $bind_pw;
/**
* @var string
*/
protected $root_dn; protected $root_dn;
/**
* @var string
*/
protected $count; protected $count;
/**
* @var array
*/
protected $ldap_extension = array( protected $ldap_extension = array(
'1.3.6.1.4.1.1466.20037' => 'STARTTLS', // notes? '1.3.6.1.4.1.1466.20037' => 'STARTTLS', // notes?
// '1.3.6.1.4.1.4203.1.11.1' => '11.1', // PASSWORD_MODIFY // '1.3.6.1.4.1.4203.1.11.1' => '11.1', // PASSWORD_MODIFY
@ -44,40 +69,38 @@ class Connection
// '1.3.6.1.1.8' => '8', // Cancel Extended Request // '1.3.6.1.1.8' => '8', // Cancel Extended Request
); );
/**
* @var array
*/
protected $ms_capability = array( protected $ms_capability = array(
// Prefix LDAP_CAP_ // Prefix LDAP_CAP_
// Source: http://msdn.microsoft.com/en-us/library/cc223359.aspx // Source: http://msdn.microsoft.com/en-us/library/cc223359.aspx
// Running Active Directory as AD DS: // Running Active Directory as AD DS:
'1.2.840.113556.1.4.800' => 'ACTIVE_DIRECTORY_OID', '1.2.840.113556.1.4.800' => 'ACTIVE_DIRECTORY_OID',
// Capable of signing and sealing on an NTLM authenticated connection // Capable of signing and sealing on an NTLM authenticated connection
// and of performing subsequent binds on a signed or sealed connection. // and of performing subsequent binds on a signed or sealed connection.
'1.2.840.113556.1.4.1791' => 'ACTIVE_DIRECTORY_LDAP_INTEG_OID', '1.2.840.113556.1.4.1791' => 'ACTIVE_DIRECTORY_LDAP_INTEG_OID',
// If AD DS: running at least W2K3, if AD LDS running at least W2K8 // If AD DS: running at least W2K3, if AD LDS running at least W2K8
'1.2.840.113556.1.4.1670' => 'ACTIVE_DIRECTORY_V51_OID', '1.2.840.113556.1.4.1670' => 'ACTIVE_DIRECTORY_V51_OID',
// If AD LDS: accepts DIGEST-MD5 binds for AD LDSsecurity principals // If AD LDS: accepts DIGEST-MD5 binds for AD LDSsecurity principals
'1.2.840.113556.1.4.1880' => 'ACTIVE_DIRECTORY_ADAM_DIGEST', '1.2.840.113556.1.4.1880' => 'ACTIVE_DIRECTORY_ADAM_DIGEST',
// Running Active Directory as AD LDS // Running Active Directory as AD LDS
'1.2.840.113556.1.4.1851' => 'ACTIVE_DIRECTORY_ADAM_OID', '1.2.840.113556.1.4.1851' => 'ACTIVE_DIRECTORY_ADAM_OID',
// If AD DS: it's a Read Only DC (RODC) // If AD DS: it's a Read Only DC (RODC)
'1.2.840.113556.1.4.1920' => 'ACTIVE_DIRECTORY_PARTIAL_SECRETS_OID', '1.2.840.113556.1.4.1920' => 'ACTIVE_DIRECTORY_PARTIAL_SECRETS_OID',
// Running at least W2K8 // Running at least W2K8
'1.2.840.113556.1.4.1935' => 'ACTIVE_DIRECTORY_V60_OID', '1.2.840.113556.1.4.1935' => 'ACTIVE_DIRECTORY_V60_OID',
// Running at least W2K8r2 // Running at least W2K8r2
'1.2.840.113556.1.4.2080' => 'ACTIVE_DIRECTORY_V61_R2_OID', '1.2.840.113556.1.4.2080' => 'ACTIVE_DIRECTORY_V61_R2_OID',
// Running at least W2K12 // Running at least W2K12
'1.2.840.113556.1.4.2237' => 'ACTIVE_DIRECTORY_W8_OID', '1.2.840.113556.1.4.2237' => 'ACTIVE_DIRECTORY_W8_OID',
); );
/**
* @var string
*/
protected $root; protected $root;
/** /**
@ -90,17 +113,23 @@ class Connection
public function __construct($config) public function __construct($config)
{ {
$this->hostname = $config->hostname; $this->hostname = $config->hostname;
$this->bind_dn = $config->bind_dn; $this->bind_dn = $config->bind_dn;
$this->bind_pw = $config->bind_pw; $this->bind_pw = $config->bind_pw;
$this->root_dn = $config->root_dn; $this->root_dn = $config->root_dn;
} }
/**
* @return string
*/
public function getDN() public function getDN()
{ {
return $this->root_dn; return $this->root_dn;
} }
/**
* @return Root|string
*/
public function root() public function root()
{ {
if ($this->root === null) { if ($this->root === null) {
@ -109,30 +138,50 @@ class Connection
return $this->root; return $this->root;
} }
/**
* @return Query
*/
public function select() public function select()
{ {
return new Query($this); return new Query($this);
} }
/**
* @param $query
* @param array $fields
* @return mixed
*/
public function fetchOne($query, $fields = array()) public function fetchOne($query, $fields = array())
{ {
$row = (array) $this->fetchRow($query, $fields); $row = (array)$this->fetchRow($query, $fields);
return array_shift($row); return array_shift($row);
} }
/**
* @param $query
* @param array $fields
* @return mixed
* @throws Exception
*/
public function fetchDN($query, $fields = array()) public function fetchDN($query, $fields = array())
{ {
$rows = $this->fetchAll($query, $fields); $rows = $this->fetchAll($query, $fields);
if (count($rows) !== 1) { if (count($rows) !== 1) {
throw new Exception(sprintf( throw new Exception(
'Cannot fetch single DN for %s', sprintf(
$query 'Cannot fetch single DN for %s',
)); $query
)
);
} }
return key($rows); return key($rows);
} }
/**
* @param $query
* @param array $fields
* @return mixed
*/
public function fetchRow($query, $fields = array()) public function fetchRow($query, $fields = array())
{ {
// TODO: This is ugly, make it better! // TODO: This is ugly, make it better!
@ -140,19 +189,28 @@ class Connection
return array_shift($results); return array_shift($results);
} }
/**
* @param Query $query
* @return int
*/
public function count(Query $query) public function count(Query $query)
{ {
$results = $this->runQuery($query, '+'); $results = $this->runQuery($query, '+');
return ldap_count_entries($this->ds, $results); return ldap_count_entries($this->ds, $results);
} }
/**
* @param $query
* @param array $fields
* @return array
*/
public function fetchAll($query, $fields = array()) public function fetchAll($query, $fields = array())
{ {
$offset = null; $offset = null;
$limit = null; $limit = null;
if ($query->hasLimit()) { if ($query->hasLimit()) {
$offset = $query->getOffset(); $offset = $query->getOffset();
$limit = $query->getLimit(); $limit = $query->getLimit();
} }
$entries = array(); $entries = array();
$results = $this->runQuery($query, $fields); $results = $this->runQuery($query, $fields);
@ -172,9 +230,13 @@ class Connection
return $entries; return $entries;
} }
/**
* @param $attrs
* @return object
*/
public function cleanupAttributes(& $attrs) public function cleanupAttributes(& $attrs)
{ {
$clean = (object) array(); $clean = (object)array();
for ($i = 0; $i < $attrs['count']; $i++) { for ($i = 0; $i < $attrs['count']; $i++) {
$attr_name = $attrs[$i]; $attr_name = $attrs[$i];
if ($attrs[$attr_name]['count'] === 1) { if ($attrs[$attr_name]['count'] === 1) {
@ -188,6 +250,12 @@ class Connection
return $clean; return $clean;
} }
/**
* @param $query
* @param $fields
* @return resource
* @throws Exception
*/
protected function runQuery($query, $fields) protected function runQuery($query, $fields)
{ {
$this->connect(); $this->connect();
@ -201,29 +269,37 @@ class Connection
$results = ldap_search( $results = ldap_search(
$this->ds, $this->ds,
$this->root_dn, $this->root_dn,
(string) $query, (string)$query,
$fields, $fields,
0, // Attributes and values 0, // Attributes and values
0 // No limit - at least where possible 0 // No limit - at least where possible
); );
if (! $results) { if (!$results) {
throw new Exception(sprintf( throw new Exception(
'LDAP query "%s" (root %s) failed: %s', sprintf(
$query, 'LDAP query "%s" (root %s) failed: %s',
$this->root_dn, $query,
ldap_error($this->ds) $this->root_dn,
)); ldap_error($this->ds)
)
);
die('Query failed'); die('Query failed');
} }
$list = array(); $list = array();
if ($query instanceof Query) { if ($query instanceof Query) {
foreach ($query->getSortColumns() as $col) { foreach ($query->getSortColumns() as $col) {
ldap_sort($this->ds, $results, $col[0]) ; ldap_sort($this->ds, $results, $col[0]);
} }
} }
return $results; return $results;
} }
/**
* @param $username
* @param $password
* @return bool
*/
public function testCredentials($username, $password) public function testCredentials($username, $password)
{ {
Log::debug("Trying to connect to %s", $this->hostname); Log::debug("Trying to connect to %s", $this->hostname);
@ -233,10 +309,12 @@ class Connection
if ($r) { if ($r) {
return true; return true;
} else { } else {
log::fatal('LDAP connection (%s / %s) failed: %s', log::fatal(
'LDAP connection (%s / %s) failed: %s',
$username, $username,
'***', '***',
ldap_error($ds)); ldap_error($ds)
);
return false; return false;
/* TODO: Log failure /* TODO: Log failure
throw new Exception(sprintf( throw new Exception(sprintf(
@ -249,17 +327,26 @@ class Connection
} }
} }
/**
* @return string
*/
protected function getConfigDir() protected function getConfigDir()
{ {
return Config::getInstance()->getConfigDir() . '/ldap'; return Config::getInstance()->getConfigDir() . '/ldap';
} }
/**
* @param $domain
*/
protected function discoverServerlistForDomain($domain) protected function discoverServerlistForDomain($domain)
{ {
$ldaps_records = dns_get_record('_ldaps._tcp.' . $domain, DNS_SRV); $ldaps_records = dns_get_record('_ldaps._tcp.' . $domain, DNS_SRV);
$ldap_records = dns_get_record('_ldap._tcp.' . $domain, DNS_SRV); $ldap_records = dns_get_record('_ldap._tcp.' . $domain, DNS_SRV);
} }
/**
*
*/
protected function prepareTlsEnvironment() protected function prepareTlsEnvironment()
{ {
$strict_tls = true; $strict_tls = true;
@ -276,9 +363,13 @@ class Connection
// file_put_contents('/tmp/tom_LDAP.conf', "TLS_REQCERT never\n"); // file_put_contents('/tmp/tom_LDAP.conf', "TLS_REQCERT never\n");
} }
/**
* @return object
*/
protected function fetchRootDseDetails() protected function fetchRootDseDetails()
{ {
$query = $this->select()->from('*', array('+')) $query = $this->select()->from('*', array('+'));
/*, array( /*, array(
'defaultNamingContext', 'defaultNamingContext',
'namingContexts', 'namingContexts',
@ -288,13 +379,13 @@ class Connection
'supportedLDAPVersion', // => array(3, 2) 'supportedLDAPVersion', // => array(3, 2)
'supportedCapabilities' 'supportedCapabilities'
))*/ ))*/
;
$fields = $query->listFields(); $fields = $query->listFields();
$result = ldap_read( $result = ldap_read(
$this->ds, $this->ds,
'', '',
(string) $query, (string)$query,
$query->listFields(), $query->listFields(),
0, 0,
0 0
@ -302,8 +393,8 @@ class Connection
$entry = ldap_first_entry($this->ds, $result); $entry = ldap_first_entry($this->ds, $result);
$result = $this->cleanupAttributes(ldap_get_attributes($this->ds, $entry)); $result = $this->cleanupAttributes(ldap_get_attributes($this->ds, $entry));
if (isset($result->supportedCapabilities)) { if (isset($result->supportedCapabilities)) {
foreach ($result->supportedCapabilities as $oid) { foreach ($result->supportedCapabilities as $oid) {
if (array_key_exists($oid, $this->ms_capability)) { if (array_key_exists($oid, $this->ms_capability)) {
@ -322,14 +413,22 @@ class Connection
return $result; return $result;
} }
/**
*
*/
public function discoverCapabilities() public function discoverCapabilities()
{ {
$this->fetchRootDseDetails(); $this->fetchRootDseDetails();
} }
/**
* @throws Exception
*/
public function connect() public function connect()
{ {
if ($this->ds !== null) return; if ($this->ds !== null) {
return;
}
$use_tls = true; $use_tls = true;
$force_tls = true; $force_tls = true;
@ -343,34 +442,42 @@ class Connection
if (ldap_start_tls($this->ds)) { if (ldap_start_tls($this->ds)) {
Log::debug("Trying ldap_start_tls() succeeded"); Log::debug("Trying ldap_start_tls() succeeded");
} else { } else {
Log::warn("ldap_start_tls() failed: %s. Does your ldap_ca.conf point to the certificate? ",ldap_error($this->ds)); Log::warn(
"ldap_start_tls() failed: %s. Does your ldap_ca.conf point to the certificate? ",
ldap_error($this->ds)
);
} }
// ldap_rename requires LDAPv3: // ldap_rename requires LDAPv3:
if (! ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, 3)) { if (!ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
throw new Exception('LDAPv3 is required'); throw new Exception('LDAPv3 is required');
} }
//
// Not setting this results in "Operations error" on AD when using the // Not setting this results in "Operations error" on AD when using the
// whole domain as search base: // whole domain as search base:
ldap_set_option($this->ds, LDAP_OPT_REFERRALS, 0); ldap_set_option($this->ds, LDAP_OPT_REFERRALS, 0);
// ldap_set_option($this->ds, LDAP_OPT_DEREF, LDAP_DEREF_NEVER); // ldap_set_option($this->ds, LDAP_OPT_DEREF, LDAP_DEREF_NEVER);
Log::debug("Trying ldap_bind(%s)",$this->bind_dn); Log::debug("Trying ldap_bind(%s)", $this->bind_dn);
$r = @ldap_bind($this->ds, $this->bind_dn, $this->bind_pw); $r = @ldap_bind($this->ds, $this->bind_dn, $this->bind_pw);
if (! $r) { if (!$r) {
log::fatal('LDAP connection (%s / %s) failed: %s', log::fatal(
$this->bind_dn,
'***',
ldap_error($this->ds));
throw new Exception(sprintf(
'LDAP connection (%s / %s) failed: %s', 'LDAP connection (%s / %s) failed: %s',
$this->bind_dn, $this->bind_dn,
'***' /* $this->bind_pw */, '***',
ldap_error($this->ds) ldap_error($this->ds)
)); );
throw new Exception(
sprintf(
'LDAP connection (%s / %s) failed: %s',
$this->bind_dn,
'***' /* $this->bind_pw */,
ldap_error($this->ds)
)
);
} }
} }
} }

View File

@ -1,7 +1,13 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Ldap; namespace Icinga\Protocol\Ldap;
/**
* Class Exception
* @package Icinga\Protocol\Ldap
*/
class Exception extends \Exception class Exception extends \Exception
{ {
} }

View File

@ -1,11 +1,9 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Ldap; namespace Icinga\Protocol\Ldap;
/**
* LdapUtils class
*
* @package Icinga\Protocol\Ldap
*/
/** /**
* This class provides useful LDAP-related functions * This class provides useful LDAP-related functions
* *
@ -52,7 +50,9 @@ class LdapUtils
{ {
$str = ''; $str = '';
foreach ($parts as $part) { foreach ($parts as $part) {
if ($str !== '') { $str .= ','; } if ($str !== '') {
$str .= ',';
}
list($key, $val) = preg_split('~=~', $part, 2); list($key, $val) = preg_split('~=~', $part, 2);
$str .= $key . '=' . self::quoteForDN($val); $str .= $key . '=' . self::quoteForDN($val);
} }
@ -69,9 +69,20 @@ class LdapUtils
*/ */
public static function quoteForDN($str) public static function quoteForDN($str)
{ {
return self::quoteChars($str, array( return self::quoteChars(
',', '=', '+', '<', '>', ';', '\\', '"', '#' $str,
)); array(
',',
'=',
'+',
'<',
'>',
';',
'\\',
'"',
'#'
)
);
} }
/** /**
@ -80,6 +91,7 @@ class LdapUtils
* Special characters will be escaped * Special characters will be escaped
* *
* @param string String to be escaped * @param string String to be escaped
* @param bool $allow_wildcard
* @return string * @return string
*/ */
public static function quoteForSearch($str, $allow_wildcard = false) public static function quoteForSearch($str, $allow_wildcard = false)
@ -95,14 +107,16 @@ class LdapUtils
* *
* Special characters will be escaped * Special characters will be escaped
* *
* @param string String to be escaped * @param $str
* @param $chars
* @internal param String $string to be escaped
* @return string * @return string
*/ */
protected static function quoteChars($str, $chars) protected static function quoteChars($str, $chars)
{ {
$quotedChars = array(); $quotedChars = array();
foreach ($chars as $k => $v) { foreach ($chars as $k => $v) {
// Temporarily prefixing with illegal '(' // Temporarily prefixing with illegal '('
$quotedChars[$k] = '(' . str_pad(dechex(ord($v)), 2, '0'); $quotedChars[$k] = '(' . str_pad(dechex(ord($v)), 2, '0');
} }
$str = str_replace($chars, $quotedChars, $str); $str = str_replace($chars, $quotedChars, $str);
@ -112,4 +126,3 @@ class LdapUtils
return $str; return $str;
} }
} }

View File

@ -1,31 +1,49 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Ldap; namespace Icinga\Protocol\Ldap;
/**
* Node class
*
* @package Icinga\Protocol\Ldap
*/
/** /**
* This class represents an LDAP node object * This class represents an LDAP node object
* *
* @copyright Copyright (c) 2013 Icinga-Web Team <info@icinga.org> * @copyright Copyright (c) 2013 Icinga-Web Team <info@icinga.org>
* @author Icinga-Web Team <info@icinga.org> * @author Icinga-Web Team <info@icinga.org>
* @package Icinga\Protocol\Ldap * @package Icinga\Protocol\Ldap
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
*/ */
class Node extends Root class Node extends Root
{ {
/**
* @var Connection
*/
protected $connection; protected $connection;
/**
* @var
*/
protected $rdn; protected $rdn;
/**
* @var Root
*/
protected $parent; protected $parent;
/**
* @param Root $parent
*/
protected function __construct(Root $parent) protected function __construct(Root $parent)
{ {
$this->connection = $parent->getConnection(); $this->connection = $parent->getConnection();
$this->parent = $parent; $this->parent = $parent;
} }
/**
* @param $parent
* @param $rdn
* @param array $props
* @return Node
*/
public static function createWithRDN($parent, $rdn, $props = array()) public static function createWithRDN($parent, $rdn, $props = array())
{ {
$node = new Node($parent); $node = new Node($parent);
@ -34,14 +52,19 @@ class Node extends Root
return $node; return $node;
} }
/**
* @return mixed
*/
public function getRDN() public function getRDN()
{ {
return $this->rdn; return $this->rdn;
} }
/**
* @return mixed|string
*/
public function getDN() public function getDN()
{ {
return $this->parent->getDN() . '.' . $this->getRDN(); return $this->parent->getDN() . '.' . $this->getRDN();
} }
} }

View File

@ -1,11 +1,9 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Ldap; namespace Icinga\Protocol\Ldap;
/**
* Search class
*
* @package Icinga\Protocol\Ldap
*/
/** /**
* Search abstraction class * Search abstraction class
* *
@ -19,22 +17,50 @@ namespace Icinga\Protocol\Ldap;
* @author Icinga-Web Team <info@icinga.org> * @author Icinga-Web Team <info@icinga.org>
* @package Icinga\Protocol\Ldap * @package Icinga\Protocol\Ldap
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
* @package Icinga\Protocol\Ldap
*/ */
class Query class Query
{ {
/**
* @var Connection
*/
protected $connection; protected $connection;
/**
* @var array
*/
protected $filters = array(); protected $filters = array();
/**
* @var array
*/
protected $fields = array(); protected $fields = array();
/**
* @var
*/
protected $limit_count; protected $limit_count;
/**
* @var
*/
protected $limit_offset; protected $limit_offset;
/**
* @var array
*/
protected $sort_columns = array(); protected $sort_columns = array();
/**
* @var
*/
protected $count; protected $count;
/** /**
* Constructor * Constructor
* *
* @param Connection LDAP Connection object * @param \Icinga\Protocol\Ldap\Connection $connection LDAP Connection object
* @return void * @return \Icinga\Protocol\Ldap\Query
*/ */
public function __construct(Connection $connection) public function __construct(Connection $connection)
{ {
@ -57,19 +83,24 @@ class Query
/** /**
* Count result set, ignoring limits * Count result set, ignoring limits
* *
* @param null $count
* @param null $offset
* @throws Exception
* @return int * @return int
*/ */
public function limit($count = null, $offset = null) public function limit($count = null, $offset = null)
{ {
if (! preg_match('~^\d+~', $count . $offset)) { if (!preg_match('~^\d+~', $count . $offset)) {
throw new Exception(sprintf( throw new Exception(
'Got invalid limit: %s, %s', sprintf(
$count, 'Got invalid limit: %s, %s',
$offset $count,
)); $offset
)
);
} }
$this->limit_count = (int) $count; $this->limit_count = (int)$count;
$this->limit_offset = (int) $offset; $this->limit_offset = (int)$offset;
return $this; return $this;
} }
@ -122,15 +153,18 @@ class Query
{ {
$result = $this->fetchAll(); $result = $this->fetchAll();
$sorted = array(); $sorted = array();
foreach ($result as $key => & $item) foreach ($result as $key => & $item) {
{ $new_key = LdapUtils::implodeDN(
$new_key = LdapUtils::implodeDN(array_reverse(LdapUtils::explodeDN( array_reverse(
preg_replace( LdapUtils::explodeDN(
'/,' . preg_quote($this->connection->getDN(), '/') . '$/', preg_replace(
'', '/,' . preg_quote($this->connection->getDN(), '/') . '$/',
$key '',
$key
)
)
) )
))); );
$sorted[$new_key] = $key; $sorted[$new_key] = $key;
} }
unset($groups); unset($groups);
@ -189,6 +223,8 @@ class Query
* *
* This creates an objectClass filter * This creates an objectClass filter
* *
* @param $objectClass
* @param array $fields
* @return Query * @return Query
*/ */
public function from($objectClass, $fields = array()) public function from($objectClass, $fields = array())
@ -249,6 +285,8 @@ class Query
/** /**
* Return a pagination adapter for the current query * Return a pagination adapter for the current query
* *
* @param null $limit
* @param null $page
* @return \Zend_Paginator * @return \Zend_Paginator
*/ */
public function paginate($limit = null, $page = null) public function paginate($limit = null, $page = null)
@ -303,7 +341,7 @@ class Query
} }
/** /**
* Descructor * Destructor
*/ */
public function __destruct() public function __destruct()
{ {
@ -311,4 +349,3 @@ class Query
unset($this->connection); unset($this->connection);
} }
} }

View File

@ -1,11 +1,9 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Ldap; namespace Icinga\Protocol\Ldap;
/**
* Root class
*
* @package Icinga\Protocol\Ldap
*/
/** /**
* This class is a special node object, representing your connections root node * This class is a special node object, representing your connections root node
* *
@ -13,40 +11,71 @@ namespace Icinga\Protocol\Ldap;
* @author Icinga-Web Team <info@icinga.org> * @author Icinga-Web Team <info@icinga.org>
* @package Icinga\Protocol\Ldap * @package Icinga\Protocol\Ldap
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
* @package Icinga\Protocol\Ldap
*/ */
class Root class Root
{ {
/**
* @var string
*/
protected $rdn; protected $rdn;
/**
* @var Connection
*/
protected $connection; protected $connection;
/**
* @var array
*/
protected $children = array(); protected $children = array();
/**
* @var array
*/
protected $props = array(); protected $props = array();
/**
* @param Connection $connection
*/
protected function __construct(Connection $connection) protected function __construct(Connection $connection)
{ {
$this->connection = $connection; $this->connection = $connection;
} }
/**
* @return bool
*/
public function hasParent() public function hasParent()
{ {
return false; return false;
} }
/**
* @param Connection $connection
* @return Root
*/
public static function forConnection(Connection $connection) public static function forConnection(Connection $connection)
{ {
$root = new Root($connection); $root = new Root($connection);
return $root; return $root;
} }
/**
* @param $dn
* @param array $props
* @return Node
*/
public function createChildByDN($dn, $props = array()) public function createChildByDN($dn, $props = array())
{ {
$dn = $this->stripMyDN($dn); $dn = $this->stripMyDN($dn);
$parts = array_reverse(LdapUtils::explodeDN($dn)); $parts = array_reverse(LdapUtils::explodeDN($dn));
$parent = $this; $parent = $this;
while($rdn = array_shift($parts)) { while ($rdn = array_shift($parts)) {
if ($parent->hasChildRDN($rdn)) { if ($parent->hasChildRDN($rdn)) {
$child = $parent->getChildByRDN($rdn); $child = $parent->getChildByRDN($rdn);
} else { } else {
$child = Node::createWithRDN($parent, $rdn, (array) $props); $child = Node::createWithRDN($parent, $rdn, (array)$props);
$parent->addChild($child); $parent->addChild($child);
} }
$parent = $child; $parent = $child;
@ -54,102 +83,159 @@ class Root
return $child; return $child;
} }
/**
* @param $rdn
* @return bool
*/
public function hasChildRDN($rdn) public function hasChildRDN($rdn)
{ {
return array_key_exists(strtolower($rdn), $this->children); return array_key_exists(strtolower($rdn), $this->children);
} }
/**
* @param $rdn
* @return mixed
* @throws Exception
*/
public function getChildByRDN($rdn) public function getChildByRDN($rdn)
{ {
if (! $this->hasChildRDN($rdn)) { if (!$this->hasChildRDN($rdn)) {
throw new Exception(sprintf( throw new Exception(
'The child RDN "%s" is not available', sprintf(
$rdn 'The child RDN "%s" is not available',
)); $rdn
)
);
} }
return $this->children[strtolower($rdn)]; return $this->children[strtolower($rdn)];
} }
/**
* @return array
*/
public function children() public function children()
{ {
return $this->children; return $this->children;
} }
/**
* @return bool
*/
public function hasChildren() public function hasChildren()
{ {
return ! empty($this->children); return !empty($this->children);
} }
/**
* @param Node $child
* @return $this
*/
public function addChild(Node $child) public function addChild(Node $child)
{ {
$this->children[strtolower($child->getRDN())] = $child; $this->children[strtolower($child->getRDN())] = $child;
return $this; return $this;
} }
/**
* @param $dn
* @return string
*/
protected function stripMyDN($dn) protected function stripMyDN($dn)
{ {
$this->assertSubDN($dn); $this->assertSubDN($dn);
return substr($dn, 0, strlen($dn) - strlen($this->getDN()) - 1); return substr($dn, 0, strlen($dn) - strlen($this->getDN()) - 1);
} }
/**
* @param $dn
* @return $this
* @throws Exception
*/
protected function assertSubDN($dn) protected function assertSubDN($dn)
{ {
$mydn = $this->getDN(); $mydn = $this->getDN();
$end = substr($dn, -1 * strlen($mydn)); $end = substr($dn, -1 * strlen($mydn));
if (strtolower($end) !== strtolower($mydn)) { if (strtolower($end) !== strtolower($mydn)) {
throw new Exception(sprintf( throw new Exception(
'"%s" is not a child of "%s"', sprintf(
$dn, '"%s" is not a child of "%s"',
$mydn $dn,
)); $mydn
)
);
} }
if (strlen($dn) === strlen($mydn)) { if (strlen($dn) === strlen($mydn)) {
throw new Exception(sprintf( throw new Exception(
'"%s" is not a child of "%s", they are equal', sprintf(
$dn, '"%s" is not a child of "%s", they are equal',
$mydn $dn,
)); $mydn
)
);
} }
return $this; return $this;
} }
/**
* @param Connection $connection
* @return $this
*/
public function setConnection(Connection $connection) public function setConnection(Connection $connection)
{ {
$this->connection = $connection; $this->connection = $connection;
return $this; return $this;
} }
/**
* @return Connection
*/
public function getConnection() public function getConnection()
{ {
return $this->connection; return $this->connection;
} }
/**
* @return bool
*/
public function hasBeenChanged() public function hasBeenChanged()
{ {
return false; return false;
} }
/**
* @return mixed
*/
public function getRDN() public function getRDN()
{ {
return $this->getDN(); return $this->getDN();
} }
/**
* @return mixed
*/
public function getDN() public function getDN()
{ {
return $this->connection->getDN(); return $this->connection->getDN();
} }
/**
* @param $key
* @return null
*/
public function __get($key) public function __get($key)
{ {
if (! array_key_exists($key, $this->props)) { if (!array_key_exists($key, $this->props)) {
return null; return null;
} }
return $this->props[$key]; return $this->props[$key];
} }
/**
* @param $key
* @return bool
*/
public function __isset($key) public function __isset($key)
{ {
return array_key_exists($key, $this->props); return array_key_exists($key, $this->props);
} }
} }

View File

@ -1,8 +1,13 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat\Exception; namespace Icinga\Protocol\Statusdat\Exception;
/**
* Class ParsingException
* @package Icinga\Protocol\Statusdat\Exception
*/
class ParsingException extends \RuntimeException class ParsingException extends \RuntimeException
{ {
} }

View File

@ -1,18 +1,25 @@
<?php <?php
/** // {{{ICINGA_LICENSE_HEADER}}}
* Created by JetBrains PhpStorm. // {{{ICINGA_LICENSE_HEADER}}}
* User: moja
* Date: 1/17/13
* Time: 10:21 AM
* To change this template use File | Settings | File Templates.
*/
namespace Icinga\Protocol\Statusdat; namespace Icinga\Protocol\Statusdat;
interface IReader interface IReader
{ {
/**
* @return mixed
*/
public function getState(); public function getState();
/**
* @return mixed
*/
public function getObjects(); public function getObjects();
public function getObjectByName($type,$name); /**
* @param $type
* @param $name
* @return mixed
*/
public function getObjectByName($type, $name);
} }

View File

@ -0,0 +1,47 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat;
/**
* Class ObjectContainer
* @package Icinga\Protocol\Statusdat
*/
class ObjectContainer extends \stdClass
{
/**
* @var \stdClass
*/
public $ref;
/**
* @var IReader
*/
public $reader;
/**
* @param \stdClass $obj
* @param IReader $reader
*/
public function __construct(\stdClass &$obj, IReader &$reader)
{
$this->ref = & $obj;
$this->reader = & $reader;
}
/**
* @param $attribute
* @return \stdClass
*/
public function __get($attribute)
{
$exploded = explode(".", $attribute);
$result = $this->ref;
foreach ($exploded as $elem) {
$result = $result->$elem;
}
return $result;
}
}

View File

@ -1,27 +1,67 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat; namespace Icinga\Protocol\Statusdat;
use Icinga\Exception\ConfigurationError;
use Icinga\Protocol\Statusdat\Exception\ParsingException as ParsingException; use Icinga\Protocol\Statusdat\Exception\ParsingException as ParsingException;
class Parser /**
* Class Parser
* @package Icinga\Protocol\Statusdat
*/
class Parser
{ {
private $deferred = array(); /**
* @var array
*/
private $deferred = array();
/**
* @var null|resource
*/
private $filehandle = null; private $filehandle = null;
/**
* @var null
*/
private $currentObjectType = null; private $currentObjectType = null;
/**
* @var null
*/
private $currentStateType = null; private $currentStateType = null;
/**
* @var null
*/
private $icingaState = null; private $icingaState = null;
/**
* @var int
*/
private $lineCtr = 0; private $lineCtr = 0;
/**
* @param null $filehandle
* @param null $baseState
* @throws \Icinga\Exception\ConfigurationError
*/
public function __construct($filehandle = null, $baseState = null) public function __construct($filehandle = null, $baseState = null)
{ {
if (!is_resource($filehandle)) if (!is_resource($filehandle)) {
throw new \Icinga\Exception\ConfigurationError("Statusdat parser can't find $filehandle"); throw new ConfigurationError("Statusdat parser can't find $filehandle");
}
$this->filehandle = $filehandle; $this->filehandle = $filehandle;
$this->icingaState = $baseState; $this->icingaState = $baseState;
} }
/**
*
*/
public function parseObjectsFile() public function parseObjectsFile()
{ {
\Icinga\Application\Logger::debug("Reading new objects file"); \Icinga\Application\Logger::debug("Reading new objects file");
@ -33,9 +73,10 @@ class Parser
$line = trim(fgets($filehandle)); $line = trim(fgets($filehandle));
$this->lineCtr++; $this->lineCtr++;
if ($line === "" || $line[0] === "#") if ($line === "" || $line[0] === "#") {
continue; continue;
$this->currentObjectType = trim(substr($line,$DEFINE,-1)); }
$this->currentObjectType = trim(substr($line, $DEFINE, -1));
if (!isset($this->icingaState[$this->currentObjectType])) { if (!isset($this->icingaState[$this->currentObjectType])) {
$this->icingaState[$this->currentObjectType] = array(); $this->icingaState[$this->currentObjectType] = array();
} }
@ -44,50 +85,62 @@ class Parser
$this->processDeferred(); $this->processDeferred();
} }
/**
* @param null $filehandle
* @throws \Icinga\Exception\ProgrammingError
*/
public function parseRuntimeState($filehandle = null) public function parseRuntimeState($filehandle = null)
{ {
if($filehandle != null) if ($filehandle != null) {
$this->filehandle = $filehandle; $this->filehandle = $filehandle;
else } else {
$filehandle = $this->filehandle; $filehandle = $this->filehandle;
}
if(!$this->icingaState) if (!$this->icingaState) {
throw new \Icinga\Exception\ProgrammingError("Tried to read runtime state without existing objects data"); throw new \Icinga\Exception\ProgrammingError("Tried to read runtime state without existing objects data");
}
$this->overwrites = array(); $this->overwrites = array();
while (!feof($filehandle)) { while (!feof($filehandle)) {
$line = trim(fgets($filehandle)); $line = trim(fgets($filehandle));
$this->lineCtr++; $this->lineCtr++;
if ($line === "" || $line[0] === "#") if ($line === "" || $line[0] === "#") {
continue; continue;
}
$this->currentStateType = trim(substr($line,0,-1)); $this->currentStateType = trim(substr($line, 0, -1));
$this->readCurrentState(); $this->readCurrentState();
} }
} }
/**
* @throws Exception\ParsingException
*/
private function readCurrentObject() private function readCurrentObject()
{ {
$filehandle = $this->filehandle; $filehandle = $this->filehandle;
$monitoringObject = new \stdClass(); $monitoringObject = new \stdClass();
while (!feof($filehandle)) { while (!feof($filehandle)) {
$line = explode("\t",trim(fgets($filehandle)),2); $line = explode("\t", trim(fgets($filehandle)), 2);
$this->lineCtr++; $this->lineCtr++;
if (!$line) if (!$line) {
continue; continue;
}
// End of object // End of object
if ($line[0] === "}") { if ($line[0] === "}") {
$this->registerObject($monitoringObject); $this->registerObject($monitoringObject);
return; return;
} }
if(!isset($line[1])) if (!isset($line[1])) {
$line[1] = ""; $line[1] = "";
}
$monitoringObject->{$line[0]} = trim($line[1]); $monitoringObject->{$line[0]} = trim($line[1]);
} }
throw new ParsingException("Unexpected EOF in objects.cache, line ".$this->lineCtr); throw new ParsingException("Unexpected EOF in objects.cache, line " . $this->lineCtr);
} }
/** /**
@ -101,48 +154,60 @@ class Parser
$objectType = $this->getObjectTypeForState(); $objectType = $this->getObjectTypeForState();
if($objectType != "host" && $objectType != "service") { if ($objectType != "host" && $objectType != "service") {
$this->skipObject(); // ignore unknown objects $this->skipObject(); // ignore unknown objects
return; return;
} }
if(!isset($this->icingaState[$this->currentObjectType])) if (!isset($this->icingaState[$this->currentObjectType])) {
throw new ParsingException("No $this->currentObjectType objects registered in objects.cache"); throw new ParsingException("No $this->currentObjectType objects registered in objects.cache");
$base = &$this->icingaState[$this->currentObjectType]; }
$state = &$this->skipObject(true); $base = & $this->icingaState[$this->currentObjectType];
$statusdatObject->runtimeState = &$state; $state = & $this->skipObject(true);
$statusdatObject->runtimeState = & $state;
$name = $this->getObjectIdentifier($statusdatObject); $name = $this->getObjectIdentifier($statusdatObject);
if(!isset($base[$name])) if (!isset($base[$name])) {
throw new ParsingException("Unknown object $name ".$this->currentObjectType." - ".print_r($statusdatObject,true)."\n".print_r($base,true)); throw new ParsingException(
$type = substr($this->currentStateType,strlen($objectType)); "Unknown object $name " . $this->currentObjectType . " - "
. print_r(
$statusdatObject,
true
)
. "\n" . print_r($base, true)
);
}
$type = substr($this->currentStateType, strlen($objectType));
if($type == "status") { if ($type == "status") {
$base[$name]->status = &$statusdatObject; $base[$name]->status = & $statusdatObject;
} else { } else {
if(!isset($base[$name]->$type) || !in_array($base[$name]->$type,$this->overwrites)) { if (!isset($base[$name]->$type) || !in_array($base[$name]->$type, $this->overwrites)) {
$base[$name]->$type = array(); $base[$name]->$type = array();
$this->overwrites[] = &$base[$name]->$type; $this->overwrites[] = & $base[$name]->$type;
} }
array_push($base[$name]->$type,$statusdatObject); array_push($base[$name]->$type, $statusdatObject);
} }
return; return;
} }
/**
* @return null|string
*/
private function getObjectTypeForState() private function getObjectTypeForState()
{ {
$pos = strpos($this->currentStateType,"service"); $pos = strpos($this->currentStateType, "service");
if($pos === False) { if ($pos === false) {
$pos = strpos($this->currentStateType,"host"); $pos = strpos($this->currentStateType, "host");
} else { } else {
$this->currentObjectType = "service"; $this->currentObjectType = "service";
return "service"; return "service";
} }
if($pos === False) if ($pos === false) {
return $this->currentStateType; return $this->currentStateType;
else { } else {
$this->currentObjectType = "host"; $this->currentObjectType = "host";
return "host"; return "host";
} }
@ -150,89 +215,116 @@ class Parser
return $this->currentObjectType; return $this->currentObjectType;
} }
/**
* @param bool $returnString
* @return string
*/
protected function skipObject($returnString = false) protected function skipObject($returnString = false)
{ {
if(!$returnString) { if (!$returnString) {
while(trim(fgets($this->filehandle)) !== "}") { while (trim(fgets($this->filehandle)) !== "}") {
} }
return; return;
} else { } else {
$str = ""; $str = "";
while(($val = trim(fgets($this->filehandle))) !== "}") { while (($val = trim(fgets($this->filehandle))) !== "}") {
$str .= $val."\n"; $str .= $val . "\n";
} }
return $str; return $str;
} }
} }
protected function registerObject(&$object) { /**
* @param $object
*/
protected function registerObject(&$object)
{
$name = $this->getObjectIdentifier($object); $name = $this->getObjectIdentifier($object);
if($name !== false) { if ($name !== false) {
$this->icingaState[$this->currentObjectType][$name] = &$object; $this->icingaState[$this->currentObjectType][$name] = & $object;
} }
$this->registerObjectAsProperty($object); $this->registerObjectAsProperty($object);
} }
/**
* @param $object
*/
protected function registerObjectAsProperty(&$object) protected function registerObjectAsProperty(&$object)
{ {
if($this->currentObjectType == "service" || $this->currentObjectType == "host") { if ($this->currentObjectType == "service" || $this->currentObjectType == "host") {
return; return;
} }
$isService = strpos($this->currentObjectType,"service") !== False; $isService = strpos($this->currentObjectType, "service") !== false;
$isHost = strpos($this->currentObjectType,"host") !== False; $isHost = strpos($this->currentObjectType, "host") !== false;
$name = $this->getObjectIdentifier($object); $name = $this->getObjectIdentifier($object);
if($isService === false && $isHost === false) // this would be error in the parser implementation if ($isService === false && $isHost === false) { // this would be error in the parser implementation
return; return;
}
$property = $this->currentObjectType; $property = $this->currentObjectType;
if($isService) { if ($isService) {
$this->currentObjectType = "service"; $this->currentObjectType = "service";
$property = substr($property,strlen("service")); $property = substr($property, strlen("service"));
} else { } else {
$this->currentObjectType = "host"; $this->currentObjectType = "host";
$property = substr($property,strlen("host")); $property = substr($property, strlen("host"));
}
if (!isset($this->icingaState[$this->currentObjectType])) {
return $this->deferRegistration($object, $this->currentObjectType . $property);
} }
if(!isset($this->icingaState[$this->currentObjectType]))
return $this->deferRegistration($object,$this->currentObjectType.$property);
// @TODO: Clean up, this differates between 1:n and 1:1 references // @TODO: Clean up, this differates between 1:n and 1:1 references
if(strpos($property ,"group") !== False) { if (strpos($property, "group") !== false) {
$sourceIdentifier = $this->getMembers($object); $sourceIdentifier = $this->getMembers($object);
foreach($sourceIdentifier as $id) { foreach ($sourceIdentifier as $id) {
$source = $this->icingaState[$this->currentObjectType][$id]; $source = $this->icingaState[$this->currentObjectType][$id];
if(!isset($source->$property)) if (!isset($source->$property)) {
$source->$property = array(); $source->$property = array();
}
array_push($source->$property, $name); array_push($source->$property, $name);
} }
} else { } else {
$source = $this->icingaState[$this->currentObjectType][$this->getObjectIdentifier($object)]; $source = $this->icingaState[$this->currentObjectType][$this->getObjectIdentifier($object)];
if(!isset($source->$property)) if (!isset($source->$property)) {
$source->$property = array(); $source->$property = array();
}
array_push($source->$property, $object); array_push($source->$property, $object);
} }
} }
protected function deferRegistration($object,$objType) /**
* @param $object
* @param $objType
*/
protected function deferRegistration($object, $objType)
{ {
$this->deferred[] = array($object,$objType); $this->deferred[] = array($object, $objType);
} }
protected function processDeferred() { /**
foreach($this->deferred as $obj) { *
*/
protected function processDeferred()
{
foreach ($this->deferred as $obj) {
$this->currentObjectType = $obj[1]; $this->currentObjectType = $obj[1];
$this->registerObjectAsProperty($obj[0]); $this->registerObjectAsProperty($obj[0]);
} }
} }
/**
* @param $object
* @return array
*/
protected function getMembers(&$object) protected function getMembers(&$object)
{ {
$members = explode(",",$object->members); $members = explode(",", $object->members);
if($this->currentObjectType == "service") { if ($this->currentObjectType == "service") {
$res = array(); $res = array();
for($i=0;$i<count($members);$i+=2) { for ($i = 0; $i < count($members); $i += 2) {
$res[] = $members[$i].";".$members[$i+1]; $res[] = $members[$i] . ";" . $members[$i + 1];
} }
return $res; return $res;
} else { } else {
@ -241,24 +333,29 @@ class Parser
} }
/**
* @param $object
* @return bool|string
*/
protected function getObjectIdentifier(&$object) protected function getObjectIdentifier(&$object)
{ {
if ($this->currentObjectType == "service") { if ($this->currentObjectType == "service") {
return $object->host_name.";".$object->service_description; return $object->host_name . ";" . $object->service_description;
} }
$name = $this->currentObjectType."_name"; $name = $this->currentObjectType . "_name";
if(isset($object->{$name})) if (isset($object->{$name})) {
return $object->{$name}; return $object->{$name};
}
return false; return false;
} }
/**
* @return null
*/
public function getRuntimeState() public function getRuntimeState()
{ {
return $this->icingaState; return $this->icingaState;
} }
}
}

View File

@ -1,10 +1,20 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat; namespace Icinga\Protocol\Statusdat;
use Icinga\Protocol; use Icinga\Protocol;
/**
* Class Query
* @package Icinga\Protocol\Statusdat
*/
class Query extends Protocol\AbstractQuery class Query extends Protocol\AbstractQuery
{ {
/**
* @var array
*/
public static $VALID_TARGETS = array( public static $VALID_TARGETS = array(
"hosts" => array("host"), "hosts" => array("host"),
"services" => array("service"), "services" => array("service"),
@ -18,76 +28,153 @@ class Query extends Protocol\AbstractQuery
"servicecomments" => array("servicecomment") "servicecomments" => array("servicecomment")
); );
/**
* @var IReader|null
*/
private $reader = null; private $reader = null;
/**
* @var string
*/
private $source = ""; private $source = "";
/**
* @var array
*/
private $columns = array(); private $columns = array();
/**
* @var null
*/
private $limit = null; private $limit = null;
/**
* @var int
*/
private $offset = 0; private $offset = 0;
/**
* @var array
*/
private $order_columns = array(); private $order_columns = array();
/**
* @var array
*/
private $groupColumns = array(); private $groupColumns = array();
/**
* @var null
*/
private $groupByFn = null; private $groupByFn = null;
/**
* @var array
*/
private $filter = array(); private $filter = array();
// Magic indexes /**
*
*/
const FN_SCOPE = 0; const FN_SCOPE = 0;
/**
*
*/
const FN_NAME = 1; const FN_NAME = 1;
/**
* @return bool
*/
public function hasOrder() public function hasOrder()
{ {
return !empty($this->order_columns); return !empty($this->order_columns);
} }
/**
* @return bool
*/
public function hasColumns() public function hasColumns()
{ {
return !empty($this->columns); return !empty($this->columns);
} }
/**
* @return array
*/
public function getColumns() public function getColumns()
{ {
return $this->columns; return $this->columns;
} }
/**
* @return bool
*/
public function hasLimit() public function hasLimit()
{ {
return $this->limit !== false; return $this->limit !== false;
} }
/**
* @return bool
*/
public function hasOffset() public function hasOffset()
{ {
return $this->offset !== false; return $this->offset !== false;
} }
/**
* @return null
*/
public function getLimit() public function getLimit()
{ {
return $this->limit; return $this->limit;
} }
/**
* @return int|null
*/
public function getOffset() public function getOffset()
{ {
return $this->offset; return $this->offset;
} }
/**
* @param IReader $reader
*/
public function __construct(IReader $reader) public function __construct(IReader $reader)
{ {
$this->reader = $reader; $this->reader = $reader;
} }
/**
* @param $key
* @param null $val
* @return $this
*/
public function where($key, $val = null) public function where($key, $val = null)
{ {
$this->filter[] = array($key, $val); $this->filter[] = array($key, $val);
return $this; return $this;
} }
/**
* @param $columns
* @param null $dir
* @return $this
*/
public function order($columns, $dir = null) public function order($columns, $dir = null)
{ {
if($dir && strtolower($dir) == "desc") if ($dir && strtolower($dir) == "desc") {
$dir = self::SORT_DESC; $dir = self::SORT_DESC;
else } else {
$dir = self::SORT_ASC; $dir = self::SORT_ASC;
if(!is_array($columns)) }
if (!is_array($columns)) {
$columns = array($columns); $columns = array($columns);
foreach($columns as $col) { }
foreach ($columns as $col) {
if (($pos = strpos($col, ' ')) !== false) { if (($pos = strpos($col, ' ')) !== false) {
$dir = strtoupper(substr($col, $pos + 1)); $dir = strtoupper(substr($col, $pos + 1));
@ -106,6 +193,12 @@ class Query extends Protocol\AbstractQuery
return $this; return $this;
} }
/**
* @param null $count
* @param int $offset
* @return $this
* @throws Exception
*/
public function limit($count = null, $offset = 0) public function limit($count = null, $offset = 0)
{ {
if ((is_null($count) || is_integer($count)) && (is_null($offset) || is_integer($offset))) { if ((is_null($count) || is_integer($count)) && (is_null($offset) || is_integer($offset))) {
@ -117,12 +210,19 @@ class Query extends Protocol\AbstractQuery
return $this; return $this;
} }
/**
* @param $table
* @param null $columns
* @return $this
* @throws \Exception
*/
public function from($table, $columns = null) public function from($table, $columns = null)
{ {
if (isset(self::$VALID_TARGETS[$table])) if (isset(self::$VALID_TARGETS[$table])) {
$this->source = $table; $this->source = $table;
else } else {
throw new \Exception("Unknown from target for status.dat :". $table); throw new \Exception("Unknown from target for status.dat :" . $table);
}
$this->columns = $columns; $this->columns = $columns;
return $this; return $this;
} }
@ -158,99 +258,131 @@ class Query extends Protocol\AbstractQuery
return $result; return $result;
} }
private function orderIndices(array &$indices) { /**
if(!empty($this->order_columns)) { * @param array $indices
foreach($indices as $type=>&$subindices) { */
private function orderIndices(array &$indices)
{
if (!empty($this->order_columns)) {
foreach ($indices as $type => &$subindices) {
$this->currentType = $type; // we're singlethreaded, so let's do it a bit dirty $this->currentType = $type; // we're singlethreaded, so let's do it a bit dirty
usort($subindices,array($this,"orderResult")); usort($subindices, array($this, "orderResult"));
} }
} }
} }
private function orderResult($a,$b) { /**
$o1 = &$this->reader->getObjectByName($this->currentType,$a); * @param $a
$o2 = &$this->reader->getObjectByName($this->currentType,$b); * @param $b
* @return int
*/
private function orderResult($a, $b)
{
$o1 = & $this->reader->getObjectByName($this->currentType, $a);
$o2 = & $this->reader->getObjectByName($this->currentType, $b);
$result = 0; $result = 0;
foreach($this->order_columns as $col) { foreach ($this->order_columns as $col) {
$result += $col[1]*strnatcasecmp($o1->{$col[0]},$o2->{$col[0]}); $result += $col[1] * strnatcasecmp($o1->{$col[0]}, $o2->{$col[0]});
} }
if($result > 0) if ($result > 0) {
return 1; return 1;
if($result < 0) }
if ($result < 0) {
return -1; return -1;
}
return 0; return 0;
} }
/**
* @param array $indices
*/
private function limitIndices(array &$indices) private function limitIndices(array &$indices)
{ {
foreach($indices as $type=>$subindices){ foreach ($indices as $type => $subindices) {
$indices[$type] = array_slice($subindices,$this->offset,$this->limit); $indices[$type] = array_slice($subindices, $this->offset, $this->limit);
} }
} }
public function groupByFunction($fn,$scope=null) /**
* @param $fn
* @param null $scope
* @return $this
*/
public function groupByFunction($fn, $scope = null)
{ {
$this->groupByFn = array($scope ? $scope : $this,$fn); $this->groupByFn = array($scope ? $scope : $this, $fn);
return $this; return $this;
} }
/**
* @param $columns
* @return $this
*/
public function groupByColumns($columns) public function groupByColumns($columns)
{ {
if(!is_array($columns)) if (!is_array($columns)) {
$columns = array($columns); $columns = array($columns);
}
$this->groupColumns = $columns; $this->groupColumns = $columns;
$this->groupByFn = array($this,"columnGroupFn"); $this->groupByFn = array($this, "columnGroupFn");
return $this; return $this;
} }
/**
* @param array $indices
* @return array
*/
private function columnGroupFn(array &$indices) private function columnGroupFn(array &$indices)
{ {
$cols = $this->groupColumns; $cols = $this->groupColumns;
$result = array(); $result = array();
foreach($indices as $type=>$subindices) { foreach ($indices as $type => $subindices) {
foreach($subindices as $objectIndex) { foreach ($subindices as $objectIndex) {
$r = &$this->reader->getObjectByName($type,$objectIndex); $r = & $this->reader->getObjectByName($type, $objectIndex);
$hash = ""; $hash = "";
$cols = array(); $cols = array();
foreach($this->groupColumns as $col) { foreach ($this->groupColumns as $col) {
$hash = md5($hash.$r->$col); $hash = md5($hash . $r->$col);
$cols[$col] = $r->$col; $cols[$col] = $r->$col;
} }
if(!isset($result[$hash])) if (!isset($result[$hash])) {
$result[$hash] = (object) array( $result[$hash] = (object)array(
"columns" => (object) $cols, "columns" => (object)$cols,
"count" => 0 "count" => 0
); );
}
$result[$hash]->count++; $result[$hash]->count++;
} }
} }
return array_values($result); return array_values($result);
} }
/**
* @return array
*/
public function getResult() public function getResult()
{ {
$indices = &$this->getFilteredIndices(); $indices = & $this->getFilteredIndices();
$this->orderIndices($indices); $this->orderIndices($indices);
if($this->groupByFn) { if ($this->groupByFn) {
$scope = $this->groupByFn[self::FN_SCOPE]; $scope = $this->groupByFn[self::FN_SCOPE];
$fn = $this->groupByFn[self::FN_NAME]; $fn = $this->groupByFn[self::FN_NAME];
return $scope->$fn($indices); return $scope->$fn($indices);
} }
$this->limitIndices($indices); $this->limitIndices($indices);
$result = array(); $result = array();
$state = &$this->reader->getObjects(); $state = & $this->reader->getObjects();
foreach ($indices as $type=>$subindices) { foreach ($indices as $type => $subindices) {
foreach($subindices as $index) { foreach ($subindices as $index) {
$result[] = &$state[$type][$index]; $result[] = & $state[$type][$index];
} }
} }
return $result; return $result;
} }
} }

View File

@ -1,89 +1,154 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat\Query; namespace Icinga\Protocol\Statusdat\Query;
class Expression implements IQueryPart class Expression implements IQueryPart
{ {
/**
*
*/
const ENC_NUMERIC = 0; const ENC_NUMERIC = 0;
/**
*
*/
const ENC_SET = 0; const ENC_SET = 0;
/**
*
*/
const ENC_STRING = 0; const ENC_STRING = 0;
/**
* @var string
*/
private $expression; private $expression;
/**
* @var null
*/
private $field = null; private $field = null;
/**
* @var array
*/
private $basedata = array(); private $basedata = array();
/**
* @var null
*/
private $function = null; private $function = null;
/**
* @var string
*/
private $value = ""; private $value = "";
/**
* @var null
*/
private $operator = null; private $operator = null;
/**
* @var null
*/
private $name = null; private $name = null;
/**
* @var null
*/
public $CB = null; public $CB = null;
/**
* @param $token
* @throws \Exception
*/
private function getOperatorType($token) private function getOperatorType($token)
{ {
switch (strtoupper($token)) { switch (strtoupper($token)) {
case ">": case ">":
$this->CB = "IS_GREATER"; $this->CB = "isGreater";
break; break;
case "<": case "<":
$this->CB = "IS_LESS"; $this->CB = "isLess";
break; break;
case ">=": case ">=":
$this->CB = "IS_GREATER_EQ"; $this->CB = "isGreaterEq";
break; break;
case "<=": case "<=":
$this->CB = "IS_LESS_EQ"; $this->CB = "isLessEq";
break; break;
case "=": case "=":
$this->CB = "IS_EQUAL"; $this->CB = "isEqual";
break; break;
case "LIKE": case "LIKE":
$this->CB = "IS_LIKE"; $this->CB = "isLike";
break; break;
case "!=": case "!=":
$this->CB = "IS_NOT_EQUAL"; $this->CB = "isNotEqual";
break; break;
case "IN": case "IN":
$this->CB = "IS_IN"; $this->CB = "isIn";
break; break;
default: default:
throw new \Exception("Unknown operator $token in expression $this->expression !"); throw new \Exception("Unknown operator $token in expression $this->expression !");
} }
} }
/**
private function extractAggregationFunction(&$tokens) { * @param $tokens
* @return mixed
*/
private function extractAggregationFunction(&$tokens)
{
$token = $tokens[0]; $token = $tokens[0];
$value = array(); $value = array();
if(preg_match("/COUNT\{(.*)\}/",$token,$value) == false) if (preg_match("/COUNT\{(.*)\}/", $token, $value) == false) {
return $token; return $token;
}
$this->function = "count"; $this->function = "count";
$tokens[0] = $value[1]; $tokens[0] = $value[1];
} }
/**
* @param $values
*/
private function parseExpression(&$values) private function parseExpression(&$values)
{ {
$tokenized = preg_split("/ +/", trim($this->expression), 3); $tokenized = preg_split("/ +/", trim($this->expression), 3);
$this->extractAggregationFunction($tokenized); $this->extractAggregationFunction($tokenized);
if (count($tokenized) != 3) if (count($tokenized) != 3) {
echo ("Currently statusdat query expressions must be in the format FIELD OPERATOR ? or FIELD OPERATOR :value_name"); echo(
"Currently statusdat query expressions must be in "
. "the format FIELD OPERATOR ? or FIELD OPERATOR :value_name"
);
}
$this->fields = explode(".",trim($tokenized[0])); $this->fields = explode(".", trim($tokenized[0]));
$this->field = $this->fields[count($this->fields)-1]; $this->field = $this->fields[count($this->fields) - 1];
$this->getOperatorType(trim($tokenized[1])); $this->getOperatorType(trim($tokenized[1]));
$tokenized[2] = trim($tokenized[2]); $tokenized[2] = trim($tokenized[2]);
if ($tokenized[2][0] === ":") { if ($tokenized[2][0] === ":") {
$this->name = substr($tokenized, 1); $this->name = substr($tokenized, 1);
$this->value = $values[$this->name]; $this->value = $values[$this->name];
} else if ($tokenized[2] === "?") {
$this->value = array_shift($values);
} else { } else {
$this->value = trim($tokenized[2]); if ($tokenized[2] === "?") {
$this->value = array_shift($values);
} else {
$this->value = trim($tokenized[2]);
}
} }
} }
/**
* @param $expression
* @param $values
* @return $this
*/
public function fromString($expression, &$values) public function fromString($expression, &$values)
{ {
$this->expression = $expression; $this->expression = $expression;
@ -91,61 +156,91 @@ class Expression implements IQueryPart
return $this; return $this;
} }
/**
* @param null $expression
* @param array $values
*/
public function __construct($expression = null, &$values = array()) public function __construct($expression = null, &$values = array())
{ {
if ($expression) if ($expression) {
$this->fromString($expression, $values); $this->fromString($expression, $values);
}
} }
/**
* @param array $base
* @param array $idx
* @return array|mixed
*/
public function filter(array &$base, &$idx = array()) public function filter(array &$base, &$idx = array())
{ {
if (!$idx) if (!$idx) {
$idx = array_keys($base); $idx = array_keys($base);
}
$this->basedata = $base; $this->basedata = $base;
return array_filter($idx, array($this,"filterFn")); return array_filter($idx, array($this, "filterFn"));
} }
/**
* @return string
*/
public function getValue() public function getValue()
{ {
return $this->value; return $this->value;
} }
/**
* @return null
*/
public function getField() public function getField()
{ {
return $this->field; return $this->field;
} }
protected function filterFn($idx) { /**
* @param $idx
* @return bool
*/
protected function filterFn($idx)
{
$values = $this->getFieldValues($idx); $values = $this->getFieldValues($idx);
if($values === False) if ($values === false) {
return false; return false;
}
if($this->CB == "IS_IN" ) { if ($this->CB == "IS_IN") {
return count(array_intersect($values,$this->value)) > 0; return count(array_intersect($values, $this->value)) > 0;
} }
if($this->CB == "IS_NOT_IN" ) if ($this->CB == "IS_NOT_IN") {
return count(array_intersect($values,$this->value)) == 0; return count(array_intersect($values, $this->value)) == 0;
if($this->function) { }
$values = call_user_func($this->function,$values); if ($this->function) {
if(!is_array($values)) $values = call_user_func($this->function, $values);
if (!is_array($values)) {
$values = array($values); $values = array($values);
}
} }
foreach($values as $val) foreach ($values as $val) {
if($this->{$this->CB}($val)) if ($this->{$this->CB}($val)) {
return true; return true;
}
}
return false; return false;
} }
/**
* @param $idx
private function getFieldValues($idx) { * @return array
*/
private function getFieldValues($idx)
{
$res = $this->basedata[$idx]; $res = $this->basedata[$idx];
foreach($this->fields as $field) { foreach ($this->fields as $field) {
if(!is_array($res)) { if (!is_array($res)) {
if(!isset($res->$field)) { if (!isset($res->$field)) {
$res = array(); $res = array();
break; break;
} }
@ -157,60 +252,87 @@ class Expression implements IQueryPart
// happens when using comments, in this case we have to create a new // happens when using comments, in this case we have to create a new
// array that contains the values/objects we're searching // array that contains the values/objects we're searching
$swap = array(); $swap = array();
foreach($res as $sub) { foreach ($res as $sub) {
if(!isset($sub->$field)) if (!isset($sub->$field)) {
continue; continue;
if(!is_array($sub->$field)) }
if (!is_array($sub->$field)) {
$swap[] = $sub->$field; $swap[] = $sub->$field;
else { } else {
$swap = array_merge($swap,$sub->$field); $swap = array_merge($swap, $sub->$field);
} }
} }
$res = $swap; $res = $swap;
} }
if(!is_array($res)) if (!is_array($res)) {
return array($res); return array($res);
}
return $res; return $res;
} }
public function IS_GREATER($value) /**
* @param $value
* @return bool
*/
public function isGreater($value)
{ {
return $value > $this->value; return $value > $this->value;
} }
public function IS_LESS($value) /**
* @param $value
* @return bool
*/
public function isLess($value)
{ {
return $value < $this->value; return $value < $this->value;
} }
public function IS_LIKE($value) /**
* @param $value
* @return bool
*/
public function isLike($value)
{ {
return preg_match("/^" . str_replace("%", ".*", $this->value) . "$/", $value) ? true : false;
return preg_match("/^".str_replace("%", ".*", $this->value)."$/", $value) ? true : false;
} }
public function IS_EQUAL($value) /**
* @param $value
* @return bool
*/
public function isEqual($value)
{ {
if(!is_numeric($value)) if (!is_numeric($value)) {
return strtolower($value) ==strtolower($this->value); return strtolower($value) == strtolower($this->value);
}
return $value == $this->value; return $value == $this->value;
} }
public function IS_NOT_EQUAL($value) /**
* @param $value
* @return bool
*/
public function isNotEqual($value)
{ {
return $value != $this->value; return $value != $this->value;
} }
public function IS_GREATER_EQ($value) /**
* @param $value
* @return bool
*/
public function isGreaterEq($value)
{ {
return $value >= $this->value; return $value >= $this->value;
} }
public function IS_LESS_EQ($value) /**
* @param $value
* @return bool
*/
public function isLessEq($value)
{ {
return $value <= $this->value; return $value <= $this->value;
} }
}
}

View File

@ -1,49 +1,130 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat\Query; namespace Icinga\Protocol\Statusdat\Query;
/**
* Class Group
* @package Icinga\Protocol\Statusdat\Query
*/
class Group implements IQueryPart class Group implements IQueryPart
{ {
/**
*
*/
const GROUP_BEGIN = "("; const GROUP_BEGIN = "(";
/**
*
*/
const GROUP_END = ")"; const GROUP_END = ")";
/**
*
*/
const CONJUNCTION_AND = "AND "; const CONJUNCTION_AND = "AND ";
/**
*
*/
const CONJUNCTION_OR = "OR "; const CONJUNCTION_OR = "OR ";
/**
*
*/
const EXPRESSION = 0; const EXPRESSION = 0;
/**
*
*/
const EOF = -1; const EOF = -1;
/**
*
*/
const TYPE_AND = "AND"; const TYPE_AND = "AND";
/**
*
*/
const TYPE_OR = "OR"; const TYPE_OR = "OR";
/**
* @var array
*/
private $items = array(); private $items = array();
/**
* @var int
*/
private $parsePos = 0; private $parsePos = 0;
/**
* @var string
*/
private $expression = ""; private $expression = "";
/**
* @var null
*/
private $expressionClass = null; private $expressionClass = null;
/**
* @var string
*/
private $type = ""; private $type = "";
/**
* @var int
*/
private $subExpressionStart = 0; private $subExpressionStart = 0;
/**
* @var int
*/
private $subExpressionLength = 0; private $subExpressionLength = 0;
/**
* @var
*/
private $value; private $value;
/**
* @param $value
*/
public function setValue($value) public function setValue($value)
{ {
$this->value = $value; $this->value = $value;
} }
/**
* @return array
*/
public function getItems() public function getItems()
{ {
return $this->items; return $this->items;
} }
/**
* @return string
*/
public function getType() public function getType()
{ {
return $this->type ? $this->type : self::TYPE_AND; return $this->type ? $this->type : self::TYPE_AND;
} }
/**
* @param $type
*/
public function setType($type) public function setType($type)
{ {
$this->type = $type; $this->type = $type;
} }
/**
* @throws \Exception
*/
private function tokenize() private function tokenize()
{ {
$token = 0; $token = 0;
@ -54,17 +135,28 @@ class Group implements IQueryPart
if ($token === self::GROUP_BEGIN) { if ($token === self::GROUP_BEGIN) {
if ($subgroupCount == 0) // check if this is a nested group, if so then it's considered part of the subexpression /**
* check if this is a nested group, if so then it's
* considered part of the subexpression
*/
if ($subgroupCount == 0) {
$this->startNewSubExpression(); $this->startNewSubExpression();
}
$subgroupCount++; $subgroupCount++;
continue; continue;
} }
if ($token === self::GROUP_END) { if ($token === self::GROUP_END) {
if ($subgroupCount < 1) if ($subgroupCount < 1) {
throw new \Exception("Invalid Query: unexpected ')' at pos " . $this->parsePos); throw new \Exception("Invalid Query: unexpected ')' at pos " . $this->parsePos);
}
$subgroupCount--; $subgroupCount--;
if ($subgroupCount == 0) // check if this is a nested group, if so then it's considered part of the subexpression /*
* check if this is a nested group, if so then it's
* considered part of the subexpression
*/
if ($subgroupCount == 0) {
$this->addSubgroupFromExpression(); $this->addSubgroupFromExpression();
}
continue; continue;
} }
@ -92,12 +184,16 @@ class Group implements IQueryPart
$this->subExpressionLength = $this->parsePos - $this->subExpressionStart; $this->subExpressionLength = $this->parsePos - $this->subExpressionStart;
} }
if ($subgroupCount > 0) if ($subgroupCount > 0) {
throw new \Exception("Unexpected end of query, are you missing a parenthesis?"); throw new \Exception("Unexpected end of query, are you missing a parenthesis?");
}
$this->startNewSubExpression(); $this->startNewSubExpression();
} }
/**
* @param $type
*/
private function createImplicitGroup($type) private function createImplicitGroup($type)
{ {
$group = new Group(); $group = new Group();
@ -110,25 +206,35 @@ class Group implements IQueryPart
} }
/**
*
*/
private function startNewSubExpression() private function startNewSubExpression()
{ {
if ($this->getCurrentSubExpression() != "") { if ($this->getCurrentSubExpression() != "") {
if (!$this->expressionClass) if (!$this->expressionClass) {
$this->items[] = new Expression($this->getCurrentSubExpression(), $this->value); $this->items[] = new Expression($this->getCurrentSubExpression(), $this->value);
else } else {
$this->items[] = new $this->expressionClass($this->getCurrentSubExpression(), $this->value); $this->items[] = new $this->expressionClass($this->getCurrentSubExpression(), $this->value);
}
} }
$this->subExpressionStart = $this->parsePos; $this->subExpressionStart = $this->parsePos;
$this->subExpressionLength = 0; $this->subExpressionLength = 0;
} }
/**
* @return string
*/
private function getCurrentSubExpression() private function getCurrentSubExpression()
{ {
return substr($this->expression, $this->subExpressionStart, $this->subExpressionLength); return substr($this->expression, $this->subExpressionStart, $this->subExpressionLength);
} }
/**
*
*/
private function addSubgroupFromExpression() private function addSubgroupFromExpression()
{ {
@ -143,23 +249,32 @@ class Group implements IQueryPart
$this->subExpressionLength = 0; $this->subExpressionLength = 0;
} }
/**
* @return bool
*/
private function isEOF() private function isEOF()
{ {
if ($this->parsePos >= strlen($this->expression)) if ($this->parsePos >= strlen($this->expression)) {
return true; return true;
}
return false; return false;
} }
/**
* @return int|string
*/
private function getNextToken() private function getNextToken()
{ {
if ($this->isEOF()) if ($this->isEOF()) {
return self::EOF; return self::EOF;
}
// skip whitespaces // skip whitespaces
while ($this->expression[$this->parsePos] == " ") { while ($this->expression[$this->parsePos] == " ") {
$this->parsePos++; $this->parsePos++;
if ($this->isEOF()) if ($this->isEOF()) {
return self::EOF; return self::EOF;
}
} }
if ($this->expression[$this->parsePos] == self::GROUP_BEGIN) { if ($this->expression[$this->parsePos] == self::GROUP_BEGIN) {
$this->parsePos++; $this->parsePos++;
@ -169,11 +284,23 @@ class Group implements IQueryPart
$this->parsePos++; $this->parsePos++;
return self::GROUP_END; return self::GROUP_END;
} }
if (substr_compare($this->expression, self::CONJUNCTION_AND, $this->parsePos, strlen(self::CONJUNCTION_AND), true) === 0) { if (substr_compare(
$this->expression,
self::CONJUNCTION_AND,
$this->parsePos,
strlen(self::CONJUNCTION_AND),
true
) === 0) {
$this->parsePos += strlen(self::CONJUNCTION_AND); $this->parsePos += strlen(self::CONJUNCTION_AND);
return self::CONJUNCTION_AND; return self::CONJUNCTION_AND;
} }
if (substr_compare($this->expression, self::CONJUNCTION_OR, $this->parsePos, strlen(self::CONJUNCTION_OR), true) === 0) { if (substr_compare(
$this->expression,
self::CONJUNCTION_OR,
$this->parsePos,
strlen(self::CONJUNCTION_OR),
true
) === 0) {
$this->parsePos += strlen(self::CONJUNCTION_OR); $this->parsePos += strlen(self::CONJUNCTION_OR);
return self::CONJUNCTION_OR; return self::CONJUNCTION_OR;
} }
@ -181,12 +308,22 @@ class Group implements IQueryPart
return self::EXPRESSION; return self::EXPRESSION;
} }
/**
* @param $ex
* @return $this
*/
public function addItem($ex) public function addItem($ex)
{ {
$this->items[] = $ex; $this->items[] = $ex;
return $this; return $this;
} }
/**
* @param $expression
* @param array $value
* @param null $expressionClass
* @return $this
*/
public function fromString($expression, &$value = array(), $expressionClass = null) public function fromString($expression, &$value = array(), $expressionClass = null)
{ {
$this->expression = $expression; $this->expression = $expression;
@ -197,24 +334,33 @@ class Group implements IQueryPart
return $this; return $this;
} }
/**
* @param null $expression
* @param array $value
*/
public function __construct($expression = null, &$value = array()) public function __construct($expression = null, &$value = array())
{ {
if ($expression) if ($expression) {
$this->fromString($expression, $value); $this->fromString($expression, $value);
}
} }
/**
* @param array $base
* @param null $idx
* @return array|null
*/
public function filter(array &$base, &$idx = null) public function filter(array &$base, &$idx = null)
{ {
if ($this->type == self::TYPE_OR) { if ($this->type == self::TYPE_OR) {
$idx = array(); $idx = array();
foreach ($this->items as &$subFilter) { foreach ($this->items as &$subFilter) {
$idx += $subFilter->filter($base, array_keys($base)); $idx += $subFilter->filter($base, array_keys($base));
} }
} else { } else {
if (!$idx) if (!$idx) {
$idx = array_keys($base); $idx = array_keys($base);
}
foreach ($this->items as $subFilter) { foreach ($this->items as $subFilter) {
$idx = array_intersect($idx, $subFilter->filter($base, $idx)); $idx = array_intersect($idx, $subFilter->filter($base, $idx));
} }
@ -223,4 +369,3 @@ class Group implements IQueryPart
return $idx; return $idx;
} }
} }

View File

@ -1,10 +1,25 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat\Query; namespace Icinga\Protocol\Statusdat\Query;
/**
* Class IQueryPart
* @package Icinga\Protocol\Statusdat\Query
*/
interface IQueryPart interface IQueryPart
{ {
public function __construct($expression = null,&$value = array()); /**
public function filter(array &$base, &$idx=null); * @param null $expression
* @param array $value
*/
public function __construct($expression = null, &$value = array());
/**
* @param array $base
* @param null $idx
* @return mixed
*/
public function filter(array &$base, &$idx = null);
} }

View File

@ -1,121 +1,145 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat; namespace Icinga\Protocol\Statusdat;
use Icinga\Exception as Exception; use Icinga\Exception as Exception;
use Icinga\Benchmark as Benchmark; use Icinga\Benchmark as Benchmark;
class ObjectContainer extends \stdClass { /**
public $ref; * Class Reader
public $reader; * @package Icinga\Protocol\Statusdat
*/
public function __construct(\stdClass &$obj,IReader &$reader) {
$this->ref = &$obj;
$this->reader = &$reader;
}
public function __get($attribute) {
$exploded = explode(".",$attribute);
$result = $this->ref;
foreach($exploded as $elem) {
$result = $result->$elem;
}
return $result;
}
}
class Reader implements IReader class Reader implements IReader
{ {
/**
*
*/
const DEFAULT_CACHE_LIFETIME = 300; const DEFAULT_CACHE_LIFETIME = 300;
/**
*
*/
const STATUSDAT_DEFAULT_CACHE_PATH = "/cache"; const STATUSDAT_DEFAULT_CACHE_PATH = "/cache";
/**
* @var null
*/
private $lastState = null; private $lastState = null;
/**
* @var bool
*/
private $hasRuntimeState = false; private $hasRuntimeState = false;
/**
* @var null
*/
private $objectCache = null; private $objectCache = null;
/**
* @var null
*/
private $statusCache = null; private $statusCache = null;
/**
* @var bool
*/
private $newState = false; private $newState = false;
/**
* @var null
*/
private $parser = null; private $parser = null;
/**
* @var bool
*/
private $noCache = false; private $noCache = false;
/**
* @param $config
* @param null $parser
* @param bool $noCache
*/
public function __construct($config = \Zend_Config, $parser = null, $noCache = false) public function __construct($config = \Zend_Config, $parser = null, $noCache = false)
{ {
$this->noCache = $noCache; $this->noCache = $noCache;
$this->config = $config; $this->config = $config;
$this->parser = $parser; $this->parser = $parser;
if(!$noCache) { if (!$noCache) {
$this->cache = $this->initializeCaches($config); $this->cache = $this->initializeCaches($config);
if($this->fromCache()) { if ($this->fromCache()) {
$this->createHostServiceConnections(); $this->createHostServiceConnections();
return; return;
} }
} }
if(!$this->lastState) if (!$this->lastState) {
$this->parseObjectsCacheFile(); $this->parseObjectsCacheFile();
if(!$this->hasRuntimeState); }
$this->parseStatusDatFile(); if (!$this->hasRuntimeState) {
if(!$noCache && $this->newState) ;
$this->statusCache->save($this->parser->getRuntimeState(),'objects'.md5($this->config->objects_file)); }
$this->parseStatusDatFile();
if (!$noCache && $this->newState) {
$this->statusCache->save($this->parser->getRuntimeState(), 'objects' . md5($this->config->objects_file));
}
$this->createHostServiceConnections(); $this->createHostServiceConnections();
} }
private function createHostServiceConnections() /**
* @throws Exception\ConfigurationError
*/
private function initializeCaches()
{ {
if (!isset($this->lastState["service"])) { $defaultCachePath = "/tmp/" . self::STATUSDAT_DEFAULT_CACHE_PATH;
return;
$cachePath = $this->config->get('cache_path', $defaultCachePath);
$maxCacheLifetime = intval($this->config->get('cache_path', self::DEFAULT_CACHE_LIFETIME));
if (!is_writeable($cachePath)) {
throw new Exception\ConfigurationError(
"Cache path $cachePath is not writable, check your configuration"
);
} }
foreach ($this->lastState["service"] as &$service) {
$host = &$this->lastState["host"][$service->host_name];
if(!isset($host->services))
$host->services = array();
$host->services[$service->service_description] = &$service;
$service->host = &$host;
}
}
public function select() $backendOptions = array(
{ 'cache_dir' => $cachePath
return new Query($this);
}
public function fetchAll(Query $query)
{
return new \Icinga\Backend\MonitoringObjectList(
$query->getResult(),
$query->getView()
); );
// the objects cache might exist for months and is still valid
$this->objectCache = $this->initCache($this->config->objects_file, $backendOptions, null);
$this->statusCache = $this->initCache($this->config->status_file, $backendOptions, $maxCacheLifetime);
} }
public function getState() /**
* @param $file
* @param $backend
* @param $lifetime
* @return \Zend_Cache_Core|\Zend_Cache_Frontend
*/
private function initCache($file, $backend, $lifetime)
{ {
return $this->lastState; $frontendOptions = array(
} 'lifetime' => $lifetime,
'automatic_serialization' => true,
public function getObjects() 'master_files' => array($file)
{ );
return $this->lastState; return \Zend_Cache::factory('Core', 'File', $frontendOptions, $backend);
}
public function getObjectByName($type, $name)
{
if (isset($this->lastState[$type]) && isset($this->lastState[$type][$name]))
return new ObjectContainer($this->lastState[$type][$name],$this);
return null;
}
public function getObjectNames($type) {
return isset($this->lastState[$type]) ? array_keys($this->lastState[$type]) : null;
} }
/**
* @return bool
*/
private function fromCache() private function fromCache()
{ {
if(!$this->readObjectsCache()) { if (!$this->readObjectsCache()) {
$this->newState = true; $this->newState = true;
return false; return false;
} }
if(!$this->readStatusCache()){ if (!$this->readStatusCache()) {
$this->newState = true; $this->newState = true;
return false; return false;
} }
@ -124,71 +148,140 @@ class Reader implements IReader
return true; return true;
} }
/**
* @return bool
*/
private function readObjectsCache() private function readObjectsCache()
{ {
$this->lastState = $this->objectCache->load('objects'.md5($this->config->objects_file)); $this->lastState = $this->objectCache->load('objects' . md5($this->config->objects_file));
if($this->lastState == false) if ($this->lastState == false) {
return false; return false;
}
} }
/**
* @return bool
*/
private function readStatusCache() private function readStatusCache()
{ {
$statusInfo = $this->stateCache->load('state'.md5($this->config->status_file)); $statusInfo = $this->stateCache->load('state' . md5($this->config->status_file));
if($statusInfo == false) if ($statusInfo == false) {
return false; return false;
}
$this->hasRuntimeState = true; $this->hasRuntimeState = true;
} }
private function initializeCaches() /**
*
*/
private function createHostServiceConnections()
{ {
$defaultCachePath = "/tmp/".self::STATUSDAT_DEFAULT_CACHE_PATH; if (!isset($this->lastState["service"])) {
return;
$cachePath = $this->config->get('cache_path',$defaultCachePath); }
$maxCacheLifetime = intval($this->config->get('cache_path',self::DEFAULT_CACHE_LIFETIME));
if(!is_writeable($cachePath))
throw new \Icinga\Exception\ConfigurationError("Cache path $cachePath is not writable, check your configuration");
$backendOptions = array(
'cache_dir' => $cachePath
);
// the objects cache might exist for months and is still valid
$this->objectCache = $this->initCache($this->config->objects_file,$backendOptions,NULL);
$this->statusCache = $this->initCache($this->config->status_file,$backendOptions,$maxCacheLifetime);
foreach ($this->lastState["service"] as &$service) {
$host = & $this->lastState["host"][$service->host_name];
if (!isset($host->services)) {
$host->services = array();
}
$host->services[$service->service_description] = & $service;
$service->host = & $host;
}
} }
private function initCache($file, $backend, $lifetime) /**
{ * @throws Exception\ConfigurationError
$frontendOptions = array( */
'lifetime' => $lifetime,
'automatic_serialization' => true,
'master_files' => array($file)
);
return \Zend_Cache::factory('Core','File',$frontendOptions,$backend);
}
private function parseObjectsCacheFile() private function parseObjectsCacheFile()
{ {
if(!is_readable($this->config->objects_file)) if (!is_readable($this->config->objects_file)) {
throw new \Icinga\Exception\ConfigurationError("Can't read objects-file {$this->config->objects_file}, check your configuration"); throw new Exception\ConfigurationError(
if(!$this->parser) "Can't read objects-file {$this->config->objects_file}, check your configuration"
$this->parser = new Parser(fopen($this->config->objects_file,"r")); );
}
if (!$this->parser) {
$this->parser = new Parser(fopen($this->config->objects_file, "r"));
}
$this->parser->parseObjectsFile(); $this->parser->parseObjectsFile();
$this->lastState = &$this->parser->getRuntimeState(); $this->lastState = & $this->parser->getRuntimeState();
} }
/**
* @throws Exception\ConfigurationError
*/
private function parseStatusDatFile() private function parseStatusDatFile()
{ {
if(!is_readable($this->config->status_file)) if (!is_readable($this->config->status_file)) {
throw new \Icinga\Exception\ConfigurationError("Can't read status-file {$this->config->status_file}, check your configuration"); throw new Exception\ConfigurationError(
if(!$this->parser) "Can't read status-file {$this->config->status_file}, check your configuration"
$this->parser = new Parser(fopen($this->config->status_file,"r"),$this->lastState); );
$this->parser->parseRuntimeState(fopen($this->config->status_file,"r")); }
$this->lastState = &$this->parser->getRuntimeState(); if (!$this->parser) {
if(!$this->noCache) $this->parser = new Parser(fopen($this->config->status_file, "r"), $this->lastState);
$this->statusCache->save(array("true" => true),"state".md5($this->config->objects_file)); }
$this->parser->parseRuntimeState(fopen($this->config->status_file, "r"));
$this->lastState = & $this->parser->getRuntimeState();
if (!$this->noCache) {
$this->statusCache->save(array("true" => true), "state" . md5($this->config->objects_file));
}
} }
/**
* @return Query
*/
public function select()
{
return new Query($this);
}
/**
* @param Query $query
* @return \Icinga\Backend\MonitoringObjectList
*/
public function fetchAll(Query $query)
{
return new \Icinga\Backend\MonitoringObjectList(
$query->getResult(),
$query->getView()
);
}
/**
* @return mixed|null
*/
public function getState()
{
return $this->lastState;
}
/**
* @return mixed|null
*/
public function getObjects()
{
return $this->lastState;
}
/**
* @param $type
* @param $name
* @return ObjectContainer|mixed|null
*/
public function getObjectByName($type, $name)
{
if (isset($this->lastState[$type]) && isset($this->lastState[$type][$name])) {
return new ObjectContainer($this->lastState[$type][$name], $this);
}
return null;
}
/**
* @param $type
* @return array|null
*/
public function getObjectNames($type)
{
return isset($this->lastState[$type]) ? array_keys($this->lastState[$type]) : null;
}
} }

View File

@ -1,34 +1,57 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Statusdat; namespace Icinga\Protocol\Statusdat;
/**
* Class RuntimeStateContainer
* @package Icinga\Protocol\Statusdat
*/
class RuntimeStateContainer extends \stdClass class RuntimeStateContainer extends \stdClass
{ {
/**
* @var string
*/
public $runtimeState = ""; public $runtimeState = "";
public function __construct($str = "") {
/**
* @param string $str
*/
public function __construct($str = "")
{
$this->runtimeState = $str; $this->runtimeState = $str;
} }
/**
* @param $attr
* @return bool
*/
public function __isset($attr) public function __isset($attr)
{ {
try { try {
$this->__get($attr); $this->__get($attr);
return true; return true;
} catch(\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
return false; return false;
} }
} }
/**
* @param $attr
* @return mixed
* @throws \InvalidArgumentException
*/
public function __get($attr) public function __get($attr)
{ {
$start = strpos($this->runtimeState, $attr . "=");
$start = strpos($this->runtimeState,$attr."="); if ($start === false) {
if($start === False)
throw new \InvalidArgumentException("Unknown property $attr"); throw new \InvalidArgumentException("Unknown property $attr");
}
$start += strlen($attr."="); $start += strlen($attr . "=");
$len = strpos($this->runtimeState,"\n",$start) - $start; $len = strpos($this->runtimeState, "\n", $start) - $start;
$this->$attr = trim(substr($this->runtimeState,$start,$len)); $this->$attr = trim(substr($this->runtimeState, $start, $len));
return $this->$attr; return $this->$attr;
} }

View File

@ -1,8 +1,7 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
/**
* Action controller
*/
namespace Icinga\Web; namespace Icinga\Web;
use Icinga\Authentication\Auth; use Icinga\Authentication\Auth;
@ -24,6 +23,7 @@ use Zend_Controller_Action_HelperBroker as ZfActionHelper;
* @copyright Copyright (c) 2013 Icinga-Web Team <info@icinga.org> * @copyright Copyright (c) 2013 Icinga-Web Team <info@icinga.org>
* @author Icinga-Web Team <info@icinga.org> * @author Icinga-Web Team <info@icinga.org>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
* @package Icinga\Web
*/ */
class ActionController extends ZfController class ActionController extends ZfController
{ {
@ -35,6 +35,9 @@ class ActionController extends ZfController
*/ */
protected $config; protected $config;
/**
* @var bool
*/
protected $replaceLayout = false; protected $replaceLayout = false;
/** /**
@ -59,10 +62,19 @@ class ActionController extends ZfController
*/ */
protected $action_name; protected $action_name;
/**
* @var bool
*/
protected $handlesAuthentication = false; protected $handlesAuthentication = false;
/**
* @var bool
*/
protected $modifiesSession = false; protected $modifiesSession = false;
/**
* @var bool
*/
protected $allowAccess = false; protected $allowAccess = false;
/** /**
@ -80,23 +92,24 @@ class ActionController extends ZfController
) { ) {
Benchmark::measure('Action::__construct()'); Benchmark::measure('Action::__construct()');
if (Auth::getInstance()->isAuthenticated() if (Auth::getInstance()->isAuthenticated()
&& ! $this->modifiesSession && !$this->modifiesSession
&& ! Notification::getInstance()->hasMessages() && !Notification::getInstance()->hasMessages()
) { ) {
session_write_close(); session_write_close();
} }
$this->module_name = $request->getModuleName(); $this->module_name = $request->getModuleName();
$this->controller_name = $request->getControllerName(); $this->controller_name = $request->getControllerName();
$this->action_name = $request->getActionName(); $this->action_name = $request->getActionName();
$this->loadConfig(); $this->loadConfig();
$this->setRequest($request) $this->setRequest($request)
->setResponse($response) ->setResponse($response)
->_setInvokeArgs($invokeArgs); ->_setInvokeArgs($invokeArgs);
$this->_helper = new ZfActionHelper($this); $this->_helper = new ZfActionHelper($this);
if ($this->handlesAuthentication() if ($this->handlesAuthentication()
|| Auth::getInstance()->isAuthenticated()) { || Auth::getInstance()->isAuthenticated()
) {
$this->allowAccess = true; $this->allowAccess = true;
$this->init(); $this->init();
} }
@ -128,7 +141,7 @@ class ActionController extends ZfController
* Helper function creating a new widget * Helper function creating a new widget
* *
* @param string $name The widget name * @param string $name The widget name
* @param string $properties Optional widget properties * @param array|string $properties Optional widget properties
* *
* @return Widget\AbstractWidget * @return Widget\AbstractWidget
*/ */
@ -142,8 +155,9 @@ class ActionController extends ZfController
* *
* TODO: This has not been implemented yet * TODO: This has not been implemented yet
* *
* @param $uri
* @param string $permission Permission name * @param string $permission Permission name
* @param string $object No idea what this should have been :-) * @internal param string $object No idea what this should have been :-)
* *
* @return bool * @return bool
*/ */
@ -160,11 +174,12 @@ class ActionController extends ZfController
* @param string $permission Permission name * @param string $permission Permission name
* @param string $object No idea what this should have been :-) * @param string $object No idea what this should have been :-)
* *
* @throws \Exception
* @return self * @return self
*/ */
final protected function assertPermission($permission, $object = null) final protected function assertPermission($permission, $object = null)
{ {
if (! $this->hasPermission($permission, $object)) { if (!$this->hasPermission($permission, $object)) {
// TODO: Log violation, create dedicated Exception class // TODO: Log violation, create dedicated Exception class
throw new \Exception('Permission denied'); throw new \Exception('Permission denied');
} }
@ -179,7 +194,7 @@ class ActionController extends ZfController
public function preDispatch() public function preDispatch()
{ {
Benchmark::measure('Action::preDispatch()'); Benchmark::measure('Action::preDispatch()');
if (! $this->allowAccess) { if (!$this->allowAccess) {
$this->_request->setModuleName('default') $this->_request->setModuleName('default')
->setControllerName('authentication') ->setControllerName('authentication')
->setActionName('login') ->setActionName('login')
@ -194,11 +209,18 @@ class ActionController extends ZfController
//$this->quickRedirect('/authentication/login?a=e'); //$this->quickRedirect('/authentication/login?a=e');
} }
/**
* @param $url
* @param array $params
*/
public function redirectNow($url, array $params = array()) public function redirectNow($url, array $params = array())
{ {
$this->_helper->Redirector->gotoUrlAndExit($url); $this->_helper->Redirector->gotoUrlAndExit($url);
} }
/**
* @return bool
*/
public function handlesAuthentication() public function handlesAuthentication()
{ {
return $this->handlesAuthentication; return $this->handlesAuthentication;
@ -212,8 +234,8 @@ class ActionController extends ZfController
protected function renderBenchmark() protected function renderBenchmark()
{ {
return '<pre class="benchmark">' return '<pre class="benchmark">'
. Benchmark::renderToHtml() . Benchmark::renderToHtml()
. '</pre>'; . '</pre>';
} }
/** /**
@ -230,41 +252,41 @@ class ActionController extends ZfController
public function postDispatch() public function postDispatch()
{ {
Benchmark::measure('Action::postDispatch()'); Benchmark::measure('Action::postDispatch()');
// TODO: Move this elsewhere, this is just an ugly test: // TODO: Move this elsewhere, this is just an ugly test:
if ($this->_request->getParam('filetype') === 'pdf') { if ($this->_request->getParam('filetype') === 'pdf') {
// Snippet stolen from less compiler in public/css.php: // Snippet stolen from less compiler in public/css.php:
require_once 'vendor/lessphp/lessc.inc.php'; require_once 'vendor/lessphp/lessc.inc.php';
$less = new \lessc; $less = new \lessc;
$cssdir = dirname(ICINGA_LIBDIR) . '/public/css'; $cssdir = dirname(ICINGA_LIBDIR) . '/public/css';
// TODO: We need a way to retrieve public dir, even if located elsewhere // TODO: We need a way to retrieve public dir, even if located elsewhere
$css = $less->compileFile($cssdir . '/pdfprint.less'); $css = $less->compileFile($cssdir . '/pdfprint.less');
/* /*
foreach ($app->moduleManager()->getLoadedModules() as $name => $module) { foreach ($app->moduleManager()->getLoadedModules() as $name => $module) {
if ($module->hasCss()) { if ($module->hasCss()) {
$css .= $less->compile( $css .= $less->compile(
'.icinga-module.module-' '.icinga-module.module-'
. $name . $name
. " {\n" . " {\n"
. file_get_contents($module->getCssFilename()) . file_get_contents($module->getCssFilename())
. "}\n\n" . "}\n\n"
); );
} }
} }
*/ */
// END of CSS test // END of CSS test
$this->render( $this->render(
null, null,
$this->_helper->viewRenderer->getResponseSegment(), $this->_helper->viewRenderer->getResponseSegment(),
$this->_helper->viewRenderer->getNoController() $this->_helper->viewRenderer->getNoController()
); );
$html = '<style>' . $css . '</style>' . (string) $this->getResponse(); $html = '<style>' . $css . '</style>' . (string)$this->getResponse();
$pdf = new \Icinga\Pdf\File(); $pdf = new \Icinga\Pdf\File();
$pdf->AddPage(); $pdf->AddPage();
@ -273,8 +295,8 @@ class ActionController extends ZfController
exit; exit;
} }
// END of PDF test // END of PDF test
if ($this->_request->isXmlHttpRequest()) { if ($this->_request->isXmlHttpRequest()) {
if ($this->replaceLayout || $this->_getParam('_render') === 'body') { if ($this->replaceLayout || $this->_getParam('_render') === 'body') {
$this->_helper->layout()->setLayout('just-the-body'); $this->_helper->layout()->setLayout('just-the-body');
@ -288,9 +310,9 @@ class ActionController extends ZfController
$nhtml = '<ul class="notification">'; $nhtml = '<ul class="notification">';
foreach ($notification->getMessages() as $msg) { foreach ($notification->getMessages() as $msg) {
$nhtml .= '<li>[' $nhtml .= '<li>['
. $msg->type . $msg->type
. '] ' . '] '
. htmlspecialchars($msg->message); . htmlspecialchars($msg->message);
} }
$nhtml .= '</ul>'; $nhtml .= '</ul>';
$this->getResponse()->append('notification', $nhtml); $this->getResponse()->append('notification', $nhtml);
@ -308,16 +330,15 @@ class ActionController extends ZfController
* *
* TODO: Could this make use of Icinga\Web\Session once done? * TODO: Could this make use of Icinga\Web\Session once done?
* *
* @param int $maxAge Max allowed token age * @param int $maxAge Max allowed token age
* @param string $sessionId A specific session id (useful for tests?) * @param string $sessionId A specific session id (useful for tests?)
* * @return bool
* return bool
*/ */
public function hasValidToken($maxAge = 600, $sessionId = null) public function hasValidToken($maxAge = 600, $sessionId = null)
{ {
$sessionId = $sessionId ? $sessionId : session_id(); $sessionId = $sessionId ? $sessionId : session_id();
$seed = $this->_getParam('seed'); $seed = $this->_getParam('seed');
if (! is_numeric($seed)) { if (!is_numeric($seed)) {
return false; return false;
} }
@ -332,10 +353,10 @@ class ActionController extends ZfController
* *
* TODO: Could this make use of Icinga\Web\Session once done? * TODO: Could this make use of Icinga\Web\Session once done?
* *
* @param int $maxAge Max allowed token age * @param int $maxAge Max allowed token age
* @param string $sessionId A specific session id (useful for tests?) * @param string $sessionId A specific session id (useful for tests?)
* *
* return array * @return array
*/ */
public function getSeedTokenPair($maxAge = 600, $sessionId = null) public function getSeedTokenPair($maxAge = 600, $sessionId = null)
{ {

View File

@ -1,15 +1,32 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Web; namespace Icinga\Web;
use Icinga\Application\Logger as Log; use Icinga\Application\Logger as Log;
use Icinga\Exception\ProgrammingError; use Icinga\Exception\ProgrammingError;
class Hook class Hook
{ {
/**
* @var array
*/
protected static $hooks = array(); protected static $hooks = array();
/**
* @var array
*/
protected static $instances = array(); protected static $instances = array();
/**
* @var string
*/
public static $BASE_NS = 'Icinga\\Web\\Hook\\'; public static $BASE_NS = 'Icinga\\Web\\Hook\\';
/**
*
*/
public static function clean() public static function clean()
{ {
self::$hooks = array(); self::$hooks = array();
@ -17,7 +34,12 @@ class Hook
self::$BASE_NS = 'Icinga\\Web\\Hook\\'; self::$BASE_NS = 'Icinga\\Web\\Hook\\';
} }
public static function has($name,$key=null) /**
* @param $name
* @param null $key
* @return bool
*/
public static function has($name, $key = null)
{ {
if ($key !== null) { if ($key !== null) {
return isset(self::$hooks[$name][$key]); return isset(self::$hooks[$name][$key]);
@ -26,9 +48,14 @@ class Hook
} }
} }
public static function createInstance($name,$key) /**
* @param $name
* @param $key
* @return null
*/
public static function createInstance($name, $key)
{ {
if (!self::has($name,$key)) { if (!self::has($name, $key)) {
return null; return null;
} }
if (isset(self::$instances[$name][$key])) { if (isset(self::$instances[$name][$key])) {
@ -48,43 +75,63 @@ class Hook
unset(self::$hooks[$name][$key]); unset(self::$hooks[$name][$key]);
return null; return null;
} }
self::assertValidHook($instance,$name); self::assertValidHook($instance, $name);
self::$instances[$name][$key] = $instance; self::$instances[$name][$key] = $instance;
return $instance; return $instance;
} }
/**
* @param $instance
* @param $name
* @throws \Icinga\Exception\ProgrammingError
*/
private static function assertValidHook(&$instance, $name) private static function assertValidHook(&$instance, $name)
{ {
$base_class = self::$BASE_NS.ucfirst($name); $base_class = self::$BASE_NS . ucfirst($name);
if (! $instance instanceof $base_class) { if (!$instance instanceof $base_class) {
throw new ProgrammingError(sprintf( throw new ProgrammingError(
'%s is not an instance of %s', sprintf(
get_class($instance), '%s is not an instance of %s',
$base_class get_class($instance),
)); $base_class
)
);
} }
} }
/**
* @param $name
* @return array
*/
public static function all($name) public static function all($name)
{ {
if (!self::has($name)) { if (!self::has($name)) {
return array(); return array();
} }
foreach (self::$hooks[$name] as $key=>$hook) { foreach (self::$hooks[$name] as $key => $hook) {
if(self::createInstance($name,$key) === null) if (self::createInstance($name, $key) === null) {
return array(); return array();
}
} }
return self::$instances[$name]; return self::$instances[$name];
} }
/**
* @param $name
* @return null
*/
public static function first($name) public static function first($name)
{ {
return self::createInstance($name,key(self::$hooks[$name])); return self::createInstance($name, key(self::$hooks[$name]));
} }
/**
* @param $name
* @param $key
* @param $class
*/
public static function register($name, $key, $class) public static function register($name, $key, $class)
{ {
self::$hooks[$name][$key] = $class; self::$hooks[$name][$key] = $class;
} }
} }

View File

@ -24,12 +24,12 @@ class ExpressionTest extends \PHPUnit_Framework_TestCase
{ {
$assertions = array( $assertions = array(
"expression > ?" => "IS_GREATER", "expression > ?" => "IS_GREATER",
"expression >= ?" => "IS_GREATER_EQ", "expression >= ?" => "isGreaterEq",
"expression <= ?" => "IS_LESS_EQ", "expression <= ?" => "isLessEq",
"expression < ?" => "IS_LESS", "expression < ?" => "isLess",
"expression = ?" => "IS_EQUAL", "expression = ?" => "isEqual",
"expression != ?" => "IS_NOT_EQUAL", "expression != ?" => "isNotEqual",
"expression like ?" => "IS_LIKE", "expression like ?" => "isLike",
"expression IN ? " => "IS_IN" "expression IN ? " => "IS_IN"
); );