Merge branch 'feature/preferences-backend-4069'

resolves #4069
This commit is contained in:
Johannes Meyer 2013-08-06 12:04:03 +02:00
commit 4befc9be94
21 changed files with 1768 additions and 9 deletions

3
.gitignore vendored
View File

@ -26,3 +26,6 @@ doc/api
# Enabled modules
config/enabledModules/
# User preferences
config/preferences/*.ini

View File

@ -17,3 +17,16 @@ target = /tmp/icinga2.log
debug.enable = 1
debug.type = stream
debug.target = /tmp/icinga2.debug.log
; Use ini store to store preferences on local disk
[preferences]
type=ini
; Use database to store preference into mysql or postgres
;[preferences]
;type=db
;dbtype=pgsql
;dbhost=127.0.0.1
;dbpassword=icingaweb
;dbuser=icingaweb
;dbname=icingaweb

View File

@ -0,0 +1 @@
# Keep this directory

105
doc/preferences.md Normal file
View File

@ -0,0 +1,105 @@
# Preferences
Preferences are user based configuration for Icinga 2 Web. For example max page
items, languages or date time settings can controlled by users.
# Architecture
Preferences are initially loaded from a provider (ini files or database) and
stored into session at login time. After this step preferences are only
persisted to the configured backend, but never reloaded from them.
# Configuration
Preferences can be configured in config.ini in **preferences** section, default
settings are this:
[preferences]
type=ini
The ini provider uses the directory **config/preferences** to create one ini
file per user and persists the data into a single file. If you want to drop your
preferences just drop the file from disk and you'll start with a new profile.
## Database provider
To be more flexible in distributed setups you can store preferences in a
database (pgsql or mysql), a typical configuration looks like the following
example:
[preferences]
type=db
dbtype=pgsql
dbhost=127.0.0.1
dbpassword=icingaweb
dbuser=icingaweb
dbname=icingaweb
### Settings
* **dbtype**: Database adapter, currently supporting ***mysql*** or ***pgsql***
* **dbhost**: Host of the database server, use localhost or 127.0.0.1
for unix socket transport
* **dbpassword**: Password for the configured database user
* **dbuser**: User who can connect to database
* **dbname**: Name of the database
* **port**(optional): For network connections the specific port if not default
(3306 for mysql and 5432 for postgres)
### Preparation
To use this feature you need a running database environment. After creating a
database and a writable user you need to import the initial table file:
* etc/schema/preferences.mysql.sql (for mysql database)
* etc/schema/preferemces.pgsql.sql (for postgres databases)
#### Example for mysql
# mysql -u root -p
mysql> create database icingaweb;
mysql> GRANT SELECT,INSERT,UPDATE,DELETE ON icingaweb.* TO \
'icingaweb'@'localhost' IDENTIFIED BY 'icingaweb';
mysql> exit
# mysql -u root -p icingaweb < /path/to/icingaweb/etc/schema/preferences.mysql.sql
After following these steps above you can configure your preferences provider.
## Coding API
You can set, update or remove preferences using the Preference data object
which is bound to the user. Here are some simple examples how to work with
that:
$preferences = $user->getPreferences();
// Get language with en_US as fallback
$preferences->get('app.language', 'en_US');
$preferences->set('app.language', 'de_DE');
$preferences->remove('app.language');
// Using transactional mode
$preferences->startTransaction();
$preferences->set('test.pref1', 'pref1');
$preferences->set('test.pref2', 'pref2');
$preferences->remove('test.pref3');
$preferemces->commit(); // Stores 3 changes in one operation
More information can be found in the api docs.
## Namespaces and behaviour
If you are using this API please obey the following rules:
* Use dotted notation for preferences
* Namespaces starting with one context identifier
* **app** as global identified (e.g. app.language)
* **mymodule** for your module
* **monitoring** for the monitoring module
* Use preferences wisely (set only when needed and write small settings)
* Use only simple data types, e.g. strings or numbers
* If you need complex types you have to do it your self (e.g. serialization)

View File

@ -0,0 +1,7 @@
create table `preferences`(
`username` VARCHAR(255) NOT NULL,
`preference` VARCHAR(100) NOT NULL,
`value` VARCHAR(255) NOT NULL,
PRIMARY KEY(username, preference)
);

View File

@ -0,0 +1,7 @@
create table "preferences"(
"username" VARCHAR(255) NOT NULL,
"preference" VARCHAR(100) NOT NULL,
"value" VARCHAR(255) NOT NULL,
PRIMARY KEY(username, preference)
);

View File

@ -140,7 +140,7 @@ abstract class ApplicationBootstrap
Benchmark::measure('Bootstrap, autoloader registered');
Icinga::setApp($this);
$this->configDir = $configDir;
$this->configDir = realpath($configDir);
require_once dirname(__FILE__) . '/functions.php';
}
@ -212,10 +212,32 @@ abstract class ApplicationBootstrap
*/
public function getApplicationDir($subdir = null)
{
$dir = $this->appDir;
return $this->getDirWithSubDir($this->appDir, $subdir);
}
/**
* Getter for config dir
* @param string|null $subdir
* @return string
*/
public function getConfigDir($subdir = null)
{
return $this->getDirWithSubDir($this->configDir, $subdir);
}
/**
* Helper to glue directories together
*
* @param string $dir
* @param string|null $subdir
* @return string
*/
private function getDirWithSubDir($dir, $subdir=null)
{
if ($subdir !== null) {
$dir .= '/' . ltrim($subdir, '/');
}
return $dir;
}

View File

@ -29,7 +29,9 @@
namespace Icinga\Application;
use Icinga\Authentication\Manager as AuthenticationManager;
use Icinga\Exception\ConfigurationError;
use Icinga\User\Preferences;
use Icinga\User;
use Icinga\Web\Request;
use Zend_Controller_Front;
use Zend_Layout;
@ -39,6 +41,8 @@ use Zend_Controller_Action_HelperBroker;
use Zend_Controller_Router_Route;
use Zend_Controller_Action_Helper_ViewRenderer;
use Icinga\Web\View;
use Icinga\User\Preferences\StoreFactory;
use Icinga\User\Preferences\SessionStore;
/**
* Use this if you want to make use of Icinga funtionality in other web projects
@ -199,14 +203,13 @@ class Web extends ApplicationBootstrap
}
/**
* Inject dependencies into request
* Create user object and inject preference interface
*
* @return self
* @throws ConfigurationError
* @return User
*/
private function setupRequest()
private function setupUser()
{
$this->request = new Request();
$authenticationManager = AuthenticationManager::getInstance(
null,
array(
@ -215,11 +218,54 @@ class Web extends ApplicationBootstrap
);
if ($authenticationManager->isAuthenticated() === true) {
if ($this->getConfig()->preferences === null) {
throw new ConfigurationError('Preferences not configured in config.ini');
}
$user = $authenticationManager->getUser();
$preferences = new Preferences();
$this->getConfig()->preferences->configPath = $this->getConfigDir('preferences');
$preferenceStore = StoreFactory::create(
$this->getConfig()->preferences,
$user
);
// Needed to update values in user session
$sessionStore = new SessionStore($authenticationManager->getSession());
// Performance: Do not ask provider if we've preferences
// stored in session
$initialPreferences = array();
if (count($sessionStore->load())) {
$initialPreferences = $sessionStore->load();
} else {
$initialPreferences = $preferenceStore->load();
$sessionStore->writeAll($initialPreferences);
}
$preferences = new Preferences($initialPreferences);
$preferences->attach($sessionStore);
$preferences->attach($preferenceStore);
$user->setPreferences($preferences);
return $user;
}
}
/**
* Inject dependencies into request
*
* @return self
*/
private function setupRequest()
{
$this->request = new Request();
$user = $this->setupUser();
if ($user instanceof User) {
$this->request->setUser($user);
}

View File

@ -31,6 +31,7 @@ namespace Icinga\Authentication;
use Icinga\Application\Logger;
use Icinga\Application\Config as IcingaConfig;
use Icinga\Exception\ConfigurationError as ConfigError;
use Icinga\User;
/**
* The authentication manager allows to identify users and

View File

@ -28,9 +28,193 @@
namespace Icinga\User;
use \SplObjectStorage;
use \SplObserver;
use \SplSubject;
use Icinga\User\Preferences\ChangeSet;
use Icinga\Exception\ProgrammingError;
/**
* Handling retrieve and persist of user preferences
*/
class Preferences
class Preferences implements SplSubject, \Countable
{
/**
* Container for all preferences
*
* @var array
*/
private $preferences = array();
/**
* All observers for changes
*
* @var SplObserver[]
*/
private $observer = array();
/**
* Current change set
*
* @var ChangeSet
*/
private $changeSet;
/**
* Flag how commits are handled
*
* @var bool
*/
private $autoCommit = true;
/**
* Create a new instance
* @param array $initialPreferences
*/
public function __construct(array $initialPreferences)
{
$this->preferences = $initialPreferences;
$this->changeSet = new ChangeSet();
}
/**
* Attach an SplObserver
*
* @link http://php.net/manual/en/splsubject.attach.php
* @param SplObserver $observer
*/
public function attach(SplObserver $observer)
{
$this->observer[] = $observer;
}
/**
* Detach an observer
*
* @link http://php.net/manual/en/splsubject.detach.php
* @param SplObserver $observer
*/
public function detach(SplObserver $observer)
{
$key = array_search($observer, $this->observer, true);
if ($key !== false) {
unset($this->observer[$key]);
}
}
/**
* Notify an observer
*
* @link http://php.net/manual/en/splsubject.notify.php
*/
public function notify()
{
/** @var SplObserver $observer */
$observer = null;
foreach ($this->observer as $observer) {
$observer->update($this);
}
}
/**
* Count elements of an object
*
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer
*/
public function count()
{
return count($this->preferences);
}
/**
* Getter for change set
* @return ChangeSet
*/
public function getChangeSet()
{
return $this->changeSet;
}
public function has($key)
{
return array_key_exists($key, $this->preferences);
}
public function set($key, $value)
{
if ($this->has($key)) {
$oldValue = $this->get($key);
// Do not notify useless writes
if ($oldValue !== $value) {
$this->changeSet->appendUpdate($key, $value);
}
} else {
$this->changeSet->appendCreate($key, $value);
}
$this->processCommit();
}
public function get($key, $default = null)
{
if ($this->has($key)) {
return $this->preferences[$key];
}
return $default;
}
public function remove($key)
{
if ($this->has($key)) {
$this->changeSet->appendDelete($key);
$this->processCommit();
return true;
}
return false;
}
public function startTransaction()
{
$this->autoCommit = false;
}
public function commit()
{
$changeSet = $this->changeSet;
if ($this->autoCommit === false) {
$this->autoCommit = true;
}
if ($changeSet->hasChanges() === true) {
foreach ($changeSet->getCreate() as $key => $value) {
$this->preferences[$key] = $value;
}
foreach ($changeSet->getUpdate() as $key => $value) {
$this->preferences[$key] = $value;
}
foreach ($changeSet->getDelete() as $key) {
unset($this->preferences[$key]);
}
$this->notify();
$this->changeSet->clear();
} else {
throw new ProgrammingError('Nothing to commit');
}
}
private function processCommit()
{
if ($this->autoCommit === true) {
$this->commit();
}
}
}

View File

@ -0,0 +1,138 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\User\Preferences;
/**
* Voyager object to transport changes between consumers
*/
class ChangeSet
{
/**
* Stack of pending updates
*
* @var array
*/
private $update = array();
/**
* Stack of pending delete operations
*
* @var array
*/
private $delete = array();
/**
* Stack of pending create operations
*
* @var array
*/
private $create = array();
/**
* Push an update to stack
*
* @param string $key
* @param mixed $value
*/
public function appendUpdate($key, $value)
{
$this->update[$key] = $value;
}
/**
* Getter for pending updates
*
* @return array
*/
public function getUpdate()
{
return $this->update;
}
/**
* Push delete operation to stack
*
* @param string $key
*/
public function appendDelete($key)
{
$this->delete[] = $key;
}
/**
* Get pending delete operations
*
* @return array
*/
public function getDelete()
{
return $this->delete;
}
/**
* Push create operation to stack
*
* @param string $key
* @param mixed $value
*/
public function appendCreate($key, $value)
{
$this->create[$key] = $value;
}
/**
* Get pending create operations
*
* @return array
*/
public function getCreate()
{
return $this->create;
}
/**
* Clear all changes
*/
public function clear()
{
$this->update = array();
$this->delete = array();
$this->create = array();
}
/**
* Test for registered changes
*
* @return bool
*/
public function hasChanges()
{
return (count($this->update) > 0) || (count($this->delete) > 0) || (count($this->create));
}
}

View File

@ -0,0 +1,241 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\User\Preferences;
use Icinga\User;
use SplSubject;
use Zend_Db_Adapter_Abstract;
use Icinga\Exception\ProgrammingError;
use Icinga\User\Preferences;
/**
* Store user preferences in database
*/
class DbStore implements LoadInterface, FlushObserverInterface
{
/**
* Column name for username
*/
const COLUMN_USERNAME = 'username';
/**
* Column name for preference
*/
const COLUMN_PREFERENCE = 'preference';
/**
* Column name for value
*/
const COLUMN_VALUE = 'value';
/**
* User object
*
* @var User
*/
private $user;
/**
* Zend database adapter
*
* @var Zend_Db_Adapter_Abstract
*/
private $dbAdapter;
/**
* Table name
*
* @var string
*/
private $table = 'preferences';
/**
* Setter for user
*
* @param User $user
*/
public function setUser(User $user)
{
$this->user = $user;
}
/**
* Setter for db adapter
*
* @param Zend_Db_Adapter_Abstract $dbAdapter
*/
public function setDbAdapter(Zend_Db_Adapter_Abstract $dbAdapter)
{
$this->dbAdapter = $dbAdapter;
$this->dbAdapter->getProfiler()->setEnabled(true);
}
/**
* Setter for table
*
* @param string $table
*/
public function setTable($table)
{
$this->table = $table;
}
/**
* Load preferences from source
*
* @return array
*/
public function load()
{
$res = $this->dbAdapter->select()->from($this->table)
->where('username=?', $this->user->getUsername())
->query();
$out = array();
foreach ($res->fetchAll() as $row) {
$out[$row[self::COLUMN_PREFERENCE]] = $row[self::COLUMN_VALUE];
}
return $out;
}
/**
* Helper to create zend db suitable where condition
*
* @param string $preference
* @return array
*/
private function createWhereCondition($preference)
{
return array(
self::COLUMN_USERNAME. '=?' => $this->user->getUsername(),
self::COLUMN_PREFERENCE. '=?' => $preference
);
}
/**
* Create operation
*
* @param string $preference
* @param mixed $value
* @return int
*/
private function doCreate($preference, $value)
{
return $this->dbAdapter->insert(
$this->table,
array(
self::COLUMN_USERNAME => $this->user->getUsername(),
self::COLUMN_PREFERENCE => $preference,
self::COLUMN_VALUE => $value
)
);
}
/**
* Update operation
*
* @param string $preference
* @param mixed $value
* @return int
*/
private function doUpdate($preference, $value)
{
return $this->dbAdapter->update(
$this->table,
array(
self::COLUMN_VALUE => $value
),
$this->createWhereCondition($preference)
);
}
/**
* Delete preference operation
*
* @param string $preference
* @return int
*/
private function doDelete($preference)
{
return $this->dbAdapter->delete(
$this->table,
$this->createWhereCondition($preference)
);
}
/**
* Receive update from subject
*
* @link http://php.net/manual/en/splobserver.update.php
* @param SplSubject $subject
* @throws ProgrammingError
*/
public function update(SplSubject $subject)
{
if (!$subject instanceof Preferences) {
throw new ProgrammingError('Not compatible with '. get_class($subject));
}
$changeSet = $subject->getChangeSet();
foreach ($changeSet->getCreate() as $key => $value) {
$retVal = $this->doCreate($key, $value);
if (!$retVal) {
throw new ProgrammingError('Could not create preference value in db: '. $key. '='. $value);
}
}
foreach ($changeSet->getUpdate() as $key => $value) {
$retVal = $this->doUpdate($key, $value);
/*
* Fallback if we switch storage type while user logged in
*/
if (!$retVal) {
$retVal = $this->doCreate($key, $value);
if (!$retVal) {
throw new ProgrammingError('Could not create preference value in db: '. $key. '='. $value);
}
}
}
foreach ($changeSet->getDelete() as $key) {
$retVal = $this->doDelete($key);
if (!$retVal) {
throw new ProgrammingError('Could not delete preference value in db: '. $key);
}
}
}
}

View File

@ -0,0 +1,45 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\User\Preferences;
use Icinga\User;
use \SplObserver;
/**
* Handle preference updates
*/
interface FlushObserverInterface extends SplObserver
{
/**
* Setter for user
*
* @param User $user
*/
public function setUser(User $user);
}

View File

@ -0,0 +1,189 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\User\Preferences;
use \SplObserver;
use \SplSubject;
use Icinga\User;
use Icinga\User\Preferences;
use Icinga\Exception\ConfigurationError;
use Icinga\Exception\ProgrammingError;
use \Zend_Config;
use \Zend_Config_Writer_Ini;
/**
* Handle preferences in ini files
*
* Load and write values from user preferences to ini files
*/
class IniStore implements LoadInterface, FlushObserverInterface
{
/**
* Path to ini configuration
*
* @var string
*/
private $configPath;
/**
* Specific user file for preferences
*
* @var string
*/
private $preferencesFile;
/**
* Config container
*
* @var Zend_Config
*/
private $iniConfig;
/**
* Ini writer
*
* @var Zend_Config_Writer_Ini
*/
private $iniWriter;
/**
* Current user
*
* @var User
*/
private $user;
/**
* Create a new object
*
* @param string|null $configPath
*/
public function __construct($configPath=null)
{
if ($configPath !== null) {
$this->setConfigPath($configPath);
}
}
/**
* Setter for config directory
*
* @param string $configPath
* @throws \Icinga\Exception\ConfigurationError
*/
public function setConfigPath($configPath)
{
if (!is_dir($configPath)) {
throw new ConfigurationError('Config dir dos not exist: '. $configPath);
}
$this->configPath = $configPath;
}
/**
* Setter for user
*
* @param User $user
*/
public function setUser(User $user)
{
$this->user = $user;
$this->preferencesFile = sprintf(
'%s/%s.ini',
$this->configPath,
$this->user->getUsername()
);
if (file_exists($this->preferencesFile) === false) {
$this->createDefaultIniFile();
}
$this->iniConfig = new Zend_Config(
parse_ini_file($this->preferencesFile),
true
);
$this->iniWriter = new Zend_Config_Writer_Ini(
array(
'config' => $this->iniConfig,
'filename' => $this->preferencesFile
)
);
}
/**
* Helper to create blank ini file
*/
private function createDefaultIniFile()
{
touch($this->preferencesFile);
}
/**
* Load preferences from source
*
* @return array
*/
public function load()
{
return $this->iniConfig->toArray();
}
/**
* Receive update from subject
*
* @link http://php.net/manual/en/splobserver.update.php
* @param SplSubject $subject
* @throws ProgrammingError
*/
public function update(SplSubject $subject)
{
if (!$subject instanceof Preferences) {
throw new ProgrammingError('Not compatible with '. get_class($subject));
}
$changeSet = $subject->getChangeSet();
foreach ($changeSet->getCreate() as $key => $value) {
$this->iniConfig->{$key} = $value;
}
foreach ($changeSet->getUpdate() as $key => $value) {
$this->iniConfig->{$key} = $value;
}
foreach ($changeSet->getDelete() as $key) {
unset($this->iniConfig->{$key});
}
// Persist changes to disk
$this->iniWriter->write();
}
}

View File

@ -0,0 +1,42 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\User\Preferences;
/**
* Describe how to load preferences from data sources
*/
interface LoadInterface
{
/**
* Load preferences from source
*
* @return array
*/
public function load();
}

View File

@ -0,0 +1,118 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\User\Preferences;
use Icinga\Authentication\Session;
use \SplObserver;
use \SplSubject;
use Icinga\User\Preferences;
use Icinga\Exception\ProgrammingError;
/**
* Modify preferences into session
*/
class SessionStore implements SplObserver, LoadInterface
{
/**
* Name of session var for preferences
*/
const DEFAULT_SESSION_NAMESPACE = 'preferences';
/**
* Session data
*
* @var Session
*/
private $session;
/**
* Create a new object
*
* @param Session $session
*/
public function __construct(Session $session)
{
$this->session = $session;
}
/**
* Receive update from subject
*
* @link http://php.net/manual/en/splobserver.update.php
* @param SplSubject $subject
* @throws ProgrammingError
*/
public function update(SplSubject $subject)
{
if (!$subject instanceof Preferences) {
throw new ProgrammingError('Not compatible with '. get_class($subject));
}
$changeSet = $subject->getChangeSet();
$data = $this->session->get(self::DEFAULT_SESSION_NAMESPACE, array());
foreach ($changeSet->getCreate() as $key => $value) {
$data[$key] = $value;
}
foreach ($changeSet->getUpdate() as $key => $value) {
$data[$key] = $value;
}
foreach ($changeSet->getDelete() as $key) {
unset($data[$key]);
}
$this->session->set(self::DEFAULT_SESSION_NAMESPACE, $data);
$this->session->write();
}
/**
* Public interface to copy all preferences into session
*
* @param array $preferences
*/
public function writeAll(array $preferences)
{
$this->session->set(self::DEFAULT_SESSION_NAMESPACE, $preferences);
$this->session->write();
}
/**
* Load preferences from source
*
* @return array
*/
public function load()
{
return $this->session->get(self::DEFAULT_SESSION_NAMESPACE, array());
}
}

View File

@ -0,0 +1,112 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\User\Preferences;
use Icinga\User;
use Icinga\Exception\ProgrammingError;
use \Zend_Config;
use \Zend_Db;
/**
* Create preference stores from zend config
*/
final class StoreFactory
{
/**
* Prefix for classes containing namespace
*/
const CLASS_PREFIX = 'Icinga\\User\\Preferences\\';
/**
* Suffix for class
*/
const CLASS_SUFFIX = 'Store';
/**
* Create storage adapter from zend configuration
*
* @param Zend_Config $config
* @param User $user
* @return FlushObserverInterface
* @throws ProgrammingError
*/
public static function create(Zend_Config $config, User $user)
{
$class = self::CLASS_PREFIX. ucfirst($config->get('type')). self::CLASS_SUFFIX;
if (class_exists($class)) {
$store = new $class();
if (!$store instanceof FlushObserverInterface) {
throw new ProgrammingError('Not instance of FlushObserverInterface: '. $class);
}
$items = $config->toArray();
unset($items['type']);
// TODO(mh): Encapsulate into a db adapter factory (#4503)
if (isset($items['dbname'])
&& isset($items['dbuser'])
&& isset($items['dbpassword'])
&& isset($items['dbhost'])
&& isset($items['dbtype'])
) {
$zendDbType = 'PDO_'. strtoupper($items['dbtype']);
$zendDbOptions = array(
'host' => $items['dbhost'],
'username' => $items['dbuser'],
'password' => $items['dbpassword'],
'dbname' => $items['dbname']
);
if (isset($items['port'])) {
$zendDbOptions['port'] = $items['port'];
}
$dbAdapter = Zend_Db::factory($zendDbType, $zendDbOptions);
$items['dbAdapter'] = $dbAdapter;
}
foreach ($items as $key => $value) {
$setter = 'set'. ucfirst($key);
if (is_callable(array($store, $setter))) {
$store->$setter($value);
}
}
$store->setUser($user);
return $store;
}
throw new ProgrammingError('Could not instantiate class: '. $class);
}
}

View File

@ -0,0 +1,93 @@
<?php
namespace Tests\Icinga\User\Preferences;
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences/ChangeSet.php';
use \PHPUnit_Framework_TestCase;
use Icinga\User\Preferences\ChangeSet;
class ChangeSetTest extends PHPUnit_Framework_TestCase
{
public function testAppendCreate()
{
$changeSet = new ChangeSet();
$changeSet->appendCreate('test.key1', 'ok1');
$changeSet->appendCreate('test.key2', 'ok2');
$creates = $changeSet->getCreate();
$this->assertCount(2, $creates);
$this->assertTrue($changeSet->hasChanges());
$this->assertEquals(
array(
'test.key1' => 'ok1',
'test.key2' => 'ok2'
),
$creates
);
}
public function testAppendUpdate()
{
$changeSet = new ChangeSet();
$changeSet->appendUpdate('test.key3', 'ok1');
$changeSet->appendUpdate('test.key4', 'ok2');
$changeSet->appendUpdate('test.key5', 'ok3');
$updates = $changeSet->getUpdate();
$this->assertCount(3, $updates);
$this->assertTrue($changeSet->hasChanges());
$this->assertEquals(
array(
'test.key3' => 'ok1',
'test.key4' => 'ok2',
'test.key5' => 'ok3'
),
$updates
);
}
public function testAppendDelete()
{
$changeSet = new ChangeSet();
$changeSet->appendDelete('test.key6');
$changeSet->appendDelete('test.key7');
$changeSet->appendDelete('test.key8');
$changeSet->appendDelete('test.key9');
$deletes = $changeSet->getDelete();
$this->assertCount(4, $deletes);
$this->assertTrue($changeSet->hasChanges());
$this->assertEquals(
array(
'test.key6',
'test.key7',
'test.key8',
'test.key9',
),
$deletes
);
}
public function testObjectReset()
{
$changeSet = new ChangeSet();
$changeSet->appendCreate('test.key1', 'ok');
$changeSet->appendCreate('test.key2', 'ok');
$changeSet->appendUpdate('test.key3', 'ok');
$changeSet->appendUpdate('test.key4', 'ok');
$changeSet->appendUpdate('test.key5', 'ok');
$changeSet->appendDelete('test.key6');
$changeSet->appendDelete('test.key7');
$changeSet->appendDelete('test.key8');
$this->assertTrue($changeSet->hasChanges());
$changeSet->clear();
$this->assertFalse($changeSet->hasChanges());
}
}

View File

@ -0,0 +1,169 @@
<?php
namespace Tests\Icinga\User\Preferences;
require_once __DIR__. '/../../../../../../library/Icinga/Exception/ConfigurationError.php';
require_once __DIR__. '/../../../../../../library/Icinga/User.php';
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences.php';
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences/LoadInterface.php';
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences/FlushObserverInterface.php';
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences/DbStore.php';
require_once 'Zend/Db.php';
require_once 'Zend/Db/Adapter/Abstract.php';
use Icinga\User;
use Icinga\User\Preferences\DbStore;
use Icinga\User\Preferences;
use \PHPUnit_Framework_TestCase;
use \Zend_Db;
use \Zend_Db_Adapter_Abstract;
use \PDOException;
use \Exception;
class DbStoreTest extends PHPUnit_Framework_TestCase
{
const TYPE_MYSQL = 'mysql';
const TYPE_PGSQL = 'pgsql';
private $database = 'icinga_unittest';
private $table = 'preferences';
private $databaseConfig = array(
'host' => '127.0.0.1',
'username' => 'icinga_unittest',
'password' => 'icinga_unittest',
'dbname' => 'icinga_unittest'
);
/**
* @var Zend_Db_Adapter_Abstract
*/
private $dbMysql;
/**
* @var Zend_Db_Adapter_Abstract
*/
private $dbPgsql;
private function createDb($type)
{
$zendType = 'PDO_'. strtoupper($type);
if ($type === self::TYPE_MYSQL) {
$this->databaseConfig['port'] = 3306;
} elseif ($type === self::TYPE_PGSQL) {
$this->databaseConfig['port'] = 5432;
}
$db = Zend_Db::factory(
$zendType,
$this->databaseConfig
);
try {
$db->getConnection();
$dumpFile = realpath(__DIR__. '/../../../../../../etc/schema/preferences.'. strtolower($type). '.sql');
if (!$dumpFile) {
throw new Exception('Dumpfile for db type not found: '. $type);
}
try {
$db->getConnection()->exec(file_get_contents($dumpFile));
} catch (PDOException $e) {
// PASS
}
} catch (\Zend_Db_Adapter_Exception $e) {
return null;
} catch (PDOException $e) {
return null;
}
return $db;
}
protected function setUp()
{
$this->dbMysql = $this->createDb(self::TYPE_MYSQL);
$this->dbPgsql = $this->createDb(self::TYPE_PGSQL);
}
protected function tearDown()
{
if ($this->dbMysql) {
$this->dbMysql->getConnection()->exec('DROP TABLE '. $this->table);
}
if ($this->dbPgsql) {
$this->dbPgsql->getConnection()->exec('DROP TABLE '. $this->table);
}
}
private function createDbStore(Zend_Db_Adapter_Abstract $db)
{
$user = new User('jdoe');
$store = new DbStore();
$store->setDbAdapter($db);
$store->setUser($user);
return $store;
}
public function testCreateUpdateDeletePreferenceValuesMySQL()
{
if ($this->dbMysql) {
$store = $this->createDbStore($this->dbMysql);
$preferences = new Preferences(array());
$preferences->attach($store);
$preferences->set('test.key1', 'OK1');
$preferences->set('test.key2', 'OK2');
$preferences->set('test.key3', 'OK2');
$preferences->remove('test.key2');
$preferences->set('test.key3', 'OKOK333');
$preferencesTest = new Preferences($store->load());
$this->assertEquals('OK1', $preferencesTest->get('test.key1'));
$this->assertNull($preferencesTest->get('test.key2'));
$this->assertEquals('OKOK333', $preferencesTest->get('test.key3'));
} else {
$this->markTestSkipped('MySQL test environment is not configured');
}
}
public function testCreateUpdateDeletePreferenceValuesPgSQL()
{
if ($this->dbPgsql) {
$store = $this->createDbStore($this->dbPgsql);
$preferences = new Preferences(array());
$preferences->attach($store);
$preferences->set('test.key1', 'OK1');
$preferences->set('test.key2', 'OK2');
$preferences->set('test.key3', 'OK2');
$preferences->remove('test.key2');
$preferences->set('test.key3', 'OKOK333');
$preferencesTest = new Preferences($store->load());
$this->assertEquals('OK1', $preferencesTest->get('test.key1'));
$this->assertNull($preferencesTest->get('test.key2'));
$this->assertEquals('OKOK333', $preferencesTest->get('test.key3'));
} else {
$this->markTestSkipped('PgSQL test environment is not configured');
}
}
}

View File

@ -0,0 +1,130 @@
<?php
namespace Tests\Icinga\User\Preferences;
require_once __DIR__. '/../../../../../../library/Icinga/Exception/ConfigurationError.php';
require_once __DIR__. '/../../../../../../library/Icinga/User.php';
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences.php';
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences/LoadInterface.php';
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences/FlushObserverInterface.php';
require_once __DIR__. '/../../../../../../library/Icinga/User/Preferences/IniStore.php';
require_once 'Zend/Config.php';
require_once 'Zend/Config/Writer/Ini.php';
use Icinga\User;
use Icinga\User\Preferences\IniStore;
use \PHPUnit_Framework_TestCase;
class IniStoreTest extends PHPUnit_Framework_TestCase
{
private $tempDir;
protected function setUp()
{
$tempDir = sys_get_temp_dir();
$this->tempDir = tempnam($tempDir, 'ini-store-test');
if (file_exists($this->tempDir)) {
unlink($this->tempDir);
}
mkdir($this->tempDir);
}
protected function tearDown()
{
if (is_dir($this->tempDir)) {
system('rm -rf '. $this->tempDir);
}
}
private function createTestConfig()
{
$user = new User('jdoe');
$iniStore = new IniStore($this->tempDir);
$iniStore->setUser($user);
$preferences = new User\Preferences(array());
$preferences->attach($iniStore);
$preferences->startTransaction();
$preferences->set('test.key1', 'ok1');
$preferences->set('test.key2', 'ok2');
$preferences->set('test.key3', 'ok3');
$preferences->set('test.key4', 'ok4');
$preferences->commit();
return $preferences;
}
public function testWritePreferencesToFile()
{
$user = new User('jdoe');
$iniStore = new IniStore($this->tempDir);
$iniStore->setUser($user);
$preferences = new User\Preferences(array());
$preferences->attach($iniStore);
$preferences->startTransaction();
$preferences->set('test.key1', 'ok1');
$preferences->set('test.key2', 'ok2');
$preferences->set('test.key3', 'ok3');
$preferences->commit();
$preferences->remove('test.key2');
$file = $this->tempDir. '/jdoe.ini';
$data = (object)parse_ini_file($file);
$this->assertAttributeEquals('ok1', 'test.key1', $data, 'ini contains test.key1');
$this->assertAttributeEquals('ok3', 'test.key3', $data, 'ini contains test.key3');
$this->assertObjectNotHasAttribute('test.key2', $data, 'ini does not contain key test.key2');
}
public function testUpdatePreferencesToFile()
{
$this->createTestConfig();
$user = new User('jdoe');
$iniStore = new IniStore($this->tempDir);
$iniStore->setUser($user);
$preferences = new User\Preferences($iniStore->load());
$preferences->attach($iniStore);
$preferences->startTransaction();
$preferences->remove('test.key1');
$preferences->remove('test.key2');
$preferences->remove('test.key3');
$preferences->set('test.key4', 'ok9898');
$this->assertCount(4, $preferences, 'Before commit we need 4 items');
$preferences->commit();
$this->assertCount(1, $preferences, 'After we need 1 item');
$this->assertEquals('ok9898', $preferences->get('test.key4'), 'After commit preference key has changed');
}
public function testLoadInterface()
{
$this->createTestConfig();
$user = new User('jdoe');
$iniStore = new IniStore($this->tempDir);
$iniStore->setUser($user);
$preferences = new User\Preferences($iniStore->load());
$this->assertEquals('ok4', $preferences->get('test.key4'), 'Test for test.key4');
$this->assertCount(4, $preferences, 'Count 4 items');
}
/**
* @expectedException Icinga\Exception\ConfigurationError
* @expectedExceptionMessage Config dir dos not exist: /path/does/not/exist
*/
public function testInitializationFailure()
{
$iniStore = new IniStore('/path/does/not/exist');
}
}

View File

@ -0,0 +1,93 @@
<?php
namespace Tests\Icinga\User;
require_once __DIR__. '/../../../../../library/Icinga/User/Preferences.php';
require_once __DIR__. '/../../../../../library/Icinga/Exception/ProgrammingError.php';
use \PHPUnit_Framework_TestCase;
use Icinga\User\Preferences;
class PreferencesTest extends PHPUnit_Framework_TestCase
{
public function testInitialPreferences()
{
$preferences = new Preferences(
array(
'test.key1' => 'ok1',
'test.key2' => 'ok2'
)
);
$this->assertCount(2, $preferences);
$this->assertEquals('ok2', $preferences->get('test.key2'));
}
public function testGetDefaultValues()
{
$preferences = new Preferences(array());
$preferences->set('test.key223', 'ok223');
$preferences->set('test.key333', 'ok333');
$this->assertCount(2, $preferences);
$this->assertEquals('ok223', $preferences->get('test.key223'));
$this->assertNull($preferences->get('does.not.exist'));
$this->assertEquals(123123, $preferences->get('does.not.exist', 123123));
}
public function testTransactionalCommit()
{
$preferences = new Preferences(array());
$preferences->startTransaction();
$preferences->set('test.key1', 'ok1');
$preferences->set('test.key2', 'ok2');
$this->assertCount(0, $preferences);
$this->assertCount(2, $preferences->getChangeSet()->getCreate());
$preferences->commit();
$this->assertCount(2, $preferences);
$preferences->startTransaction();
$preferences->remove('test.key2');
$this->assertEquals('ok2', $preferences->get('test.key2'));
$this->assertCount(1, $preferences->getChangeSet()->getDelete());
$preferences->commit();
$this->assertNull($preferences->get('test.key2'));
}
/**
* @expectedException Icinga\Exception\ProgrammingError
* @expectedExceptionMessage Nothing to commit
*/
public function testNothingToCommitException()
{
$preferences = new Preferences(array());
$preferences->commit();
}
public function testSetCreateOrUpdate()
{
$preferences = new Preferences(array());
$preferences->startTransaction();
$preferences->set('test.key1', 'ok1');
$this->assertCount(1, $preferences->getChangeSet()->getCreate());
$this->assertCount(0, $preferences->getChangeSet()->getUpdate());
$preferences->commit();
$preferences->startTransaction();
$preferences->set('test.key1', 'ok2');
$this->assertCount(0, $preferences->getChangeSet()->getCreate());
$this->assertCount(1, $preferences->getChangeSet()->getUpdate());
$preferences->commit();
}
}