Example #1
0
 public function addLoadedModules()
 {
     foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $name => $module) {
         $this->addModule($name, $module);
     }
     return $this;
 }
Example #2
0
 public static function send($minified = false)
 {
     header('Content-Type: application/javascript');
     $basedir = Icinga::app()->getBootstrapDirecory();
     $js = $out = '';
     $min = $minified ? '.min' : '';
     // TODO: Cache header
     header('Content-Type: application/javascript');
     $cacheFile = '/tmp/cache_icinga' . $min . '.js';
     if (file_exists($cacheFile)) {
         readfile($cacheFile);
         exit;
     }
     // We do not minify vendor files
     foreach (self::$vendorFiles as $file) {
         $out .= file_get_contents($basedir . '/' . $file . $min . '.js');
     }
     foreach (self::$jsFiles as $file) {
         $js .= file_get_contents($basedir . '/' . $file);
     }
     foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $name => $module) {
         if ($module->hasJs()) {
             $js .= file_get_contents($module->getJsFilename());
         }
     }
     if ($minified) {
         require_once 'IcingaVendor/JShrink/Minifier.php';
         $out .= Minifier::minify($js, array('flaggedComments' => false));
     } else {
         $out .= $js;
     }
     // Not yet, this is for tests only. Waiting for Icinga\Web\Cache
     // file_put_contents($cacheFile, $out);
     echo $out;
 }
Example #3
0
 /**
  * Get the view this menu item is being rendered to
  *
  * @return View
  */
 protected function getView()
 {
     if ($this->view === null) {
         $this->view = Icinga::app()->getViewRenderer()->view;
     }
     return $this->view;
 }
Example #4
0
 /**
  * Return an image from the application's or the module's public folder
  */
 public function imgAction()
 {
     // TODO(el): I think this action only retrieves images from modules
     $module = $this->_getParam('module_name');
     $file = $this->_getParam('file');
     $basedir = Icinga::app()->getModuleManager()->getModule($module)->getBaseDir();
     $filePath = realpath($basedir . '/public/img/' . $file);
     if ($filePath === false) {
         $this->httpNotFound('%s does not exist', $filePath);
     }
     if (preg_match('/\\.([a-z]+)$/i', $file, $m)) {
         $extension = $m[1];
         if ($extension === 'svg') {
             $extension = 'svg+xml';
         }
     } else {
         $extension = 'fixme';
     }
     $s = stat($filePath);
     header('Content-Type: image/' . $extension);
     header(sprintf('ETag: "%x-%x-%x"', $s['ino'], $s['size'], (double) str_pad($s['mtime'], 16, '0')));
     header('Cache-Control: public, max-age=3600');
     header('Pragma: cache');
     header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $s['mtime']) . ' GMT');
     readfile($filePath);
 }
Example #5
0
 public function serveAction()
 {
     $minVersion = '5.4.0';
     if (version_compare(PHP_VERSION, $minVersion) < 0) {
         throw new IcingaException('You are running PHP %s, internal webserver requires %s.', PHP_VERSION, $minVersion);
     }
     $fork = $this->params->get('daemonize');
     $documentRoot = $this->params->shift();
     $socket = $this->params->shift();
     // TODO: Sanity check!!
     if ($socket === null) {
         $socket = '0.0.0.0:80';
         // throw new IcingaException('Socket is required');
     }
     if ($documentRoot === null) {
         $documentRoot = Icinga::app()->getBaseDir('public');
         if (!file_exists($documentRoot) || !is_dir($documentRoot)) {
             throw new IcingaException('Document root directory is required');
         }
     }
     $documentRoot = realpath($documentRoot);
     if ($fork) {
         $this->forkAndExit();
     }
     echo "Serving Icingaweb from {$documentRoot}\n";
     $cmd = sprintf('%s -S %s -t %s %s', readlink('/proc/self/exe'), $socket, $documentRoot, Icinga::app()->getLibraryDir('/Icinga/Application/webrouter.php'));
     // TODO: Store webserver log, switch uid, log index.php includes, pid file
     if ($fork) {
         exec($cmd);
     } else {
         passthru($cmd);
     }
 }
Example #6
0
 /**
  * Create menu from the application's menu config file plus the config files from all enabled modules
  *
  * @return  self
  */
 public static function fromConfig()
 {
     $menu = new static('menu');
     $manager = Icinga::app()->getModuleManager();
     try {
         $menuConfigs = array(Config::app('menu'));
     } catch (NotReadableError $e) {
         Logger::error($e);
         $menuConfigs = array();
     }
     try {
         $modules = $manager->listEnabledModules();
     } catch (NotReadableError $e) {
         Logger::error($e);
         $modules = array();
     }
     foreach ($modules as $moduleName) {
         try {
             $moduleMenuConfig = Config::module($moduleName, 'menu');
         } catch (NotReadableError $e) {
             Logger::error($e);
             $moduleMenuConfig = array();
         }
         if (!empty($moduleMenuConfig)) {
             $menuConfigs[] = $moduleMenuConfig;
         }
     }
     return $menu->loadMenuItems($menu->flattenConfigs($menuConfigs));
 }
 public function getConfigDir()
 {
     if ($this->configDir === null) {
         $dir = Icinga::app()->getModuleManager()->getModule('businessprocess')->getConfigDir();
         // TODO: This is silly. We need Config::requireDirectory().
         if (!is_dir($dir)) {
             if (!is_dir(dirname($dir))) {
                 if (!@mkdir(dirname($dir))) {
                     throw new SystemPermissionException('Could not create config directory "%s"', dirname($dir));
                 }
             }
             if (!mkdir($dir)) {
                 throw new SystemPermissionException('Could not create config directory "%s"', $dir);
             }
         }
         $dir = $dir . '/processes';
         if (!is_dir($dir)) {
             if (!mkdir($dir)) {
                 throw new SystemPermissionException('Could not create config directory "%s"', $dir);
             }
         }
         $this->configDir = $dir;
     }
     return $this->configDir;
 }
Example #8
0
 /**
  * {@inheritdoc}
  */
 public function init()
 {
     $this->providedPermissions = array('*' => $this->translate('Allow everything') . ' (*)', 'application/stacktraces' => $this->translate('Allow to adjust in the preferences whether to show stacktraces') . ' (application/stacktraces)', 'config/*' => $this->translate('Allow config access') . ' (config/*)');
     $helper = new Zend_Form_Element('bogus');
     $mm = Icinga::app()->getModuleManager();
     foreach ($mm->listInstalledModules() as $moduleName) {
         $modulePermission = $mm::MODULE_PERMISSION_NS . $moduleName;
         $this->providedPermissions[$modulePermission] = sprintf($this->translate('Allow access to module %s') . ' (%s)', $moduleName, $modulePermission);
         $module = $mm->getModule($moduleName, false);
         foreach ($module->getProvidedPermissions() as $permission) {
             /** @var object $permission */
             $this->providedPermissions[$permission->name] = $permission->description . ' (' . $permission->name . ')';
         }
         foreach ($module->getProvidedRestrictions() as $restriction) {
             /** @var object $restriction */
             // Zend only permits alphanumerics, the underscore, the circumflex and any ASCII character in range
             // \x7f to \xff (127 to 255)
             $name = $helper->filterName($restriction->name);
             while (isset($this->providedRestrictions[$name])) {
                 // Because Zend_Form_Element::filterName() replaces any not permitted character with the empty
                 // string we may have duplicate names, e.g. 're/striction' and 'restriction'
                 $name .= '_';
             }
             $this->providedRestrictions[$name] = array('description' => $restriction->description, 'name' => $restriction->name);
         }
     }
 }
Example #9
0
 public static function load($name, Module $module = null)
 {
     if ($module === null) {
         $basedir = Icinga::app()->getApplicationDir('forms');
         $ns = '\\Icinga\\Web\\Forms\\';
     } else {
         $basedir = $module->getFormDir();
         $ns = '\\Icinga\\Module\\' . ucfirst($module->getName()) . '\\Forms\\';
     }
     if (preg_match('~^[a-z0-9/]+$~i', $name)) {
         $parts = preg_split('~/~', $name);
         $class = ucfirst(array_pop($parts)) . 'Form';
         $file = sprintf('%s/%s/%s.php', rtrim($basedir, '/'), implode('/', $parts), $class);
         if (file_exists($file)) {
             require_once $file;
             $class = $ns . $class;
             $options = array();
             if ($module !== null) {
                 $options['icingaModule'] = $module;
             }
             return new $class($options);
         }
     }
     throw new ProgrammingError(sprintf('Cannot load %s (%s), no such form', $name, $file));
 }
 /**
  * Access the current view
  *
  * Will instantiate a new one if none exists
  * // TODO: App->getView
  *
  * @return Zend_View_Abstract
  */
 protected function view()
 {
     if (self::$view === null) {
         self::$view = Icinga::app()->getViewRenderer()->view;
     }
     return self::$view;
 }
 /**
  * Return this controller's module
  *
  * @return  Module
  */
 public function Module()
 {
     if ($this->module === null) {
         $this->module = Icinga::app()->getModuleManager()->getModule($this->getModuleName());
     }
     return $this->module;
 }
Example #12
0
 /**
  * {@inheritdoc}
  */
 public function render()
 {
     $repo = new AnnouncementIniRepository();
     $etag = $repo->getEtag();
     $cookie = new AnnouncementCookie();
     if ($cookie->getEtag() !== $etag) {
         $cookie->setEtag($etag);
         $cookie->setNextActive($repo->findNextActive());
         Icinga::app()->getResponse()->setCookie($cookie);
     }
     $acked = array();
     foreach ($cookie->getAcknowledged() as $hash) {
         $acked[] = Filter::expression('hash', '!=', $hash);
     }
     $acked = Filter::matchAll($acked);
     $announcements = $repo->findActive();
     $announcements->applyFilter($acked);
     if ($announcements->hasResult()) {
         $html = '<ul role="alert" id="announcements">';
         foreach ($announcements as $announcement) {
             $ackForm = new AcknowledgeAnnouncementForm();
             $ackForm->populate(array('hash' => $announcement->hash));
             $html .= '<li><div>' . $this->view()->escape($announcement->message) . '</div>' . $ackForm . '</li>';
         }
         $html .= '</ul>';
         return $html;
     }
     // Force container update on XHR
     return '<div style="display: none;"></div>';
 }
Example #13
0
 /**
  * Get the response
  *
  * @return Response
  */
 public function getResponse()
 {
     if ($this->response === null) {
         $this->response = Icinga::app()->getResponse();
     }
     return $this->response;
 }
Example #14
0
 /**
  * Get the request
  *
  * @return Request
  */
 public function getRequest()
 {
     if ($this->request === null) {
         $this->request = Icinga::app()->getRequest();
     }
     return $this->request;
 }
Example #15
0
 /**
  * Send the client side script code to the client
  *
  * Does not cache the client side script code if the HTTP header Cache-Control or Pragma is set to no-cache.
  *
  * @param   bool    $minified   Whether to compress the client side script code
  */
 public static function send($minified = false)
 {
     header('Content-Type: application/javascript');
     $basedir = Icinga::app()->getBootstrapDirectory();
     $js = $out = '';
     $min = $minified ? '.min' : '';
     // Prepare vendor file list
     $vendorFiles = array();
     foreach (self::$vendorFiles as $file) {
         $vendorFiles[] = $basedir . '/' . $file . $min . '.js';
     }
     // Prepare Icinga JS file list
     $jsFiles = array();
     foreach (self::$jsFiles as $file) {
         $jsFiles[] = $basedir . '/' . $file;
     }
     foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $name => $module) {
         if ($module->hasJs()) {
             foreach ($module->getJsFiles() as $path) {
                 if (file_exists($path)) {
                     $jsFiles[] = $path;
                 }
             }
         }
     }
     $files = array_merge($vendorFiles, $jsFiles);
     $request = Icinga::app()->getRequest();
     $noCache = $request->getHeader('Cache-Control') === 'no-cache' || $request->getHeader('Pragma') === 'no-cache';
     if (!$noCache && FileCache::etagMatchesFiles($files)) {
         header("HTTP/1.1 304 Not Modified");
         return;
     } else {
         $etag = FileCache::etagForFiles($files);
     }
     header('Cache-Control: public');
     header('ETag: "' . $etag . '"');
     header('Content-Type: application/javascript');
     $cacheFile = 'icinga-' . $etag . $min . '.js';
     $cache = FileCache::instance();
     if (!$noCache && $cache->has($cacheFile)) {
         $cache->send($cacheFile);
         return;
     }
     // We do not minify vendor files
     foreach ($vendorFiles as $file) {
         $out .= ';' . ltrim(trim(file_get_contents($file)), ';') . "\n";
     }
     foreach ($jsFiles as $file) {
         $js .= file_get_contents($file) . "\n\n\n";
     }
     if ($minified) {
         require_once 'JShrink/Minifier.php';
         $out .= Minifier::minify($js, array('flaggedComments' => false));
     } else {
         $out .= $js;
     }
     $cache->store($cacheFile, $out);
     echo $out;
 }
Example #16
0
 /**
  * Dump benchmark data
  *
  * Will dump a text table if running on CLI and a simple HTML table
  * otherwise. Use Benchmark::TIME and Benchmark::MEMORY to choose whether
  * you prefer to show either time or memory or both in your output
  *
  * @param  int   Whether to get time and/or memory summary
  * @return string
  */
 public static function dump($what = null)
 {
     if (Icinga::app()->isCli()) {
         echo self::renderToText($what);
     } else {
         echo self::renderToHtml($what);
     }
 }
Example #17
0
 /**
  * {@inheritdoc}
  *
  * @return  $this
  */
 public function createElements(array $formData)
 {
     $themes = Icinga::app()->getThemes();
     $themes[StyleSheet::DEFAULT_THEME] .= ' (' . $this->translate('default') . ')';
     $this->addElement('select', 'themes_default', array('description' => $this->translate('The default theme', 'Form element description'), 'disabled' => count($themes) < 2 ? 'disabled' : null, 'label' => $this->translate('Default Theme', 'Form element label'), 'multiOptions' => $themes, 'value' => StyleSheet::DEFAULT_THEME));
     $this->addElement('checkbox', 'themes_disabled', array('description' => $this->translate('Check this box for disallowing users to change the theme. If a default theme is set, it will be' . ' used nonetheless', 'Form element description'), 'label' => $this->translate('Users Can\'t Change Theme', 'Form element label')));
     return $this;
 }
 public function init()
 {
     $m = Icinga::app()->getModuleManager();
     if (!$m->hasLoaded('monitoring') && $m->hasInstalled('monitoring')) {
         $m->loadModule('monitoring');
     }
     $this->view->errors = array();
     $this->view->compact = $this->params->get('view') === 'compact';
 }
 /**
  * Returns a ordered list of fields to show in the table
  *
  * @return array
  */
 public function getFields()
 {
     if ($this->fields !== null) {
         return $this->fields;
     }
     $fields = Icinga::app()->getRequest()->getUrl()->getParam('fields');
     $fields = preg_split('/\\s*,\\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY);
     return $this->fields = $fields;
 }
 /**
  * Collect module tabs for all modules containing the given controller
  *
  * @param string $controller        The controller name to use for tab collection
  *
  * @return array                    An array of Tabs objects or arrays containing Tab descriptions
  */
 private static function collectModuleTabs($controller)
 {
     $moduleManager = Icinga::app()->getModuleManager();
     $modules = $moduleManager->listEnabledModules();
     $tabs = array();
     foreach ($modules as $module) {
         $tabs += self::createModuleConfigurationTabs($controller, $moduleManager->getModule($module));
     }
     return $tabs;
 }
Example #21
0
 /**
  * Display exception
  */
 public function errorAction()
 {
     $error = $this->_getParam('error_handler');
     $exception = $error->exception;
     /** @var \Exception $exception */
     Logger::error($exception);
     Logger::error('Stacktrace: %s', $exception->getTraceAsString());
     switch ($error->type) {
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
         case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
             $modules = Icinga::app()->getModuleManager();
             $path = ltrim($this->_request->get('PATH_INFO'), '/');
             $path = preg_split('~/~', $path);
             $path = array_shift($path);
             $this->getResponse()->setHttpResponseCode(404);
             $this->view->message = $this->translate('Page not found.');
             if ($this->Auth()->isAuthenticated() && $modules->hasInstalled($path) && !$modules->hasEnabled($path)) {
                 $this->view->message .= ' ' . sprintf($this->translate('Enabling the "%s" module might help!'), $path);
             }
             break;
         default:
             switch (true) {
                 case $exception instanceof HttpMethodNotAllowedException:
                     $this->getResponse()->setHttpResponseCode(405);
                     $this->getResponse()->setHeader('Allow', $exception->getAllowedMethods());
                     break;
                 case $exception instanceof HttpNotFoundException:
                     $this->getResponse()->setHttpResponseCode(404);
                     break;
                 case $exception instanceof MissingParameterException:
                     $this->getResponse()->setHttpResponseCode(400);
                     $this->getResponse()->setHeader('X-Status-Reason', 'Missing parameter ' . $exception->getParameter());
                     break;
                 case $exception instanceof HttpBadRequestException:
                     $this->getResponse()->setHttpResponseCode(400);
                     break;
                 case $exception instanceof SecurityException:
                     $this->getResponse()->setHttpResponseCode(403);
                     break;
                 default:
                     $this->getResponse()->setHttpResponseCode(500);
                     break;
             }
             $this->view->message = $exception->getMessage();
             if ($this->getInvokeArg('displayExceptions')) {
                 $this->view->stackTrace = $exception->getTraceAsString();
             }
             break;
     }
     if ($this->getRequest()->isApiRequest()) {
         $this->getResponse()->json()->setErrorMessage($this->view->message)->sendResponse();
     }
     $this->view->request = $error->request;
 }
Example #22
0
 /**
  * Load Pane items provided by all enabled modules
  *
  * @return  $this
  */
 public function load()
 {
     $manager = Icinga::app()->getModuleManager();
     foreach ($manager->getLoadedModules() as $module) {
         if ($this->getUser()->can($manager::MODULE_PERMISSION_NS . $module->getName())) {
             $this->mergePanes($module->getPaneItems());
         }
     }
     $this->loadUserDashboards();
     return $this;
 }
Example #23
0
 /**
  * Load Pane items provided by all enabled modules
  *
  * @return  $this
  */
 public function load()
 {
     $manager = Icinga::app()->getModuleManager();
     foreach ($manager->getLoadedModules() as $module) {
         /** @var $module \Icinga\Application\Modules\Module */
         $this->mergePanes($module->getPaneItems());
     }
     if ($this->user !== null) {
         $this->loadUserDashboards();
     }
     return $this;
 }
 protected static function username()
 {
     if (Icinga::app()->isCli()) {
         return 'cli';
     }
     $auth = Auth::getInstance();
     if ($auth->isAuthenticated()) {
         return $auth->getUser()->getUsername();
     } else {
         return '<unknown>';
     }
 }
Example #25
0
 /**
  * Create the StyleSheet
  */
 public function __construct()
 {
     // PHP had a rather conservative PCRE backtrack limit unless 5.3.7
     if (version_compare(PHP_VERSION, '5.3.7') <= 0) {
         ini_set('pcre.backtrack_limit', 1000000);
     }
     $app = Icinga::app();
     $this->app = $app;
     $this->lessCompiler = new LessCompiler();
     $this->pubPath = $app->getBootstrapDirectory();
     $this->collect();
 }
Example #26
0
 /**
  * Get the path to Icinga Web 2's documentation
  *
  * @return string
  */
 protected function getWebPath()
 {
     $path = Icinga::app()->getBaseDir('doc');
     if (is_dir($path)) {
         return $path;
     }
     if (($path = $this->Config()->get('documentation', 'icingaweb2')) !== null) {
         if (is_dir($path)) {
             return $path;
         }
     }
     $this->httpNotFound($this->translate('Documentation for Icinga Web 2 is not available'));
 }
 /**
  * Get the path to Icinga Web 2's documentation
  *
  * @return  string
  *
  * @throws  Zend_Controller_Action_Exception    If Icinga Web 2's documentation is not available
  */
 protected function getPath()
 {
     $path = Icinga::app()->getBaseDir('doc');
     if (is_dir($path)) {
         return $path;
     }
     if (($path = $this->Config()->get('documentation', 'icingaweb2')) !== null) {
         if (is_dir($path)) {
             return $path;
         }
     }
     throw new Zend_Controller_Action_Exception($this->translate('Documentation for Icinga Web 2 is not available'), 404);
 }
 /**
  * Return a list of available navigation item types
  *
  * @return  array
  */
 protected function listItemTypes()
 {
     $moduleManager = Icinga::app()->getModuleManager();
     $types = $this->defaultItemTypes;
     foreach ($moduleManager->getLoadedModules() as $module) {
         if ($this->hasPermission($moduleManager::MODULE_PERMISSION_NS . $module->getName())) {
             $moduleTypes = $module->getNavigationItems();
             if (!empty($moduleTypes)) {
                 $types = array_merge($types, $moduleTypes);
             }
         }
     }
     return $types;
 }
Example #29
0
 /**
  * Creates the assigned key to the resource
  *
  * @param ResourceConfigForm $form
  *
  * @return bool
  */
 public static function beforeAdd(ResourceConfigForm $form)
 {
     $configDir = Icinga::app()->getConfigDir();
     $user = $form->getElement('user')->getValue();
     $filePath = $configDir . '/ssh/' . $user;
     if (!file_exists($filePath)) {
         $file = File::create($filePath, 0600);
     } else {
         $form->error(sprintf($form->translate('The private key for the user "%s" is already exists.'), $user));
         return false;
     }
     $file->fwrite($form->getElement('private_key')->getValue());
     $form->getElement('private_key')->setValue($configDir . '/ssh/' . $user);
     return true;
 }
Example #30
0
 public function apply()
 {
     $moduleManager = Icinga::app()->getModuleManager();
     $moduleManager->detectInstalledModules($this->modulePaths);
     $success = true;
     foreach ($this->moduleNames as $moduleName) {
         try {
             $moduleManager->enableModule($moduleName);
         } catch (Exception $e) {
             $this->errors[$moduleName] = $e;
             $success = false;
         }
     }
     return $success;
 }