Beispiel #1
0
 /**
  * Get user permissions and restrictions
  *
  * @param   User $user
  *
  * @return  array
  */
 public function getPermissionsAndRestrictions(User $user)
 {
     $permissions = array();
     $restrictions = array();
     $username = $user->getUsername();
     try {
         $roles = Config::app('roles');
     } catch (NotReadableError $e) {
         Logger::error('Can\'t get permissions and restrictions for user \'%s\'. An exception was thrown:', $username, $e);
         return array($permissions, $restrictions);
     }
     $userGroups = $user->getGroups();
     foreach ($roles as $role) {
         if ($this->match($username, $userGroups, $role)) {
             $permissions = array_merge($permissions, array_diff(String::trimSplit($role->permissions), $permissions));
             $restrictionsFromRole = $role->toArray();
             unset($restrictionsFromRole['users']);
             unset($restrictionsFromRole['groups']);
             unset($restrictionsFromRole['permissions']);
             foreach ($restrictionsFromRole as $name => $restriction) {
                 if (!isset($restrictions[$name])) {
                     $restrictions[$name] = array();
                 }
                 $restrictions[$name][] = $restriction;
             }
         }
     }
     return array($permissions, $restrictions);
 }
 /**
  * Set the given options
  *
  * @param   array   $options
  *
  * @return  $this
  */
 public function setOptions(array $options)
 {
     foreach ($options as $name => $value) {
         $setter = 'set' . String::cname($name);
         if (method_exists($this, $setter)) {
             $this->{$setter}($value);
         }
     }
 }
Beispiel #3
0
 protected function _error($messageKey, $value = null)
 {
     if ($messageKey === static::NOT_IN_ARRAY) {
         $matches = String::findSimilar($this->_value, $this->_haystack);
         if (empty($matches)) {
             $this->_messages[$messageKey] = sprintf(t('"%s" is not in the list of allowed values.'), $this->_value);
         } else {
             $this->_messages[$messageKey] = sprintf(t('"%s" is not in the list of allowed values. Did you mean one of the following?: %s'), $this->_value, implode(', ', $matches));
         }
     } else {
         parent::_error($messageKey, $value);
     }
 }
Beispiel #4
0
 /**
  * Dispatch request to a controller and action
  *
  * @param   Zend_Controller_Request_Abstract  $request
  * @param   Zend_Controller_Response_Abstract $response
  *
  * @throws  Zend_Controller_Dispatcher_Exception    If the controller is not an instance of
  *                                                  Zend_Controller_Action_Interface
  * @throws  Exception                               If dispatching the request fails
  */
 public function dispatch(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response)
 {
     $this->setResponse($response);
     $controllerName = $request->getControllerName();
     if (!$controllerName) {
         parent::dispatch($request, $response);
         return;
     }
     $controllerName = String::cname($controllerName, '-') . 'Controller';
     $moduleName = $request->getModuleName();
     if ($moduleName === null || $moduleName === $this->_defaultModule) {
         $controllerClass = 'Icinga\\' . self::CONTROLLER_NAMESPACE . '\\' . $controllerName;
     } else {
         $controllerClass = 'Icinga\\Module\\' . ucfirst($moduleName) . '\\' . self::CONTROLLER_NAMESPACE . '\\' . $controllerName;
     }
     if (!class_exists($controllerClass)) {
         parent::dispatch($request, $response);
         return;
     }
     $controller = new $controllerClass($request, $response, $this->getParams());
     if (!$controller instanceof Zend_Controller_Action && !$controller instanceof Zend_Controller_Action_Interface) {
         throw new Zend_Controller_Dispatcher_Exception('Controller "' . $controllerClass . '" is not an instance of Zend_Controller_Action_Interface');
     }
     $action = $this->getActionMethod($request);
     $request->setDispatched(true);
     // Buffer output by default
     $disableOb = $this->getParam('disableOutputBuffering');
     $obLevel = ob_get_level();
     if (empty($disableOb)) {
         ob_start();
     }
     try {
         $controller->dispatch($action);
     } catch (Exception $e) {
         // Clean output buffer on error
         $curObLevel = ob_get_level();
         if ($curObLevel > $obLevel) {
             do {
                 ob_get_clean();
                 $curObLevel = ob_get_level();
             } while ($curObLevel > $obLevel);
         }
         throw $e;
     }
     if (empty($disableOb)) {
         $content = ob_get_clean();
         $response->appendBody($content);
     }
 }
 /**
  * Return a list of groups for an username
  *
  * @param   string  $username
  *
  * @return  array
  */
 public function getGroupsByUsername($username)
 {
     $groups = array();
     try {
         $config = Config::app('memberships');
     } catch (NotReadableError $e) {
         return $groups;
     }
     foreach ($config as $section) {
         $users = String::trimSplit($section->users);
         if (in_array($username, $users)) {
             $groups = array_merge($groups, String::trimSplit($section->groups));
         }
     }
     return $groups;
 }
 /**
  * Retrieve permissions
  *
  * @param   string  $username
  * @param   array   $groups
  *
  * @return  array
  */
 public function getPermissions($username, array $groups)
 {
     $permissions = array();
     try {
         $config = Config::app('permissions');
     } catch (NotReadableError $e) {
         return $permissions;
     }
     foreach ($config as $section) {
         if ($this->match($section, $username, $groups)) {
             foreach ($section as $key => $value) {
                 if (strpos($key, 'permission') === 0) {
                     $permissions = array_merge($permissions, String::trimSplit($value));
                 }
             }
         }
     }
     return $permissions;
 }
Beispiel #7
0
 /**
  * Load a role
  *
  * @param   string  $name           The name of the role
  *
  * @return  $this
  *
  * @throws  LogicException          If the config is not set
  * @see     ConfigForm::setConfig() For setting the config.
  */
 public function load($name)
 {
     if (!isset($this->config)) {
         throw new LogicException(sprintf('Can\'t load role \'%s\'. Config is not set', $name));
     }
     if (!$this->config->hasSection($name)) {
         throw new InvalidArgumentException(sprintf($this->translate('Can\'t load role \'%s\'. Role does not exist'), $name));
     }
     $role = $this->config->getSection($name)->toArray();
     $role['permissions'] = !empty($role['permissions']) ? String::trimSplit($role['permissions']) : null;
     $role['name'] = $name;
     $restrictions = array();
     foreach ($this->providedRestrictions as $name => $spec) {
         if (isset($role[$spec['name']])) {
             // Translate restriction names to filtered element names
             $restrictions[$name] = $role[$spec['name']];
             unset($role[$spec['name']]);
         }
     }
     $role = array_merge($role, $restrictions);
     $this->populate($role);
     return $this;
 }
 /**
  * Return the groups the given user is a member of
  *
  * @param   User    $user
  *
  * @return  array
  */
 public function getMemberships(User $user)
 {
     $result = $this->select()->fetchAll();
     $groups = array();
     foreach ($result as $group) {
         $groups[$group->group_name] = $group->parent;
     }
     $username = strtolower($user->getUsername());
     $memberships = array();
     foreach ($result as $group) {
         if ($group->users && !in_array($group->group_name, $memberships)) {
             $users = array_map('strtolower', String::trimSplit($group->users));
             if (in_array($username, $users)) {
                 $memberships[] = $group->group_name;
                 $parent = $groups[$group->group_name];
                 while ($parent !== null) {
                     $memberships[] = $parent;
                     $parent = isset($groups[$parent]) ? $groups[$parent] : null;
                 }
             }
         }
     }
     return $memberships;
 }
Beispiel #9
0
 /**
  * Display the given perfdata string to the user
  *
  * @param   string  $perfdataStr    The perfdata string
  * @param   bool    $compact        Whether to display the perfdata in compact mode
  * @param   int     $limit          Max labels to show; 0 for no limit
  * @param   string  $color          The color indicating the perfdata state
  *
  * @return string
  */
 public function perfdata($perfdataStr, $compact = false, $limit = 0, $color = Perfdata::PERFDATA_OK)
 {
     $pieChartData = PerfdataSet::fromString($perfdataStr)->asArray();
     uasort($pieChartData, function ($a, $b) {
         return $a->worseThan($b) ? -1 : ($b->worseThan($a) ? 1 : 0);
     });
     $results = array();
     $keys = array('', 'label', 'value', 'min', 'max', 'warn', 'crit');
     $columns = array();
     $labels = array_combine($keys, array('', $this->view->translate('Label'), $this->view->translate('Value'), $this->view->translate('Min'), $this->view->translate('Max'), $this->view->translate('Warning'), $this->view->translate('Critical')));
     foreach ($pieChartData as $perfdata) {
         if ($perfdata->isVisualizable()) {
             $columns[''] = '';
         }
         foreach ($perfdata->toArray() as $column => $value) {
             if (empty($value) || $column === 'min' && floatval($value) === 0.0 || $column === 'max' && $perfdata->isPercentage() && floatval($value) === 100) {
                 continue;
             }
             $columns[$column] = $labels[$column];
         }
     }
     // restore original column array sorting
     $headers = array();
     foreach ($keys as $column) {
         if (isset($columns[$column])) {
             $headers[$column] = $labels[$column];
         }
     }
     $table = array('<thead><tr><th>' . implode('</th><th>', $headers) . '</th></tr></thead><tbody>');
     foreach ($pieChartData as $perfdata) {
         if ($compact && $perfdata->isVisualizable()) {
             $results[] = $perfdata->asInlinePie($color)->render();
         } else {
             $data = array();
             if ($perfdata->isVisualizable()) {
                 $data[] = $perfdata->asInlinePie($color)->render();
             } elseif (isset($columns[''])) {
                 $data[] = '';
             }
             if (!$compact) {
                 foreach ($perfdata->toArray() as $column => $value) {
                     if (!isset($columns[$column])) {
                         continue;
                     }
                     $text = $this->view->escape(empty($value) ? '-' : $value);
                     $data[] = sprintf('<span title="%s">%s</span>', $text, String::ellipsisCenter($text, 24));
                 }
             }
             $table[] = '<tr><td class="sparkline-col">' . implode('</td><td>', $data) . '</td></tr>';
         }
     }
     $table[] = '</tbody>';
     if ($limit > 0) {
         $count = $compact ? count($results) : count($table);
         if ($count > $limit) {
             if ($compact) {
                 $results = array_slice($results, 0, $limit);
                 $title = sprintf($this->view->translate('%d more ...'), $count - $limit);
                 $results[] = '<span title="' . $title . '">...</span>';
             } else {
                 $table = array_slice($table, 0, $limit);
             }
         }
     }
     if ($compact) {
         return join('', $results);
     } else {
         if (empty($table)) {
             return '';
         }
         return sprintf('<table class="performance-data-table">%s</table>', implode("\n", $table));
     }
 }
Beispiel #10
0
 /**
  * Join alias or column $name into $table using $query
  *
  * Attempts to find a valid table for the given alias or column name and a method labelled join<TableName>
  * to process the actual join logic. If neither of those is found, ProgrammingError will be thrown.
  * The method is called with the same parameters but in reversed order.
  *
  * @param   string              $name       The alias or column name to join into $target
  * @param   array|string        $target     The table to join $name into
  * @param   RepositoryQUery     $query      The query to apply the JOIN-clause on
  *
  * @return  string                          The resolved alias or $name
  *
  * @throws  ProgrammingError                In case no valid table or join<TableName>-method is found
  */
 public function joinColumn($name, $target, RepositoryQuery $query)
 {
     $tableName = $this->findTableName($name);
     if (!$tableName) {
         throw new ProgrammingError('Unable to find a valid table for column "%s" to join into "%s"', $name, $this->removeTablePrefix($this->clearTableAlias($target)));
     }
     if (($column = $this->resolveQueryColumnAlias($tableName, $name)) === null) {
         $column = $name;
     }
     $prefixedTableName = $this->prependTablePrefix($tableName);
     if ($query->getQuery()->hasJoinedTable($prefixedTableName)) {
         return $column;
     }
     $joinMethod = 'join' . String::cname($tableName);
     if (!method_exists($this, $joinMethod)) {
         throw new ProgrammingError('Unable to join table "%s" into "%s". Method "%s" not found', $tableName, $this->removeTablePrefix($this->clearTableAlias($target)), $joinMethod);
     }
     $this->{$joinMethod}($query, $target, $name);
     return $column;
 }
Beispiel #11
0
 /**
  * Return an empty array with all possible host state names
  *
  * @return array    An array containing all possible host states as keys and 0 as values.
  */
 public static function getServiceStatesSummaryEmpty()
 {
     return String::cartesianProduct(array(array('services'), array(Service::getStateText(Service::STATE_OK), Service::getStateText(Service::STATE_WARNING), Service::getStateText(Service::STATE_CRITICAL), Service::getStateText(Service::STATE_UNKNOWN), Service::getStateText(Service::STATE_PENDING)), array(null, 'handled', 'unhandled')), '_');
 }
Beispiel #12
0
 public static function createFromStateSummary(stdClass $states, $title, array $colors)
 {
     $handledUnhandledStates = array();
     foreach ($states as $key => $value) {
         if (String::endsWith($key, '_handled') || String::endsWith($key, '_unhandled')) {
             $handledUnhandledStates[$key] = $value;
         }
     }
     $chart = new self(array_values($handledUnhandledStates), $title, $colors);
     return $chart->setSize(50)->setTitle('')->setSparklineClass('sparkline-multi');
 }
 /**
  * {@inheritdoc}
  */
 public function next()
 {
     do {
         $file = readdir($this->handle);
         if ($file === false) {
             $key = false;
             break;
         } else {
             $skip = false;
             do {
                 if ($this->skipHidden && $file[0] === '.') {
                     $skip = true;
                     break;
                 }
                 $path = $this->path . '/' . $file;
                 if (is_dir($path)) {
                     $skip = true;
                     break;
                 }
                 if ($this->skipEmpty && !filesize($path)) {
                     $skip = true;
                     break;
                 }
                 if ($this->extension && !String::endsWith($file, $this->extension)) {
                     $skip = true;
                     break;
                 }
                 $key = $file;
                 $file = $path;
             } while (0);
         }
     } while ($skip);
     $this->current = $file;
     /** @noinspection PhpUndefinedVariableInspection */
     $this->key = $key;
 }
 public function testWhetherTrimSplitSplitsByTheGivenDelimiter()
 {
     $this->assertEquals(array('one', 'two', 'three'), String::trimSplit('one.two.three', '.'), 'String::trimSplit does not split a string by the given delimiter');
 }
Beispiel #15
0
 /**
  * Return an empty array with all possible host state names
  *
  * @return array    An array containing all possible host states as keys and 0 as values.
  */
 public static function getHostStatesSummaryEmpty()
 {
     return String::cartesianProduct(array(array('hosts'), array(Host::getStateText(Host::STATE_UP), Host::getStateText(Host::STATE_DOWN), Host::getStateText(Host::STATE_UNREACHABLE), Host::getStateText(Host::STATE_PENDING)), array(null, 'handled', 'unhandled')), '_');
 }
Beispiel #16
0
<?php

namespace Icinga\Web\View;

use Icinga\Util\String;
$this->addHelperFunction('ellipsis', function ($string, $maxLength, $ellipsis = '...') {
    return String::ellipsis($string, $maxLength, $ellipsis);
});
$this->addHelperFunction('nl2br', function ($string) {
    return str_replace(array('\\r\\n', '\\r', '\\n'), '<br>', $string);
});
Beispiel #17
0
 /**
  * Create and return a new navigation item for the given configuration
  *
  * @param   string              $name
  * @param   array|ConfigObject  $properties
  *
  * @return  NavigationItem
  *
  * @throws  InvalidArgumentException    If the $properties argument is neither an array nor a ConfigObject
  */
 public function createItem($name, $properties)
 {
     if ($properties instanceof ConfigObject) {
         $properties = $properties->toArray();
     } elseif (!is_array($properties)) {
         throw new InvalidArgumentException('Argument $properties must be of type array or ConfigObject');
     }
     $itemType = isset($properties['type']) ? String::cname($properties['type'], '-') : 'NavigationItem';
     if (!empty(static::$types) && isset(static::$types[$itemType])) {
         return new static::$types[$itemType]($name, $properties);
     }
     $item = null;
     foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $module) {
         $classPath = 'Icinga\\Module\\' . ucfirst($module->getName()) . '\\' . static::NAVIGATION_NS . '\\' . $itemType;
         if (class_exists($classPath)) {
             $item = new $classPath($name, $properties);
             break;
         }
     }
     if ($item === null) {
         $classPath = 'Icinga\\' . static::NAVIGATION_NS . '\\' . $itemType;
         if (class_exists($classPath)) {
             $item = new $classPath($name, $properties);
         }
     }
     if ($item === null) {
         Logger::debug('Failed to find custom navigation item class %s for item %s. Using base class NavigationItem now', $itemType, $name);
         $item = new NavigationItem($name, $properties);
         static::$types[$itemType] = 'Icinga\\Web\\Navigation\\NavigationItem';
     } elseif (!$item instanceof NavigationItem) {
         throw new ProgrammingError('Class %s must inherit from NavigationItem', $classPath);
     } else {
         static::$types[$itemType] = $classPath;
     }
     return $item;
 }
 /**
  * Return the form for the given type of navigation item
  *
  * @param   string  $type
  *
  * @return  Form
  */
 protected function getItemForm($type)
 {
     $className = String::cname($type, '-') . 'Form';
     $form = null;
     foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $module) {
         $classPath = 'Icinga\\Module\\' . ucfirst($module->getName()) . '\\' . static::FORM_NS . '\\' . $className;
         if (class_exists($classPath)) {
             $form = new $classPath();
             break;
         }
     }
     if ($form === null) {
         $classPath = 'Icinga\\' . static::FORM_NS . '\\' . $className;
         if (class_exists($classPath)) {
             $form = new $classPath();
         }
     }
     if ($form === null) {
         Logger::debug('Failed to find custom navigation item form %s for item %s. Using form NavigationItemForm now', $className, $type);
         $form = new NavigationItemForm();
     } elseif (!$form instanceof NavigationItemForm) {
         throw new ProgrammingError('Class %s must inherit from NavigationItemForm', $classPath);
     }
     return $form;
 }
Beispiel #19
0
 /**
  * Convert the given comma separated string to an array
  *
  * @param   string  $value
  *
  * @return  array
  */
 protected function retrieveCommaSeparatedString($value)
 {
     if ($value && is_string($value)) {
         $value = String::trimSplit($value);
     } elseif ($value !== null) {
         throw new ProgrammingError('Cannot retrieve value "%s" as array. It\'s not a string', $value);
     }
     return $value;
 }
Beispiel #20
0
 /**
  * Set the properties of the acknowledgement
  *
  * @param   array|object|Traversable $properties
  *
  * @return  $this
  * @throws  InvalidArgumentException If the type of the given properties is invalid
  */
 public function setProperties($properties)
 {
     if (!is_array($properties) && !is_object($properties) && !$properties instanceof Traversable) {
         throw new InvalidArgumentException('Properties must be either an array or an instance of Traversable');
     }
     foreach ($properties as $name => $value) {
         $setter = 'set' . ucfirst(String::cname($name));
         if (method_exists($this, $setter)) {
             $this->{$setter}($value);
         }
     }
     return $this;
 }