protected function addMessage($message, $type = 'info') { if (!in_array($type, array('info', 'error', 'warning', 'success'))) { throw new ProgrammingError(sprintf('"%s" is not a valid notification type', $type)); } if ($this->isCli) { $msg = sprintf('[%s] %s', $type, $message); switch ($type) { case 'info': case 'success': Logger::info($msg); break; case 'warning': Logger::warn($msg); break; case 'error': Logger::error($msg); break; } return; } $mo = (object) array('type' => $type, 'message' => $message); // Get, change, set - just to be on the safe side: $session = Session::getSession(); $msgs = $session->messages; $msgs[] = $mo; $session->messages = $msgs; $session->write(); }
/** * 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)); }
/** * Add an lower priority filter expression to be applied on this query * * The syntax of the expression and valid parameters are to be defined by the concrete * backend-specific query implementation. * * @param string $expression Implementation specific search expression * @param mixed $parameters Implementation specific search value to use for query placeholders * @return self Fluent interface */ public function orWhere($expression, $parameters = null) { $node = $this->parseFilterExpression($expression, $parameters); if ($node === null) { Logger::debug('Ignoring invalid filter expression: %s (params: %s)', $expression, $parameters); return $this; } $this->filter->insert(Node::createOrNode()); $this->filter->insert($node); return $this; }
/** * Detect installed modules from every path provided in modulePaths * * @return self */ public function detectInstalledModules() { foreach ($this->modulePaths as $basedir) { $canonical = realpath($basedir); if ($canonical === false) { Logger::warning('Module path "%s" does not exist', $basedir); continue; } if (!is_dir($canonical)) { Logger::error('Module path "%s" is not a directory', $canonical); continue; } if (!is_readable($canonical)) { Logger::error('Module path "%s" is not readable', $canonical); continue; } if (($dh = opendir($canonical)) !== false) { while (($file = readdir($dh)) !== false) { if ($file[0] === '.') { continue; } if (is_dir($canonical . '/' . $file)) { if (!array_key_exists($file, $this->installedBaseDirs)) { $this->installedBaseDirs[$file] = $canonical . '/' . $file; } else { Logger::debug('Module "%s" already exists in installation path "%s" and is ignored.', $canonical . '/' . $file, $this->installedBaseDirs[$file]); } } } closedir($dh); } } ksort($this->installedBaseDirs); return $this; }
public function setAuthenticated(User $user, $persist = true) { $username = $user->getUsername(); try { $config = IcingaConfig::app(); } catch (NotReadableError $e) { Logger::error(new Exception('Cannot load preferences for user "' . $username . '". An exception was thrown', 0, $e)); $config = new Zend_Config(array()); } if (($preferencesConfig = $config->preferences) !== null) { try { $preferencesStore = PreferencesStore::create($preferencesConfig, $user); $preferences = new Preferences($preferencesStore->load()); } catch (NotReadableError $e) { Logger::error(new Exception('Cannot load preferences for user "' . $username . '". An exception was thrown', 0, $e)); $preferences = new Preferences(); } } else { $preferences = new Preferences(); } $user->setPreferences($preferences); $membership = new Membership(); $groups = $membership->getGroupsByUsername($username); $user->setGroups($groups); $admissionLoader = new AdmissionLoader(); $user->setPermissions($admissionLoader->getPermissions($username, $groups)); $user->setRestrictions($admissionLoader->getRestrictions($username, $groups)); $this->user = $user; if ($persist == true) { $session = Session::getSession(); $session->refreshId(); $this->persistCurrentUser(); } }
/** * Log a message with severity DEBUG * * @param mixed $arg,... A string, exception or format-string + substitutions */ public static function debug() { if (static::$instance !== null && func_num_args() > 0) { static::$instance->log(static::formatMessage(func_get_args()), static::$DEBUG); } }
/** * Register module * * @return bool */ public function register() { $this->registerAutoloader()->registerWebIntegration(); try { $this->launchRunScript(); } catch (Exception $e) { Logger::warning('Launching the run script %s for module %s failed with the following exception: %s', $this->runScript, $this->name, $e->getMessage()); return false; } return true; }
/** * Write the given external command to the command pipe * * @param string $command * * @throws RuntimeException When the command could not be sent to the remote Icinga host * @see Transport::send() */ public function send($command) { $retCode = 0; $output = array(); Logger::debug('Icinga instance is on different host, attempting to send command %s via ssh to %s:%s/%s', $command, $this->host, $this->port, $this->path); $hostConnector = $this->user ? $this->user . "@" . $this->host : $this->host; $command = escapeshellarg('[' . time() . '] ' . $command); $sshCommand = sprintf('ssh -o BatchMode=yes -o KbdInteractiveAuthentication=no %s -p %d' . ' "echo %s > %s" 2>&1', $hostConnector, $this->port, $command, $this->path); exec($sshCommand, $output, $retCode); Logger::debug("Command '%s' exited with %d: %s", $sshCommand, $retCode, $output); if ($retCode != 0) { $msg = 'Could not send command to remote Icinga host: ' . implode(PHP_EOL, $output) . " (returncode {$retCode})"; Logger::error($msg); throw new RuntimeException($msg); } }
/** * Setup internationalization using gettext * * Uses the preferred user language or the configured default and system default, respectively. * * @return self */ protected function setupInternationalization() { parent::setupInternationalization(); if ($this->user !== null && $this->user->getPreferences() !== null && ($locale = $this->user->getPreferences()->get('app.language') !== null)) { try { Translator::setupLocale($locale); } catch (Exception $error) { Logger::warning('Cannot set locale "' . $locale . '" configured in ' . 'preferences of user "' . $this->user->getUsername() . '"'); } } return $this; }
/** * Remove session cookies */ private function clearCookies() { if (ini_get('session.use_cookies')) { Logger::debug('Clear session cookie'); $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']); } }
protected function prepareNewConnection() { $use_tls = false; $force_tls = true; $force_tls = false; if ($use_tls) { $this->prepareTlsEnvironment(); } $ds = ldap_connect($this->hostname, $this->port); $cap = $this->discoverCapabilities($ds); $this->capabilities = $cap; if ($use_tls) { if ($cap->starttls) { if (@ldap_start_tls($ds)) { Logger::debug('LDAP STARTTLS succeeded'); } else { Logger::debug('LDAP STARTTLS failed: %s', ldap_error($ds)); throw new \Exception(sprintf('LDAP STARTTLS failed: %s', ldap_error($ds))); } } elseif ($force_tls) { throw new \Exception(sprintf('TLS is required but not announced by %s', $this->host_name)); } else { // TODO: Log noticy -> TLS enabled but not announced } } // ldap_rename requires LDAPv3: if ($cap->ldapv3) { if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) { throw new Exception('LDAPv3 is required'); } } else { // TODO: remove this -> FORCING v3 for now ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); Logger::warning('No LDAPv3 support detected'); } // Not setting this results in "Operations error" on AD when using the // whole domain as search base: ldap_set_option($ds, LDAP_OPT_REFERRALS, 0); // ldap_set_option($ds, LDAP_OPT_DEREF, LDAP_DEREF_NEVER); return $ds; }
/** * Check if the current user backend is valid, i.e. it's enabled and the config's valid * * @return bool */ public function valid() { if (!$this->config->valid()) { // Stop when there are no more backends to check return false; } $backendConfig = $this->config->current(); if ((bool) $backendConfig->get('disabled', false) === true) { $this->next(); return $this->valid(); } try { $name = $this->key(); $backend = UserBackend::create($name, $backendConfig); } catch (ConfigurationError $e) { Logger::error(new ConfigurationError('Cannot create authentication backend "' . $name . '". An exception was thrown:', 0, $e)); $this->next(); return $this->valid(); } $this->currentBackend = $backend; return true; }
/** * Initialize the internal caches if enabled * * @throws ConfigurationError */ private function initializeCaches() { $defaultCachePath = self::STATUSDAT_DEFAULT_CACHE_PATH; $cachePath = $this->config->get('cache_path', $defaultCachePath); $maxCacheLifetime = intval($this->config->get('cache_path', self::DEFAULT_CACHE_LIFETIME)); $cachingEnabled = true; if (!is_writeable($cachePath)) { Logger::warning('Can\'t cache Status.dat backend; make sure cachepath %s is writable by the web user. ' . 'Caching is now disabled', $cachePath); $cachePath = null; } $backendOptions = array('cache_dir' => $cachePath); // the object cache might exist for months and is still valid $this->objectCache = $this->initCache($this->config->object_file, $backendOptions, null, $cachingEnabled); $this->statusCache = $this->initCache($this->config->status_file, $backendOptions, $maxCacheLifetime, $cachingEnabled); }
protected function setupLogging() { Logger::create(new Zend_Config(array('enable' => true, 'level' => Logger::$INFO, 'type' => 'file', 'target' => 'php://stderr'))); return $this; }
/** * Create or return an instance of a given hook * * TODO: Should return some kind of a hook interface * * @param string $name One of the predefined hook names * @param string $key The identifier of a specific subtype * * @return mixed */ public static function createInstance($name, $key) { if (!self::has($name, $key)) { return null; } if (isset(self::$instances[$name][$key])) { return self::$instances[$name][$key]; } $class = self::$hooks[$name][$key]; try { $instance = new $class(); } catch (Exception $e) { Logger::debug('Hook "%s" (%s) (%s) failed, will be unloaded: %s', $name, $key, $class, $e->getMessage()); // TODO: Persist unloading for "some time" or "current session" unset(self::$hooks[$name][$key]); return null; } self::assertValidHook($instance, $name); self::$instances[$name][$key] = $instance; return $instance; }
/** * Setup internationalization using gettext * * Uses the language defined in the global config or the default one * * @return self */ protected function setupInternationalization() { try { Translator::setupLocale($this->config->global !== null ? $this->config->global->get('language', Translator::DEFAULT_LOCALE) : Translator::DEFAULT_LOCALE); } catch (Exception $error) { Logger::error($error); } $localeDir = $this->getApplicationDir('locale'); if (file_exists($localeDir) && is_dir($localeDir)) { Translator::registerDomain('icinga', $localeDir); } return $this; }