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);
/**
* @return bool
*/
public function hasOrder() public function hasOrder()
{ {
return false; return false;
} }
/**
* @return bool
*/
public function hasColumns() public function hasColumns()
{ {
return false; return false;
} }
/**
* @return array
*/
public function getColumns() public function getColumns()
{ {
return array(); return array();
} }
/**
* @return bool
*/
public function hasLimit() public function hasLimit()
{ {
return false; return false;
} }
/**
* @return bool
*/
public function hasOffset() 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,13 +1,35 @@
<?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 = "";
/**
* @param $author
* @param $comment
* @param bool $persistent
*/
public function __construct($author, $comment, $persistent = false) public function __construct($author, $comment, $persistent = false)
{ {
$this->author = $author; $this->author = $author;
@ -15,7 +37,13 @@ class Comment implements IComment
$this->persistent = $persistent; $this->persistent = $persistent;
} }
public function getFormatString($type) { /**
* @param $type
* @return string
* @throws InvalidCommandException
*/
public function getFormatString($type)
{
$params = ';' . ($this->persistent ? '1' : '0') . ';' . $this->author . ';' . $this->comment; $params = ';' . ($this->persistent ? '1' : '0') . ';' . $this->author . ';' . $this->comment;
switch ($type) { switch ($type) {
@ -32,6 +60,4 @@ class Comment implements IComment
} }
return "ADD_{$typeVar}_COMMENT$params"; return "ADD_{$typeVar}_COMMENT$params";
} }
} }

View File

@ -1,25 +1,63 @@
<?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;
/**
* @param $start
* @param $end
* @param Comment $comment
* @param int $duration
*/
public function __construct($start, $end, Comment $comment, $duration = 0) 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) { /**
* @param $type
* @return string
*/
public function getFormatString($type)
{
return 'SCHEDULE_' . $type . '_DOWNTIME;%s' return 'SCHEDULE_' . $type . '_DOWNTIME;%s'
. ($type == CommandPipe::TYPE_SERVICE ? ';%s;' : ';') . ($type == CommandPipe::TYPE_SERVICE ? ';%s;' : ';')
. $this->startTime . ';' . $this->endTime . $this->startTime . ';' . $this->endTime

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,18 +1,63 @@
<?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,
@ -22,6 +67,9 @@ class PropertyModifier {
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) {
@ -31,11 +79,17 @@ class PropertyModifier {
} }
} }
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) {
@ -48,5 +102,3 @@ class PropertyModifier {
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;
/** /**
@ -96,11 +119,17 @@ class Connection
} }
/**
* @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(
sprintf(
'Cannot fetch single DN for %s', 'Cannot fetch single DN for %s',
$query $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,12 +189,21 @@ 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;
@ -172,6 +230,10 @@ class Connection
return $entries; return $entries;
} }
/**
* @param $attrs
* @return object
*/
public function cleanupAttributes(& $attrs) public function cleanupAttributes(& $attrs)
{ {
$clean = (object)array(); $clean = (object)array();
@ -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();
@ -207,12 +275,15 @@ class Connection
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(
sprintf(
'LDAP query "%s" (root %s) failed: %s', 'LDAP query "%s" (root %s) failed: %s',
$query, $query,
$this->root_dn, $this->root_dn,
ldap_error($this->ds) ldap_error($this->ds)
)); )
);
die('Query failed'); die('Query failed');
} }
$list = array(); $list = array();
@ -224,6 +295,11 @@ class Connection
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,7 +379,7 @@ class Connection
'supportedLDAPVersion', // => array(3, 2) 'supportedLDAPVersion', // => array(3, 2)
'supportedCapabilities' 'supportedCapabilities'
))*/ ))*/
;
$fields = $query->listFields(); $fields = $query->listFields();
$result = ldap_read( $result = ldap_read(
@ -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,7 +442,10 @@ 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)
);
} }
@ -351,26 +453,31 @@ class Connection
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(
'LDAP connection (%s / %s) failed: %s',
$this->bind_dn, $this->bind_dn,
'***', '***',
ldap_error($this->ds)); ldap_error($this->ds)
throw new Exception(sprintf( );
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 */, '***' /* $this->bind_pw */,
ldap_error($this->ds) 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,7 +107,9 @@ 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)
@ -112,4 +126,3 @@ class LdapUtils
return $str; return $str;
} }
} }

View File

@ -1,11 +1,9 @@
<?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
* *
@ -16,16 +14,36 @@ namespace Icinga\Protocol\Ldap;
*/ */
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,16 +83,21 @@ 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(
sprintf(
'Got invalid limit: %s, %s', 'Got invalid limit: %s, %s',
$count, $count,
$offset $offset
)); )
);
} }
$this->limit_count = (int)$count; $this->limit_count = (int)$count;
$this->limit_offset = (int)$offset; $this->limit_offset = (int)$offset;
@ -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(
LdapUtils::explodeDN(
preg_replace( preg_replace(
'/,' . preg_quote($this->connection->getDN(), '/') . '$/', '/,' . 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,30 +11,61 @@ 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);
@ -54,91 +83,145 @@ 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(
sprintf(
'The child RDN "%s" is not available', 'The child RDN "%s" is not available',
$rdn $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(
sprintf(
'"%s" is not a child of "%s"', '"%s" is not a child of "%s"',
$dn, $dn,
$mydn $mydn
)); )
);
} }
if (strlen($dn) === strlen($mydn)) { if (strlen($dn) === strlen($mydn)) {
throw new Exception(sprintf( throw new Exception(
sprintf(
'"%s" is not a child of "%s", they are equal', '"%s" is not a child of "%s", they are equal',
$dn, $dn,
$mydn $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)) {
@ -147,9 +230,12 @@ class Root
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();
/**
* @param $type
* @param $name
* @return mixed
*/
public function getObjectByName($type, $name); 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
* @package Icinga\Protocol\Statusdat
*/
class Parser class Parser
{ {
/**
* @var array
*/
private $deferred = 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,8 +73,9 @@ 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,23 +85,30 @@ 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();
@ -68,6 +116,9 @@ class Parser
} }
/**
* @throws Exception\ParsingException
*/
private function readCurrentObject() private function readCurrentObject()
{ {
$filehandle = $this->filehandle; $filehandle = $this->filehandle;
@ -75,16 +126,18 @@ class Parser
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);
@ -105,15 +158,24 @@ class Parser
$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]; $base = & $this->icingaState[$this->currentObjectType];
$state = & $this->skipObject(true); $state = & $this->skipObject(true);
$statusdatObject->runtimeState = & $state; $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(
"Unknown object $name " . $this->currentObjectType . " - "
. print_r(
$statusdatObject,
true
)
. "\n" . print_r($base, true)
);
}
$type = substr($this->currentStateType, strlen($objectType)); $type = substr($this->currentStateType, strlen($objectType));
if ($type == "status") { if ($type == "status") {
@ -129,20 +191,23 @@ class Parser
} }
/**
* @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,6 +215,10 @@ 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) {
@ -165,7 +234,11 @@ class Parser
} }
} }
protected function registerObject(&$object) { /**
* @param $object
*/
protected function registerObject(&$object)
{
$name = $this->getObjectIdentifier($object); $name = $this->getObjectIdentifier($object);
@ -175,17 +248,21 @@ class Parser
$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";
@ -194,38 +271,53 @@ class Parser
$this->currentObjectType = "host"; $this->currentObjectType = "host";
$property = substr($property, strlen("host")); $property = substr($property, strlen("host"));
} }
if(!isset($this->icingaState[$this->currentObjectType])) if (!isset($this->icingaState[$this->currentObjectType])) {
return $this->deferRegistration($object, $this->currentObjectType . $property); 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);
} }
} }
/**
* @param $object
* @param $objType
*/
protected function deferRegistration($object, $objType) protected function deferRegistration($object, $objType)
{ {
$this->deferred[] = array($object, $objType); $this->deferred[] = array($object, $objType);
} }
protected function processDeferred() { /**
*
*/
protected function processDeferred()
{
foreach ($this->deferred as $obj) { 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);
@ -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,75 +28,152 @@ 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) {
@ -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,7 +258,11 @@ class Query extends Protocol\AbstractQuery
return $result; return $result;
} }
private function orderIndices(array &$indices) { /**
* @param array $indices
*/
private function orderIndices(array &$indices)
{
if (!empty($this->order_columns)) { if (!empty($this->order_columns)) {
foreach ($indices as $type => &$subindices) { 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
@ -167,7 +271,13 @@ class Query extends Protocol\AbstractQuery
} }
} }
private function orderResult($a,$b) { /**
* @param $a
* @param $b
* @return int
*/
private function orderResult($a, $b)
{
$o1 = & $this->reader->getObjectByName($this->currentType, $a); $o1 = & $this->reader->getObjectByName($this->currentType, $a);
$o2 = & $this->reader->getObjectByName($this->currentType, $b); $o2 = & $this->reader->getObjectByName($this->currentType, $b);
$result = 0; $result = 0;
@ -175,13 +285,18 @@ class Query extends Protocol\AbstractQuery
$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) {
@ -189,21 +304,35 @@ class Query extends Protocol\AbstractQuery
} }
} }
/**
* @param $fn
* @param null $scope
* @return $this
*/
public function groupByFunction($fn, $scope = null) 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;
@ -217,17 +346,21 @@ class Query extends Protocol\AbstractQuery
$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()
{ {
@ -252,5 +385,4 @@ class Query extends Protocol\AbstractQuery
} }
return $result; return $result;
} }
} }

View File

@ -1,72 +1,130 @@
<?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];
@ -76,14 +134,21 @@ class Expression implements IQueryPart
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] === "?") { } else {
if ($tokenized[2] === "?") {
$this->value = array_shift($values); $this->value = array_shift($values);
} else { } else {
$this->value = trim($tokenized[2]); $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,57 +156,87 @@ 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) { if ($this->function) {
$values = call_user_func($this->function, $values); $values = call_user_func($this->function, $values);
if(!is_array($values)) if (!is_array($values)) {
$values = array($values); $values = array($values);
} }
foreach($values as $val) }
if($this->{$this->CB}($val)) foreach ($values as $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)) {
@ -158,59 +253,86 @@ class Expression implements IQueryPart
// 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,24 +249,33 @@ 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++;
return self::GROUP_BEGIN; return self::GROUP_BEGIN;
@ -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
{ {
/**
* @param null $expression
* @param array $value
*/
public function __construct($expression = null, &$value = array()); public function __construct($expression = null, &$value = array());
/**
* @param array $base
* @param null $idx
* @return mixed
*/
public function filter(array &$base, &$idx = null); public function filter(array &$base, &$idx = null);
} }

View File

@ -1,42 +1,68 @@
<?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;
@ -49,66 +75,64 @@ class Reader implements IReader
return; return;
} }
} }
if(!$this->lastState) if (!$this->lastState) {
$this->parseObjectsCacheFile(); $this->parseObjectsCacheFile();
if(!$this->hasRuntimeState); }
if (!$this->hasRuntimeState) {
;
}
$this->parseStatusDatFile(); $this->parseStatusDatFile();
if(!$noCache && $this->newState) if (!$noCache && $this->newState) {
$this->statusCache->save($this->parser->getRuntimeState(), 'objects' . md5($this->config->objects_file)); $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;
}
foreach ($this->lastState["service"] as &$service) { $cachePath = $this->config->get('cache_path', $defaultCachePath);
$host = &$this->lastState["host"][$service->host_name]; $maxCacheLifetime = intval($this->config->get('cache_path', self::DEFAULT_CACHE_LIFETIME));
if(!isset($host->services)) if (!is_writeable($cachePath)) {
$host->services = array(); throw new Exception\ConfigurationError(
$host->services[$service->service_description] = &$service; "Cache path $cachePath is not writable, check your configuration"
$service->host = &$host;
}
}
public function select()
{
return new Query($this);
}
public function fetchAll(Query $query)
{
return new \Icinga\Backend\MonitoringObjectList(
$query->getResult(),
$query->getView()
); );
} }
public function getState()
$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);
}
/**
* @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()) {
@ -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);
} }
private function initCache($file, $backend, $lifetime) foreach ($this->lastState["service"] as &$service) {
{ $host = & $this->lastState["host"][$service->host_name];
$frontendOptions = array( if (!isset($host->services)) {
'lifetime' => $lifetime, $host->services = array();
'automatic_serialization' => true, }
'master_files' => array($file) $host->services[$service->service_description] = & $service;
); $service->host = & $host;
return \Zend_Cache::factory('Core','File',$frontendOptions,$backend); }
} }
/**
* @throws Exception\ConfigurationError
*/
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"
);
}
if (!$this->parser) {
$this->parser = new Parser(fopen($this->config->objects_file, "r")); $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"
);
}
if (!$this->parser) {
$this->parser = new Parser(fopen($this->config->status_file, "r"), $this->lastState); $this->parser = new Parser(fopen($this->config->status_file, "r"), $this->lastState);
}
$this->parser->parseRuntimeState(fopen($this->config->status_file, "r")); $this->parser->parseRuntimeState(fopen($this->config->status_file, "r"));
$this->lastState = & $this->parser->getRuntimeState(); $this->lastState = & $this->parser->getRuntimeState();
if(!$this->noCache) if (!$this->noCache) {
$this->statusCache->save(array("true" => true), "state" . md5($this->config->objects_file)); $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,14 +1,32 @@
<?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 {
@ -19,12 +37,17 @@ class RuntimeStateContainer extends \stdClass
} }
} }
/**
* @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;

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;
/** /**
@ -96,7 +108,8 @@ class ActionController extends ZfController
$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,6 +174,7 @@ 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)
@ -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;
@ -310,8 +332,7 @@ class ActionController extends ZfController
* *
* @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)
{ {
@ -335,7 +356,7 @@ class ActionController extends ZfController
* @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,6 +34,11 @@ class Hook
self::$BASE_NS = 'Icinga\\Web\\Hook\\'; self::$BASE_NS = 'Icinga\\Web\\Hook\\';
} }
/**
* @param $name
* @param null $key
* @return bool
*/
public static function has($name, $key = null) public static function has($name, $key = null)
{ {
if ($key !== null) { if ($key !== null) {
@ -26,6 +48,11 @@ class Hook
} }
} }
/**
* @param $name
* @param $key
* @return null
*/
public static function createInstance($name, $key) public static function createInstance($name, $key)
{ {
if (!self::has($name, $key)) { if (!self::has($name, $key)) {
@ -53,38 +80,58 @@ class Hook
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(
sprintf(
'%s is not an instance of %s', '%s is not an instance of %s',
get_class($instance), get_class($instance),
$base_class $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"
); );