Beispiel #1
0
 /**
  * Apply permissions, restrictions and roles to the given user
  *
  * @param   User    $user
  */
 public function applyRoles(User $user)
 {
     $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;
     }
     $userGroups = $user->getGroups();
     $permissions = array();
     $restrictions = array();
     $roleObjs = array();
     foreach ($roles as $roleName => $role) {
         if ($this->match($username, $userGroups, $role)) {
             $permissionsFromRole = StringHelper::trimSplit($role->permissions);
             $permissions = array_merge($permissions, array_diff($permissionsFromRole, $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;
             }
             $roleObj = new Role();
             $roleObjs[] = $roleObj->setName($roleName)->setPermissions($permissionsFromRole)->setRestrictions($restrictionsFromRole);
         }
     }
     $user->setPermissions($permissions);
     $user->setRestrictions($restrictions);
     $user->setRoles($roleObjs);
 }
 /**
  * Set the given options
  *
  * @param   array   $options
  *
  * @return  $this
  */
 public function setOptions(array $options)
 {
     foreach ($options as $name => $value) {
         $setter = 'set' . StringHelper::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 = StringHelper::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 = StringHelper::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);
     }
 }
Beispiel #5
0
 /**
  * Load a role
  *
  * @param   string  $name           The name of the role
  *
  * @return  $this
  *
  * @throws  LogicException          If the config is not set
  * @throws  NotFoundError           If the given role does not exist
  * @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 NotFoundError($this->translate('Can\'t load role \'%s\'. Role does not exist'), $name);
     }
     $role = $this->config->getSection($name)->toArray();
     $role['permissions'] = !empty($role['permissions']) ? StringHelper::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;
 }
 /**
  * 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(StringHelper::cname($name));
         if (method_exists($this, $setter)) {
             $this->{$setter}($value);
         }
     }
     return $this;
 }
 public function testWhetherTrimSplitSplitsByTheGivenDelimiter()
 {
     $this->assertEquals(array('one', 'two', 'three'), StringHelper::trimSplit('one.two.three', '.'), 'String::trimSplit does not split a string by the given delimiter');
 }
 /**
  * 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', StringHelper::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;
 }
 /**
  * {@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 && !StringHelper::endsWith($file, $this->extension)) {
                     $skip = true;
                     break;
                 }
                 $key = $file;
                 $file = $path;
             } while (0);
         }
     } while ($skip);
     $this->current = $file;
     /** @noinspection PhpUndefinedVariableInspection */
     $this->key = $key;
 }
Beispiel #10
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 StringHelper::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 #11
0
 public static function createFromStateSummary(stdClass $states, $title, array $colors)
 {
     $handledUnhandledStates = array();
     foreach ($states as $key => $value) {
         if (StringHelper::endsWith($key, '_handled') || StringHelper::endsWith($key, '_unhandled')) {
             $handledUnhandledStates[$key] = $value;
         }
     }
     $chart = new self(array_values($handledUnhandledStates), $title, $colors);
     return $chart->setSize(50)->setTitle('')->setSparklineClass('sparkline-multi');
 }
Beispiel #12
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 StringHelper::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 #13
0
 /**
  * {@inheritdoc}
  */
 public function next()
 {
     do {
         $this->files->next();
         $skip = false;
         if (!$this->files->valid()) {
             $file = false;
             $path = false;
             break;
         } else {
             $file = $this->files->current();
             do {
                 if ($this->skipHidden && $file[0] === '.') {
                     $skip = true;
                     break;
                 }
                 $path = $this->path . '/' . $file;
                 if (is_dir($path)) {
                     if ($this->flags & static::FILES_FIRST === static::FILES_FIRST) {
                         $this->queue[] = array($path, $file);
                         $skip = true;
                     }
                     break;
                 }
                 if ($this->skipEmpty && !filesize($path)) {
                     $skip = true;
                     break;
                 }
                 if ($this->extension && !StringHelper::endsWith($file, $this->extension)) {
                     $skip = true;
                     break;
                 }
             } while (0);
         }
     } while ($skip);
     /** @noinspection PhpUndefinedVariableInspection */
     if ($path === false && !empty($this->queue)) {
         list($path, $file) = array_shift($this->queue);
     }
     $this->current = $path;
     $this->key = $file;
 }
Beispiel #14
0
<?php

namespace Icinga\Web\View;

use Icinga\Util\StringHelper;
$this->addHelperFunction('ellipsis', function ($string, $maxLength, $ellipsis = '...') {
    return StringHelper::ellipsis($string, $maxLength, $ellipsis);
});
$this->addHelperFunction('nl2br', function ($string) {
    return str_replace(array('\\r\\n', '\\r', '\\n'), '<br>', $string);
});
Beispiel #15
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']) ? StringHelper::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 = StringHelper::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 #17
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 = StringHelper::trimSplit($value);
     } elseif ($value !== null) {
         throw new ProgrammingError('Cannot retrieve value "%s" as array. It\'s not a string', $value);
     }
     return $value;
 }
Beispiel #18
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, null is returned.
  * 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   string              $target     The table to join $name into
  * @param   RepositoryQUery     $query      The query to apply the JOIN-clause on
  *
  * @return  string|null                     The resolved alias or $name, null if no join logic is found
  */
 public function joinColumn($name, $target, RepositoryQuery $query)
 {
     if (!($tableName = $this->findTableName($name))) {
         return;
     }
     if (($column = $this->resolveQueryColumnAlias($tableName, $name)) === null) {
         $column = $name;
     }
     if (($joinIdentifier = $this->resolveTableAlias($tableName)) === null) {
         $joinIdentifier = $this->prependTablePrefix($tableName);
     }
     if ($query->getQuery()->hasJoinedTable($joinIdentifier)) {
         return $column;
     }
     $joinMethod = 'join' . StringHelper::cname($tableName);
     if (!method_exists($this, $joinMethod)) {
         throw new ProgrammingError('Unable to join table "%s" into "%s". Method "%s" not found', $tableName, $target, $joinMethod);
     }
     $this->{$joinMethod}($query, $target, $name);
     return $column;
 }
Beispiel #19
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, StringHelper::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 aria-hidden="true" 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));
     }
 }