Initial checking from CVS

This commit is contained in:
Deon George
2011-01-14 01:45:19 +11:00
commit fe11dd5f51
70 changed files with 10950 additions and 0 deletions

283
lib/common.php Normal file
View File

@@ -0,0 +1,283 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/common.php,v 1.18 2009/04/19 04:12:19 wurley Exp $
/**
* Contains code to be executed at the top of each application page.
* include this file at the top of every PHP file.
*
* This file will "pre-initialise" an application environment so that any PHP file will have a consistent
* environment with other application PHP files.
*
* This code WILL NOT check that all required functions are usable/readable, etc. This process has
* been moved to index.php (which really is only called once when a browser hits the application for the first time).
*
* @author Deon George (c) 2009
* @package phpTSMadmin
*/
/**
* @package phpTSMadmin
*/
/* Initialize the app array. The app array is initialised each invocation of a PLA script and therefore
has no state between invocations.*/
$app = array();
# The index we will store our config in $_SESSION
if (! defined('APPCONFIG'))
define('APPCONFIG','appConfig');
/**
* Catch any scripts that are called directly.
* If they are called directly, then they should be routed back through index.php
*/
$app['direct_scripts'] = array('cmd.php','index.php',
'image.dbbackuphistory.php','image.occupancy.php','image.backupevents.php','image.schedule.gantt.php'
);
# Which script was invoked.
$app['script_running'] = $_SERVER['SCRIPT_NAME'];
foreach ($app['direct_scripts'] as $script) {
$app['scriptOK'] = false;
if (preg_match('/'.$script.'$/',$app['script_running'])) {
$app['scriptOK'] = true;
break;
}
}
# Anything in the tools dir or cron dir can be executed directly.
if ((! $app['scriptOK'] && preg_match('/^\/[cron|tools]/',$app['script_running'])) || ! isset($_SERVER['SERVER_SOFTWARE']))
$app['scriptOK'] = true;
if (! $app['scriptOK']) {
if (isset($_REQUEST['server_id']))
header(sprintf('Location: index.php?server_id=%s',$_REQUEST['server_id']));
else
header('Location: index.php');
die();
}
/**
* All commands are disabled in read-only unless specified here
*/
$app['readwrite_cmds'] = array(
);
/**
* Timer stopwatch, used to instrument the application
*/
if (! function_exists('stopwatch')) {
function stopwatch() {
static $mt_previous = 0;
list($usec,$sec) = explode(' ',microtime());
$mt_current = (float)$usec + (float)$sec;
if (! $mt_previous) {
$mt_previous = $mt_current;
return 0;
} else {
$mt_diff = ($mt_current - $mt_previous);
$mt_previous = $mt_current;
return sprintf('%.5f',$mt_diff);
}
}
# For compatability - if common has been sourced a second time, then return to the calling script.
} else {
return;
}
# Set the defualt time zone, if it isnt set in php.ini
if (function_exists('date_default_timezone_set') && ! ini_get('date.timezone'))
date_default_timezone_set('UTC');
# If we are called from index.php, LIBDIR will be set, all other calls to common.php dont need to set it.
if (! defined('LIBDIR'))
define('LIBDIR','../lib/');
# For PHP5 backward/forward compatibility
if (! defined('E_STRICT'))
define('E_STRICT',2048);
# General functions needed to proceed.
ob_start();
require_once realpath(LIBDIR.'functions.php');
if (ob_get_level())
ob_end_clean();
/**
* Turn on all notices and warnings. This helps us write cleaner code (we hope at least)
* Our custom error handler receives all error notices that pass the error_reporting()
* level set above.
*/
# Call our custom defined error handler, if it is defined in functions.php
if (function_exists('app_error_handler'))
set_error_handler('app_error_handler');
# Disable error reporting until all our required functions are loaded.
error_reporting(0);
/**
* functions.php should have defined our $app['function_files'] array, listing all our
* required functions (order IS important).
* index.php should have checked they exist and are usable - we'll assume that the user
* has been via index.php, and fixed any problems already.
*/
ob_start();
if (isset($app['function_files']) && is_array($app['function_files']))
foreach ($app['function_files'] as $script)
require_once realpath($script);
# Now read in config_default.php
require_once realpath(LIBDIR.'config_default.php');
if (ob_get_level())
ob_end_clean();
# We are now ready for error reporting.
error_reporting(E_ALL);
# Start our session.
app_session_start();
# If we get here, and $_SESSION[APPCONFIG] is not set, then redirect the user to the index.
if (isset($_SERVER['SERVER_SOFTWARE']) && ! isset($_SESSION[APPCONFIG])) {
if ($_SERVER['QUERY_STRING'])
header(sprintf('Location: index.php?URI=%s',base64_encode($_SERVER['QUERY_STRING'])));
else
header('Location: index.php');
die();
} else {
# Check our custom variables.
# @todo Change this so that we dont process a cached session.
$_SESSION[APPCONFIG]->CheckCustom();
}
# Check for safe mode.
if (ini_get('safe_mode') && ! get_request('cmd','GET'))
system_message(array(
'title'=>_('PHP Safe Mode'),
'body'=>_('You have PHP Safe Mode enabled. This application may work unexpectedly in Safe Mode.'),
'type'=>'info'));
# Set our timezone, if it is specified in config.php
if ($_SESSION[APPCONFIG]->getValue('appearance','timezone'))
date_default_timezone_set($_SESSION[APPCONFIG]->getValue('appearance','timezone'));
# If we are here, $_SESSION is set - so enabled DEBUGing if it has been configured.
if (($_SESSION[APPCONFIG]->getValue('debug','syslog') || $_SESSION[APPCONFIG]->getValue('debug','file'))
&& $_SESSION[APPCONFIG]->getValue('debug','level'))
define('DEBUG_ENABLED',1);
else
define('DEBUG_ENABLED',0);
if (DEBUG_ENABLED)
debug_log('Application (%s) initialised and starting with (%s).',1,__FILE__,__LINE__,__METHOD__,
app_version(),$_REQUEST);
# Set our PHP timelimit.
if ($_SESSION[APPCONFIG]->getValue('session','timelimit') && ! ini_get('safe_mode'))
set_time_limit($_SESSION[APPCONFIG]->getValue('session','timelimit'));
# If debug mode is set, increase the time_limit, since we probably need it.
if (DEBUG_ENABLED && $_SESSION[APPCONFIG]->getValue('session','timelimit') && ! ini_get('safe_mode'))
set_time_limit($_SESSION[APPCONFIG]->getValue('session','timelimit') * 5);
/**
* Language configuration. Auto or specified?
* Shall we attempt to auto-determine the language?
*/
# If we are in safe mode, and LANG is not in the allowed vars, display an error.
if (ini_get('safe_mode') && ! in_array('LANG',explode(',',ini_get('safe_mode_allowed_env_vars'))))
error('You are running in SAFE_MODE, but LANG is not in the safe_mode_allowed_env_vars. Please add LANG to safe_mode_allowed_env_vars','error',true,false);
$app['language'] = $_SESSION[APPCONFIG]->getValue('appearance','language');
if ($app['language'] == 'auto') {
# Make sure their browser correctly reports language. If not, skip this.
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
# Get the languages which are spetcified in the HTTP header
$app['lang_http'] = preg_split ('/[;,]+/',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($app['lang_http'] as $key => $value) {
if (substr($value,0,2) == 'q=') {
unset($app['lang_http'][$key]);
continue;
}
$value = preg_split('/[-]+/',$value);
if (sizeof($value) == 2)
$app['lang_http'][$key] = strtolower($value[0]).'_'.strtoupper($value[1]);
else
$app['lang_http'][$key] = auto_lang(strtolower($value[0]));
}
$app['lang_http'] = array_unique($app['lang_http']);
foreach ($app['lang_http'] as $lang) {
$app['language_dir'] = LANGDIR.$lang;
if ((substr($lang,0,2) == 'en') ||
(file_exists($app['language_dir']) && is_readable($app['language_dir']))) {
# Set language
putenv('LANG='.$lang); # e.g. LANG=de_DE
$lang .= '.UTF-8';
setlocale(LC_ALL,$lang); # set LC_ALL to de_DE
bindtextdomain('messages',LANGDIR);
bind_textdomain_codeset('messages','UTF-8');
textdomain('messages');
header('Content-type: text/html; charset=UTF-8',true);
break;
}
}
#todo Generate an error if language doesnt exist.
}
} else {
# Grab the language file configured in config.php
#todo Generate an error if language doesnt exist.
if ($app['language'] != null) {
if (strcmp($app['language'],'english') == 0)
$app['language'] = 'en_GB';
# Set language
putenv('LANG='.$app['language']); # e.g. LANG=de_DE
$app['language'] .= '.UTF-8';
setlocale(LC_ALL,$app['language']); # set LC_ALL to de_DE
bindtextdomain('messages',LANGDIR);
bind_textdomain_codeset('messages','UTF-8');
textdomain('messages');
header('Content-type: text/html; charset=UTF-8',true);
}
}
/**
* Strip slashes from GET, POST, and COOKIE variables if this
* PHP install is configured to automatically addslashes()
*/
if (get_magic_quotes_gpc() && (! isset($slashes_stripped) || ! $slashes_stripped)) {
array_stripslashes($_REQUEST);
array_stripslashes($_GET);
array_stripslashes($_POST);
array_stripslashes($_COOKIE);
$slashes_stripped = true;
}
# Create our application repository variable.
$app['server'] = $_SESSION[APPCONFIG]->getServer(get_request('server_id','REQUEST'));
/**
* At this point we have read all our additional function PHP files and our configuration.
* If we are using hooks, run the session_init hook.
*/
if (function_exists('run_hook'))
run_hook('post_session_init',array());
?>

75
lib/config_custom.php Normal file
View File

@@ -0,0 +1,75 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/config_custom.php,v 1.3 2009/04/19 05:32:12 wurley Exp $
/**
* Custom Configuration processing and defaults.
*
* @author The phpTSMadmin development team
* @package phpTSMadmin
*/
/** Available Commands
*/
$config->configDefinition('command','devclassinfo',array(
'summary'=>'Device Class Info',
'desc'=>'This will show detailed information on your devclasses.',
'default'=>'devclass.info'));
$config->configDefinition('command','help',array(
'summary'=>'Help',
'desc'=>'Help Pages',
'default'=>'help'));
$config->configDefinition('command','libraryinfo',array(
'summary'=>'Library Info',
'desc'=>'Information on Automated Tape Libraries.',
'default'=>'library.info'));
$config->configDefinition('command','nodedetail',array(
'summary'=>'Node Detail',
'desc'=>'Detail of Node Storage Usage.',
'default'=>'node.detail'));
$config->configDefinition('command','nodeoccupancy',array(
'summary'=>'Node Occupancy',
'desc'=>'Summary of Node Occupancy.',
'default'=>'node.occupancy'));
$config->configDefinition('command','nodesummary',array(
'summary'=>'Node Summary',
'desc'=>'Summary of Node activities.',
'default'=>'node.summary'));
$config->configDefinition('command','nodethruput',array(
'summary'=>'Node Traffic',
'desc'=>'This will show recent node traffic.',
'default'=>'node.thruput'));
$config->configDefinition('command','schedulegantt',array(
'summary'=>'Schedule Gantt',
'desc'=>'Gantt view of todays schedules.',
'default'=>'schedule.gantt'));
$config->configDefinition('command','summarygantt',array(
'summary'=>'Activity Summary Gantt',
'desc'=>'Gantt view of todays activities.',
'default'=>'summary.gantt'));
$config->configDefinition('command','serverdb',array(
'summary'=>'Server DB Information',
'desc'=>'Database Information for TSM Server.',
'default'=>'server.db'));
$config->configDefinition('command','serverstats',array(
'summary'=>'Server Stats',
'desc'=>'TSM Server Performance Stats.',
'default'=>'server.stats'));
$config->configDefinition('command','volumeinfo',array(
'summary'=>'Volume Status',
'desc'=>'Status Information on Sequential Volumes.',
'default'=>'volume.info'));
$config->configDefinition('command','volumeinventory',array(
'summary'=>'Volume Inventory',
'desc'=>'Information on Volumes.',
'default'=>'volume.inventory'));
$config->configDefinition('lib','jpgraph',array(
'desc'=>'Path to JPGraph',
'default'=>LIBDIR.'JpGraph'));
$config->configDefinition('image','path',array(
'desc'=>'Path to generated images',
'default'=>HTDOCDIR.'tmp'));
$config->configDefinition('image','pathurl',array(
'desc'=>'URL Path to generated images',
'default'=>'tmp/'));
?>

337
lib/config_default.php Normal file
View File

@@ -0,0 +1,337 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/config_default.php,v 1.16 2009/04/19 05:44:55 wurley Exp $
/**
* Configuration processing and defaults.
*
* @author The phpTSMadmin development team
* @package phpTSMadmin
*
* @todo Add validation of set variables to enforce limits or particular values.
*/
/** The minimum version of PHP required to run this application. */
define('REQUIRED_PHP_VERSION','5.0.0');
/**
* The config class contains all our configuration settings for a session.
*
* An instance of this class should be stored in $_SESSION to maintain state, and to avoid
* rebuilding/rereading it at the state of each page output.
*
* @package phpTSMadmin
*
* @author The phpTSMadmin development team
* @author Deon George
*/
class Config {
public $custom;
protected $default;
public $servers = array();
public $hooks = array();
public function __construct() {
$this->custom = new stdClass;
$this->default = new stdClass;
$this->default->app['name'] = array(
'desc'=>'Application Name',
'default'=>'phpTSMadmin');
$this->default->appearance['compress'] = array(
'desc'=>'Compress Output',
'default'=>false);
$this->default->appearance['control_icons'] = array(
'desc'=>'Show the control as icons or text',
'default'=>false);
$this->default->appearance['menu'] = array(
'desc'=>'Class name which inherits from Menu class and implements the draw() method',
'default'=>'menu_html');
/** Language
* The language setting. If you set this to 'auto', This application will
* attempt to determine your language automatically. Otherwise, set
* this to your applicable language in xx_XX format.
*/
$this->default->appearance['language'] = array(
'desc'=>'Language',
'default'=>'auto');
$this->default->appearance['page_title'] = array(
'desc'=>'Change the page title to this text',
'default'=>'');
$this->default->appearance['stylesheet'] = array(
'desc'=>'Style sheet to use',
'default'=>'style.css');
$this->default->appearance['timezone'] = array(
'desc'=>'Define our timezone, if not defined in php.ini',
'default'=>null);
$this->default->appearance['logged_in_chars'] = array(
'desc'=>'Number of chars of loggin name to show',
'default'=>15);
/** Caching
*/
$this->default->cache['menu'] = array(
'desc'=>'Cache the Menu',
'default'=>false);
$this->default->cache['time'] = array(
'desc'=>'How long to cache our TSM queries',
'default'=>600);
/** Commands
* Define which high level commands are available.
*/
$this->default->commands['all'] = array(
'desc'=>'Define command availability',
'default'=> array(
'home' => true,
'login' => true,
'logout' => true,
'purge' => true,
'showcache' => true,
'register' => true
));
/** Debug Attributes
* Attributes that control debugging
*/
$this->default->debug['level'] = array(
'desc'=>'Debug level verbosity',
'default'=>0);
$this->default->debug['syslog'] = array(
'desc'=>'Whether to send debug messages to syslog',
'default'=>false);
$this->default->debug['file'] = array(
'desc'=>'Name of file to send debug output to',
'default'=>null);
$this->default->debug['addr'] = array(
'desc'=>'IP address of client to provide debugging info.',
'default'=>null);
$this->default->debug['append'] = array(
'desc'=>'Whether to append to the debug file, or create it fresh each time',
'default'=>true);
$this->default->debug['show_cache'] = array(
'desc'=>'Show the tool that shows debugging information.',
'default'=>false);
/** Session Attributes
* Session related attributes.
*/
$this->default->session['blowfish'] = array(
'desc'=>'Blowfish key to encrypt cookie details',
'default'=>null);
$this->default->session['memorylimit'] = array(
'desc'=>'Set the PHP memorylimit warning threshold.',
'default'=>24);
$this->default->session['timelimit'] = array(
'desc'=>'Set the PHP timelimit.',
'default'=>30);
/** Cookie Time
* If you used auth_type 'form' in the servers list, you can adjust how long the cookie will last
* (default is 0 seconds, which expires when you close the browser)
*/
$this->default->session['cookie_time'] = array(
'desc'=>'Time in seconds for the life of cookies',
'default'=>0);
/** Session Menu
*/
$this->default->menu['session'] = array(
'desc'=>'Menu items when logged in.',
'default'=>array(
'info'=>array('php'=>'info.php','icon'=>'info.png','text'=>'Server Info')
));
/** Available Commands
*/
}
/**
* Access the configuration, taking into account the defaults and the customisations
*/
private function getConfigArray($usecache=true) {
static $CACHE = array();
if ($usecache && count($CACHE))
return $CACHE;
foreach ($this->default as $key => $vals)
$CACHE[$key] = $vals;
foreach ($this->custom as $key => $vals)
foreach ($vals as $index => $val)
$CACHE[$key][$index]['value'] = $val;
return $CACHE;
}
/**
* Get a configuration value.
*/
public function getValue($key,$index,$fatal=true) {
$config = $this->getConfigArray();
if (! isset($config[$key]))
if ($fatal)
error(sprintf('A call was made in [%s] to getValue requesting [%s] that isnt predefined.',
basename($_SERVER['PHP_SELF']),$key),'error',null,true);
else
return null;
if (! isset($config[$key][$index]))
if ($fatal)
error(sprintf('Requesting an index [%s] in key [%s] that isnt predefined.',$index,$key),'error',null,true);
else
return null;
return isset($config[$key][$index]['value']) ? $config[$key][$index]['value'] : $config[$key][$index]['default'];
}
/**
* Return the untested config items
*/
public function untested() {
$result = array();
foreach ($this->default as $option => $details)
foreach ($details as $param => $values)
if (isset($values['untested']) && $values['untested'])
array_push($result,sprintf('%s.%s',$option,$param));
return $result;
}
/**
* Function to check and warn about any unusual defined variables.
*/
public function CheckCustom() {
if (isset($this->custom)) {
foreach ($this->custom as $masterkey => $masterdetails) {
if (isset($this->default->$masterkey)) {
if (! is_array($masterdetails))
error(sprintf('Error in configuration file, [%s] should be an ARRAY.',$masterdetails),'error',null,true);
foreach ($masterdetails as $key => $value) {
# Test that the key is correct.
if (! in_array($key,array_keys($this->default->$masterkey)))
error(sprintf('Error in configuration file, [%s] has not been defined as a configurable variable.',$key),'error',null,true);
# Test if its should be an array or not.
if (is_array($this->default->{$masterkey}[$key]['default']) && ! is_array($value))
error(sprintf('Error in configuration file, %s[\'%s\'] SHOULD be an array of values.',$masterkey,$key),'error',null,true);
if (! is_array($this->default->{$masterkey}[$key]['default']) && is_array($value))
error(sprintf('Error in configuration file, %s[\'%s\'] should NOT be an array of values.',$masterkey,$key),'error',null,true);
}
} else {
error(sprintf('Error in configuration file, [%s] has not been defined as a MASTER configurable variable.',$masterkey),'error',null,true);
}
}
}
}
/**
* Get a list of available commands.
*/
public function getCommandList() {
$config = $this->getConfigArray(false);
masort($config['command'],'summary');
if (isset($config['command']) && is_array($config['command']))
return $config['command'];
else
return array();
}
/**
* The parameter number is variable.
* For example : isCommandAvailable('search','simple_search')
*/
public function isCommandAvailable($index='all') {
$a = func_get_args();
if (! in_array($index,array('all','script')))
$index = 'all';
else
array_shift($a);
if (count($a) == 1 && is_array($a[0]))
$a = $a[0];
$i = 0;
# Command availability list
$cmd = $this->getValue('commands',$index);
# Search for the command
while ($i < count($a)) {
if (! is_array($cmd))
return $cmd;
if (! isset($cmd[$a[$i]]))
return false;
$cmd = $cmd[$a[$i]];
$i++;
}
# If this is a leaf command, return its availability
if (! is_array($cmd))
return $cmd;
# Else the command is available, if one of its sub-command is available
$a[] = '';
foreach ($cmd as $c => $v) {
$a[$i] = $c;
if ($this->isCommandAvailable($a))
return true;
}
return false;
}
public function configDefinition($key,$index,$config) {
if (! is_array($config) || ! array_key_exists('desc',$config) || ! array_key_exists('default',$config))
return;
if (isset($this->default->$key))
$definition = $this->default->$key;
$definition[$index] = $config;
$this->default->$key = $definition;
}
public function setServers($servers) {
$this->servers = $servers;
}
public function getServer($index=null) {
return $this->servers->Instance($index);
}
/**
* Return a list of our servers
* @param boolean $visible - Only return visible servers
*/
public function getServerList($visible=true) {
return $this->servers->getServerList($visible);
}
}
?>

501
lib/ds.php Normal file
View File

@@ -0,0 +1,501 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/ds.php,v 1.5 2009/04/19 04:15:21 wurley Exp $
/**
* Classes and functions for communication of Data Stores
*
* @author Deon George (c) 2009
* @package phpTSMadmin
*/
/**
* This abstract class provides the basic variables and methods.
*
* @package phpTSMadmin
* @subpackage DataStore
*/
abstract class DS {
# ID of this db.
protected $index;
# Configuration paramters.
protected $default;
protected $custom;
protected $type;
abstract function __construct($index);
/**
* This will make the connection to the datasource
*/
abstract protected function connect($method,$debug=false);
/**
* Login to the datastore
* method: default = anon, connect to ds using bind_id not auth_id.
* method: 'user', connect with auth_id
* method: '<freetext>', any custom extra connection to ds.
*/
abstract public function login($user=null,$pass=null,$method=null);
/**
* Query the datasource
*/
abstract public function query($query,$method,$index=null,$debug=false);
/**
* Return error details from previous operation
*/
abstract protected function getErrorMessage();
abstract protected function getErrorNum();
/**
* Functions that set and verify object configuration details
*/
public function setDefaults($defaults) {
foreach ($defaults as $key => $details)
foreach ($details as $setting => $value)
$this->default->{$key}[$setting] = $value;
}
public function isDefaultKey($key) {
return isset($this->default->$key);
}
public function isDefaultSetting($key,$setting) {
return array_key_exists($setting,$this->default->{$key});
}
/**
* Return a configuration value
*/
public function getValue($key,$setting,$fatal=true) {
if (isset($this->custom->{$key}[$setting]))
return $this->custom->{$key}[$setting];
elseif (isset($this->default->{$key}[$setting]) && array_key_exists('default',$this->default->{$key}[$setting]))
return $this->default->{$key}[$setting]['default'];
else {
if ($fatal)
debug_dump_backtrace("Error trying to get a non-existant value ($key,$setting)",1);
else
return null;
}
}
/**
* Set a configuration value
*/
public function setValue($key,$setting,$value) {
if (isset($this->custom->{$key}[$setting]))
system_message(array(
'title'=>_('Configuration setting already defined.'),
'body'=>sprintf('A call has been made to reset a configuration value (%s,%s,%s)',
$key,$setting,$value),
'type'=>'info'));
$this->custom->{$key}[$setting] = $value;
}
/**
* Return the untested config items
*/
public function untested() {
$result = array();
foreach ($this->default as $option => $details)
foreach ($details as $param => $values)
if (isset($values['untested']) && $values['untested'])
array_push($result,sprintf('%s.%s',$option,$param));
return $result;
}
/**
* Get the name of this datastore
*/
public function getName() {
return $this->getValue('server','name');
}
/**
* Functions that enable login and logout of the application
*/
/**
* Return the authentication type for this object
*/
public function getAuthType() {
switch ($this->getValue('login','auth_type')) {
case 'config' :
case 'session' :
return $this->getValue('login','auth_type');
default :
die(sprintf('Error: <b>%s</b> hasnt been configured for auth_type <b>%s</b>',__METHOD__,
$this->getValue('login','auth_type')));
}
}
/**
* Get the login name of the user logged into this datastore's connection method
*/
public function getLogin($method=null) {
$method = $this->getMethod($method);
switch ($this->getAuthType()) {
case 'config' :
return $this->getValue('login','bind_id');
case 'session' :
if (! isset($_SESSION['USER'][$this->index][$method]['name']))
return null;
return $_SESSION['USER'][$this->index][$method]['name'];
default :
die(sprintf('Error: %s hasnt been configured for auth_type %s',__METHOD__,$this->getAuthType()));
}
}
/**
* Set the login details of the user logged into this datastore's connection method
*/
protected function setLogin($user,$pass,$method=null) {
$method = $this->getMethod($method);
switch ($this->getAuthType()) {
case 'config' :
case 'session' :
$_SESSION['USER'][$this->index][$method]['name'] = $user;
$_SESSION['USER'][$this->index][$method]['pass'] = $pass;
return true;
default :
die(sprintf('Error: %s hasnt been configured for auth_type %s',__METHOD__,$this->getAuthType()));
}
}
/**
* Get the login password of the user logged into this datastore's connection method
*/
protected function getPassword($method=null) {
$method = $this->getMethod($method);
switch ($this->getAuthType()) {
case 'config' :
return $this->getValue('login','bind_pass');
case 'session' :
return (isset($_SESSION['USER'][$this->index][$method]['pass'])) ? $_SESSION['USER'][$this->index][$method]['pass'] : null;
default :
die(sprintf('Error: %s hasnt been configured for auth_type %s',__METHOD__,$this->getAuthType()));
}
}
/**
* Return if this datastore's connection method has been logged into
*/
public function isLoggedIn($method=null) {
$method = $this->getMethod($method);
return is_null($this->getLogin($method)) ? false : true;
}
/**
* Logout of this datastore's connection method
*/
public function logout($method) {
$method = $this->getMethod($method);
switch ($this->getAuthType()) {
case 'config' :
return true;
case 'session' :
if (isset($_SESSION['USER'][$this->index][$method]))
unset($_SESSION['USER'][$this->index][$method]);
return true;
default :
die(sprintf('Error: %s hasnt been configured for auth_type %s',__METHOD__,$this->getAuthType()));
}
}
/**
* Functions that return the condition of the datasource
*/
public function isVisible() {
return $this->getValue('server','visible');
}
public function isReadOnly() {
return $this->getValue('server','read_only');
}
public function getIndex() {
return $this->index;
}
/**
* Work out which connection method to use.
* If a method is passed, then it will be passed back. If no method is passed, then we'll
* check to see if the user is logged in. If they are, then 'user' is used, otherwise
* 'anon' is used.
*
* @param int Server ID
* @return string Connection Method
*/
protected function getMethod($method=null) {
# Immediately return if method is set.
if (! is_null($method))
return $method;
if ($this->isLoggedIn('user'))
return 'user';
else
return 'anon';
}
/**
* Get a attribute value from a query
*/
public function getAttrValue($query,$attr,$method=null,$debug=false) {
$result = $this->query($query,$method,$attr,$debug);
if ($debug)
debug_dump(array('query'=>$query,'result'=>$result));
if (count($result) > 1)
system_message(array(
'title'=>_('Invalid call to function.'),
'body'=>sprintf('%s should have return 0 or 1 value, but return %s (%s)<br />(%s)',
__METHOD__,count($result),serialize($result),serialize($query)),
'type'=>'info'));
else
foreach ($result as $key => $value)
return $value;
}
}
/**
* The list of database sources
*
* @package leenooksApp
* @subpackage DataStore
*/
class Datastore {
# Out DS index id
private $index;
# List of all the objects
private $objects = array();
# Default settings
private $default;
public function __construct() {
$this->default = new StdClass;
$this->default->server['id'] = array(
'desc'=>'Server ID',
'default'=>null);
$this->default->server['name'] = array(
'desc'=>'Server name',
'default'=>null);
# Connectivity Info
$this->default->server['host'] = array(
'desc'=>'Host Name',
'default'=>'127.0.0.1');
$this->default->server['port'] = array(
'desc'=>'Port Number',
'default'=>null);
# Read or write only access
$this->default->server['read_only'] = array(
'desc'=>'Server is in READ ONLY mode',
'default'=>false);
$this->default->server['visible'] = array(
'desc'=>'Whether this server is visible',
'default'=>true);
# Authentication Information
$this->default->login['auth_type'] = array(
'desc'=>'Authentication Type',
'default'=>'session');
/*
/* ID to login to this application, this assumes that there is
* application authentication on top of authentication required to
* access the data source **
$this->default->login['auth_id'] = array(
'desc'=>'User Login ID to login to this DS',
'default'=>null);
$this->default->login['auth_pass'] = array(
'desc'=>'User Login Password to login to this DS',
'default'=>null);
*/
$this->default->login['auth_text'] = array(
'desc'=>'Text to show at the login prompt',
'default'=>'User Name');
$this->default->login['bind_id'] = array(
'desc'=>'User Login ID to bind to this DS',
'default'=>null);
$this->default->login['bind_pass'] = array(
'desc'=>'User Login Password to bind to this DS',
'default'=>null);
$this->default->login['timeout'] = array(
'desc'=>'Session timout in seconds',
'default'=>session_cache_expire()-1);
# Location to custom pages
$this->default->custom['pages_prefix'] = array(
'desc'=>'Prefix name for custom pages',
'default'=>null);
}
/**
* Create a new database object
*/
public function newServer($type) {
if (class_exists($type)) {
$this->index = count($this->objects)+1;
$this->objects[$this->index] = new $type($this->index);
$this->objects[$this->index]->setDefaults($this->default);
return $this->index;
} else {
printf('ERROR: Class [%s] doesnt exist',$type);
die();
}
}
/**
* Set values for a database object.
*/
public function setValue($key,$setting,$value) {
if (defined('DEBUG_ENABLED') && (DEBUG_ENABLED))
debug_log('Entered with (%s,%s,%s)',3,__FILE__,__LINE__,__METHOD__,
$key,$setting,$value);
if (! $this->objects[$this->index]->isDefaultKey($key))
error("ERROR: Setting a key [$key] that isnt predefined.",'error',true);
if (! $this->objects[$this->index]->isDefaultSetting($key,$setting))
error("ERROR: Setting a index [$key,$setting] that isnt predefined.",'error',true);
# Test if its should be an array or not.
if (is_array($this->objects[$this->index]->getValue($key,$setting)) && ! is_array($value))
error("Error in configuration file, {$key}['$this->index'] SHOULD be an array of values.",'error',true);
if (! is_array($this->objects[$this->index]->getValue($key,$setting)) && is_array($value))
error("Error in configuration file, {$key}['$this->index'] should NOT be an array of values.",'error',true);
# Store the value in the object.
$this->objects[$this->index]->setValue($key,$setting,$value);
}
/**
* Get a list of all the configured servers.
*
* @param boolean Only show visible servers.
* @return array list of all configured servers.
*/
public function getServerList($isVisible=true) {
static $CACHE;
if (! isset($CACHE[$isVisible])) {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with (%s)',3,__FILE__,__LINE__,__METHOD__,$isVisible);
$CACHE[$isVisible] = array();
# Debugging incase objects is not set.
if (! $this->objects) {
print "<PRE>";
debug_print_backtrace();
die();
}
foreach ($this->objects as $id => $server)
if (! $isVisible || ($isVisible && $server->getValue('server','visible')))
$CACHE[$isVisible][$id] = $server;
}
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with (%s), Returning (%s)',3,__FILE__,__LINE__,__METHOD__,
$isVisible,$CACHE);
return $CACHE[$isVisible];
}
/**
* Return an object Instance of a configured database.
*
* @param int Index
* @return object Datastore instance object.
*/
public function Instance($index=null) {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with (%s)',3,__FILE__,__LINE__,__METHOD__,$index);
# If no index defined, then pick the lowest one.
if (is_null($index))
$index = min($this->GetServerList())->getIndex();
if (! isset($this->objects[$index]))
debug_dump_backtrace("Error: Datastore instance [$index] doesnt exist?",1);
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Returning instance of database (%s)',3,__FILE__,__LINE__,__METHOD__,$index);
return $this->objects[$index];
}
/**
* Return an object Instance of a configured database.
*
* @param string Name of the instance to retrieve
* @return object Datastore instance object.
*/
public function InstanceName($name=null) {
if (DEBUG_ENABLED)
debug_log('Entered with (%s)',3,__FILE__,__LINE__,__METHOD__,$name);
foreach ($this->getServerList(false) as $index)
if ($this->objects[$index]->getName() == $name)
return $this->objects[$index];
# If we get here, then no object with the name exists.
return null;
}
/**
* Return an object Instance of a configured database.
*
* @param string ID of the instance to retrieve
* @return object Datastore instance object.
*/
public function InstanceId($id=null) {
if (DEBUG_ENABLED)
debug_log('Entered with (%s)',3,__FILE__,__LINE__,__METHOD__,$id);
foreach ($this->getServerList(false) as $index)
if ($this->objects[$index->getIndex()]->getValue('server','id') == $id)
return $this->objects[$index->getIndex()];
# If we get here, then no object with the name exists.
return null;
}
}
?>

712
lib/ds_tsm.php Normal file
View File

@@ -0,0 +1,712 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/ds_tsm.php,v 1.8 2009/04/19 04:03:05 wurley Exp $
/**
* @package phpTSMadmin
* @author Deon George (c) 2006
*/
class tsm extends DS {
public function __construct($index) {
$this->index = $index;
$this->type = 'tsm';
# Additional values that can go in our config.php
$this->custom = new StdClass;
$this->default = new StdClass;
# TSM Server Stanza Name
$this->default->server['stanza'] = array(
'desc'=>'TSM Server Stanza Name',
'default'=>null);
$this->default->system['dsmadmc'] = array(
'desc'=>'Path to dsmadmc command.',
'default'=>'/opt/tivoli/tsm/client/ba/bin/dsmadmc');
$this->default->system['errorlog'] = array(
'desc'=>'Set errorlog filename',
'default'=>'/tmp/pta-tsm-errorlog.log');
$this->default->system['tapeage'] = array(
'desc'=>'Age of tapes to alert for rotation',
'default'=>180);
# TSM Parameters
$this->default->tsmparm['msgFormat'] = array(
'desc'=>'Format of TSM message codes.',
'default'=>'[A-Z]{3}[0-9]{4}[I|E|W|S]');
$this->default->tsmparm['queryStartMsg'] = array(
'desc'=>'TSM code depicting START of queries results.',
'default'=>'ANS8000I');
$this->default->tsmparm['queryEndMsg'] = array(
'desc'=>'TSM code depicting END of queries results.',
'default'=>'ANS8002I');
$this->default->tsmparm['loginFail'] = array(
'desc'=>'Known TSM "failed login" message codes.',
'default'=>array(
'ANS8023E', //
'ANS1017E', // TCP/IP connection rejected.
'ANS1217E', // Server name not found in System Options File
'ANS1355E', // Sessions disabled.
'ANS8034E' // Your administrator ID is not recognized by this server.
));
$this->default->tsmparm['loginFailIgnore'] = array(
'desc'=>'Known TSM "ignore" message codes during login.',
'default'=>array(
'ANS0110E', // LogMsg: Unable to open error log file '%s' for output.
'ANS8002I' // Highest return code was %s.
));
$this->default->tsmparm['ignoremsg'] = array(
'desc'=>'Known TSM "ignore" message codes.',
'default'=>array(
'ANS8001I', // Return code %s.
'ANS0102W' // Unable to open the message repository %s. The American English repository will be used instead.
));
$this->default->tsmparm['nodatamsg'] = array(
'desc'=>'Known TSM "select returned no data" message codes.',
'default'=>array(
'ANR2034E' // SELECT: No match found using this criteria.
));
}
/**
* Required ABSTRACT functions
*/
/**
* Connect and Bind to the Database
*
* @param method This enables to have multiple different types of connects, ie: read only, readwrite, etc
* @return resource|null Connection resource if successful, null if not.
*/
protected function connect($method,$debug=false) {
$method = $this->getMethod($method);
if (! $this->isLoggedIn($method))
system_message(array('title'=>'Not Logged In',
'body'=>sprintf('You are not logged into server %s',$this->getValue('server','name')),
'type'=>'warn'),'index.php');
if (! file_exists($this->getValue('system','dsmadmc'))) {
system_message(array('title'=>'Cant find DSMADMC',
'body'=>sprintf('Unable to find the dsmadmc at <b>%s</b>',$this->getValue('system','dsmadmc')),
'type'=>'error'));
return false;
}
if ($this->getValue('system','errorlog'))
$errorlog = sprintf('-errorlogname=%s',$this->getValue('system','errorlog'));
if (is_null($this->getValue('server','stanza')) || ! trim($this->getValue('server','stanza')))
$TSMcmd = sprintf('%s -id=%s -password=%s -displ=list %s',
$this->getValue('system','dsmadmc'),$this->getLogin($method),$this->getPassword($method),
isset($errorlog) ? $errorlog : '');
else
$TSMcmd = sprintf('%s -se=%s -id=%s -password=%s -displ=list %s',
$this->getValue('system','dsmadmc'),
$this->getValue('server','stanza'),$this->getLogin($method),$this->getPassword($method),
isset($errorlog) ? $errorlog : '');
return $TSMcmd;
}
/**
* Login to the database with the application user/password
*
* @param method This enables to have multiple different types of connects, ie: read only, readwrite, etc
* @return boolean true|false for successful login.
*/
public function login($user=null,$pass=null,$method=null) {
# Set our user and password.
$this->setLogin($user,$pass,$method);
# Test that it works.
$result = $this->query('SELECT platform,version,release,level,sublevel FROM status',$method);
if (! $result)
$this->logout($method);
else
return true;
return false;
}
/**
* Perform a query to the Database
*
* @param string SQL query to perform
* @param string Index items according to this key
* @return array|null Results of query.
*/
public function query($query,$method,$index=null,$debug=false) {
$TSMcmd = sprintf('%s "%s"',$this->connect($method,$debug),$query);
$TSMcmdOutput = exec($TSMcmd,$OutputLines,$return);
if ($debug)
debug_dump(array('cmd'=>$TSMcmd,'TSMcmdOutput'=>$TSMcmdOutput,'return'=>$return));
# Parse the ouput for key:value pairs.
$outindex = 0;
$isQueryResult = 0;
$isKeyValue = 0;
$haveHelp = false;
$QueryResult = false;
$tsmCommands = array();
foreach ($OutputLines as $OutputLine ) {
$OutputLine = preg_replace('/\s+$/','',$OutputLine);
if ($debug)
debug_dump("($isQueryResult/$isKeyValue): WORKING line [$OutputLine]");
# See if we got a message number.
if (preg_match("/^(".$this->getValue('tsmparm','msgFormat').")\s+/",$OutputLine,$matches)) {
$msgnum = $matches[1];
if ($debug)
debug_dump("($isQueryResult/$isKeyValue): Got SYSTEM Msg [$OutputLine]");
# Filter through the output and check if we got our start message.
if (preg_match("/^".$this->getValue('tsmparm','queryStartMsg')."\s+/",$OutputLine)) {
if ($debug)
debug_dump("($isQueryResult/$isKeyValue): Got START Msg [$OutputLine]");
$isQueryResult = 1;
continue;
# Break out of loop when we get our end message.
} elseif (preg_match("/^".$this->getValue('tsmparm','queryEndMsg')."\s+/",$OutputLine)) {
if ($debug)
debug_dump("($isQueryResult/$isKeyValue): Got END Msg [$OutputLine]");
break;
}
if (in_array($msgnum,$this->getValue('tsmparm','nodatamsg')))
continue;
if (! in_array($msgnum,$this->getValue('tsmparm','ignoremsg')))
system_message(array('title'=>'TSM Message','body'=>$OutputLine));
}
# If we the line is a queryResult line
if ($isQueryResult) {
# See if we got a key:value pair, otherwise go to next line.
if (preg_match('/:/',$OutputLine) && ! (preg_match('/^help/',$query))) {
$OutputLine = preg_replace('/\s*:\s+/',':',$OutputLine);
list($key,$value) = explode(':',$OutputLine,2);
$isKeyValue = 1;
# Not key:value, so check if we need to increase the index.
} else {
# Is this a show slots command, so there is more info
if (preg_match('/^show slots/',$query)) {
if (preg_match('/^Slot /',$OutputLine)) {
foreach ((preg_split('/,\s*/',$OutputLine,-1)) as $slotkey => $val) {
if (preg_match('/^element number\s+/',$val)) {
$key = preg_replace('/^element number\s+/','',$val);
} elseif (preg_match('/^Slot\s+/',$val)) {
$slots['slot'] = preg_replace('/^Slot\s+/','',$val);
} elseif (preg_match('/^status\s+/',$val)) {
$slots['status'] = preg_replace('/^status\s+/','',$val);
} elseif (preg_match('/^barcode value </',$val)) {
$slots['barcodelabel'] = preg_replace('/^barcode value <(.*)>/',"$1",$val);
} elseif (preg_match('/^barcode\s+/',$val)) {
$slots['barcode'] = preg_replace('/^barcode /','',$val);
}
}
$QueryResult[$outindex]['SlotUsage'][$key] = $slots;
} elseif (preg_match('/busy.$/',$OutputLine)) {
system_message(array('title'=>'Library is Busy',
'body'=>sprintf('The library appears busy at the moment.<br />%s',$OutputLine),
'type'=>'info'),
sprintf('index.php',get_request('cmd','REQUEST') ? sprintf('cmd=%s',get_request('cmd','REQUEST')) : ''));
}
# Is this a help command, so there is more info
} elseif (preg_match('/^help$/',$query)) {
if (preg_match('/^\s*([0-9]+) - Commands /',$OutputLine)) {
$helpnum = preg_replace('/^\s*([0-9]+) - Commands .*/','$1',$OutputLine);
$tsmCommands = array_unique(array_merge($tsmCommands,$this->query("help $helpnum",null)));
}
} elseif (preg_match('/^help\s+[0-9]+/',$query)) {
if (! $OutputLine)
continue;
if (! $haveHelp && preg_match('/^\s*Command Name/',$OutputLine)) {
$haveHelp = true;
$helpCommands = array();
continue;
}
if ($haveHelp) {
# Filter out the beginning spaces.
$OutputLine = preg_replace('/^\s*/','',$OutputLine);
# Filter out the "(See Note)" messages.
$OutputLine = preg_replace('/\s\(.*\)/','',$OutputLine);
# Join the two columns together
$OutputLine = preg_replace('/\ \s+/','|',$OutputLine);
# We should now just have commands and they should be in uppercase.
if (preg_match('/[a-z0-9]/',$OutputLine))
continue;
#debug_dump("Im finally here with [$OutputLine].");
foreach (explode('|',$OutputLine) as $helpCMD)
array_push($helpCommands,$helpCMD);
}
} elseif (preg_match('/^help\s+[A-Z]+/',$query)) {
# Sometimes QueryResult gets data because of colons - we need to capture that.
if (isset($QueryResult) && is_array($QueryResult)) {
foreach ($QueryResult as $lineDetail)
foreach ($lineDetail as $key => $ldindex)
$helpText[] = $key.$ldindex;
$QueryResult = array();
}
$helpText[] = $OutputLine;
//debug_dump(array("Im finally here with [$OutputLine]."=>$QueryResult));
# If this is a blank line
} elseif (!$OutputLine) {
# Only increment index if the previous iteration was a key/value pair.
# Reset isKeyValue so we dont increase index for 2 non key:value lines in a row.
if ($isKeyValue) {
if (!preg_match('/^show/',$query))
$outindex++;
$isKeyValue = 0;
}
} // if
continue;
} // if
$key = preg_replace('/^\s+/','',$key);
$value = preg_replace('/^\s+/','',$value);
$QueryResult[$outindex][$key] = $value;
} // if
} // foreach
if (is_array($tsmCommands) && preg_match('/^help$/',$query)) {
asort($tsmCommands);
$QueryResult = $tsmCommands;
}
if (isset($helpCommands) && preg_match('/^help\s+[0-9]+/',$query))
$QueryResult = $helpCommands;
if (isset($helpText) && preg_match('/^help\s+[A-Z]+/',$query))
$QueryResult = $helpText;
if ($debug)
debug_dump($QueryResult,0);
if (! $isQueryResult && $debug)
Error(sprintf('The query <BR>%s<BR>didnt return anything [%s]',preg_replace('/-password=(.*)\ -/','-password=x -',$TSMcmd),serialize($OutputLines)));
if ($index && is_array($QueryResult)) {
foreach ($QueryResult as $result => $val) {
if (isset($val[$index]))
$IndexQueryResult[$val[$index]] = $QueryResult[$result];
}
return (isset($IndexQueryResult) ? $IndexQueryResult : false);
} elseif (is_array($QueryResult)) {
return $QueryResult;
}
return array();
}
/**
* Get the last error string
*/
protected function getErrorMessage() {
return null;
}
/**
* Get the last error number
*/
protected function getErrorNum() {
return null;
}
/**
* Return if anonymous bind is allowed in the configuration
*/
public function isAnonBindAllowed() {
return false;
}
/**
* Query the database for particular attributes values.
*/
public function queryAttr($table,$attrs,$key,$where=null,$orderby=null) {
return array();
}
/**
* Register user to the application
*/
public function register($user,$pass,$other=array()) {
return null;
}
/**
* Query TSM and get Database information
*/
function QueryDBDetail() {
$query = $this->query('select * from DB',null);
$this->CACHE['db'] = $query[0];
$this->CACHE['db']['dbvols'] = $this->query('select * from DBVOLUMES',null);
$this->CACHE['cache']['db'] = time();
$this->CACHE['cache']['log'] = time();
$query = $this->query('select * from LOG',null);
$this->CACHE['log'] = $query[0];
$this->CACHE['log']['logvols'] = $this->query('select * from LOGVOLUMES',null);
$_SESSION['tsm'][$this->index] = $this->CACHE;
}
/**
* Return the DB information.
* @param string attribute
* @return string value for attribute
*/
function GetDBDetail($attribute) {
if (! isset($this->CACHE['db'][$attribute]))
$this->QueryDBDetail();
if (! isset($this->CACHE['db'][$attribute]))
Error(sprintf(_('ERROR: A request to get DB attribute "%" didnt return a value'),$attribute));
return $this->CACHE['db'][$attribute];
}
/**
* Return the LOG information.
* @param string attribute
* @return string value for attribute
*/
function GetLogDetail($attribute) {
if (! isset($this->CACHE['log'][$attribute]))
$this->QueryDBDetail();
if (! isset($this->CACHE['log'][$attribute]))
Error(sprintf(_('ERROR: A request to get LOG attribute "%" didnt return a value'),$attribute));
return $this->CACHE['log'][$attribute];
}
/**
* Return the VOLUMES information
* @return array
*/
function GetVolumes() {
if (isset($this->CACHE['volumes']))
return $this->CACHE['volumes'];
$this->CACHE['volumes'] = $this->query('select * from VOLUMES',null,'VOLUME_NAME');
$this->CACHE['cache']['volumes'] = time();
$_SESSION['tsm'][$this->index] = $this->CACHE;
return $this->CACHE['volumes'];
}
/**
* Return the LIBVOLUMES information
* @return array
*/
function GetLibVolumes() {
if (isset($this->CACHE['libvols']))
return $this->CACHE['libvols'];
$this->CACHE['libvols'] = $this->query('select * from LIBVOLUMES',null,'HOME_ELEMENT');
$this->CACHE['cache']['libvols'] = time();
$_SESSION['tsm'][$this->index] = $this->CACHE;
return $this->CACHE['libvols'];
}
/**
* Return the DB Backup Volumes
* @return array
*/
function GetDBBackupInfo() {
if (isset($this->CACHE['dbbackup']))
return $this->CACHE['dbbackup'];
$this->CACHE['dbbackup']['vols'] = $this->query("select * from VOLHISTORY where TYPE in ('BACKUPFULL','BACKUPINCR','DBSNAPSHOT') order by BACKUP_SERIES,BACKUP_OPERATION,VOLUME_SEQ",
null,'VOLUME_NAME');
# Now check that a backup series is valid - since it should be in order.
$lastSeries = -1;
$backupfirst = '';
$backuplast = '';
$backupcount = 0;
if (is_array($this->CACHE['dbbackup']['vols'])) {
foreach ($this->CACHE['dbbackup']['vols'] as $volume => $voldetails) {
if ($lastSeries != $voldetails['BACKUP_SERIES']) {
$lastSeries = $voldetails['BACKUP_SERIES'];
$lastOperation = -1;
$lastSeq = 0;
if (! $backupfirst | $voldetails['DATE_TIME'] < $backupfirst)
$backupfirst = $voldetails['DATE_TIME'];
if (! $backuplast | $voldetails['DATE_TIME'] > $backuplast)
$backuplast = $voldetails['DATE_TIME'];
$backupcount++;
}
# No point trying this series if it is invalid.
if (isset($status[$voldetails['BACKUP_SERIES']]['status']) &&
($status[$voldetails['BACKUP_SERIES']]['status'] == 'InValid'))
continue;
$this->CACHE['dbbackup']['vols'][$volume]['STATUS'] = 'Valid';
if (($voldetails['BACKUP_OPERATION'] == $lastOperation) || ($voldetails['BACKUP_OPERATION']-1 == $lastOperation)) {
$status[$voldetails['BACKUP_SERIES']]['status'] = 'Valid';
$lastOperation = $voldetails['BACKUP_OPERATION'];
} else {
$status[$voldetails['BACKUP_SERIES']]['status'] = 'InValid';
$status[$voldetails['BACKUP_SERIES']]['statusreason'] = sprintf(_('Missing SERIES volumes, expected [%s], found [%s].'),
$lastOperation+1,$voldetails['BACKUP_OPERATION']);
continue;
}
if (($voldetails['VOLUME_SEQ'] == $lastSeq) || $voldetails['VOLUME_SEQ']-1 == $lastSeq) {
$status[$voldetails['BACKUP_SERIES']]['status'] = 'Valid';
$lastSeq = $voldetails['VOLUME_SEQ'];
} else {
$status[$voldetails['BACKUP_SERIES']]['status'] = 'InValid';
$status[$voldetails['BACKUP_SERIES']]['statusreason'] = sprintf(_('Missing SERIES volumes, expected [%s], found [%s].'),$lastSeq+1,$voldetails['VOLUME_SEQ']);
}
$lastSeq = $voldetails['VOLUME_SEQ'];
}
# Now we know which series are invalid, mark all the volumes.
foreach ($this->CACHE['dbbackup']['vols'] as $volume => $voldetails) {
$this->CACHE['dbbackup']['vols'][$volume]['STATUS'] = $status[$voldetails['BACKUP_SERIES']]['status'];
if (isset($status[$voldetails['BACKUP_SERIES']]['statusreason']))
$this->CACHE['dbbackup']['vols'][$volume]['STATUSREASON'] = $status[$voldetails['BACKUP_SERIES']]['statusreason'];
}
}
# Grab backup information
$history = $this->query('select DATE_TIME,MSGNO,MESSAGE from ACTLOG where MSGNO in (4550,4551) order by DATE_TIME',null);
if (! isset($history[0]['ANR2034E SELECT']))
foreach ($history as $index => $historydetail) {
$this->CACHE['dbbackup']['history'][$index]['date'] = $historydetail['DATE_TIME'];
switch ($historydetail['MSGNO']) {
case 4550:
if (preg_match('/([0-9]+) pages copied./',$historydetail['MESSAGE'],$matchall)) {
$this->CACHE['dbbackup']['history'][$index]['size'] = $matchall[1];
$this->CACHE['dbbackup']['history'][$index]['type'] = 'FULL';
}
break;
case 4551:
if (preg_match('/([0-9]+) pages copied./',$historydetail['MESSAGE'],$matchall)) {
$this->CACHE['dbbackup']['history'][$index]['size'] = $matchall[1];
$this->CACHE['dbbackup']['history'][$index]['type'] = 'INCR';
}
break;
default:
printf('Message %s not catered for [%s]...',$historydetail['MSGNO'],$historydetail['MESSAGE']);
die();
}
}
# Get DBBackup Trigger information.
$select = $this->query('select * from DBBACKUPTRIGGER',null);
$result = array_shift($select);
if (isset($result['ANR2034E SELECT']))
$this->CACHE['dbbackup']['trigger'] = false;
else
$this->CACHE['dbbackup']['trigger'] = $result;
$this->CACHE['dbbackup']['first'] = $backupfirst;
$this->CACHE['dbbackup']['last'] = $backuplast;
$this->CACHE['dbbackup']['count'] = $backupcount;
$this->CACHE['cache']['dbbackup'] = time();
$_SESSION['tsm'][$this->index] = $this->CACHE;
return $this->CACHE['dbbackup'];
}
function GetDBBackupDetail($detail) {
if (isset($this->CACHE['dbbackup'][$detail]))
return $this->CACHE['dbbackup'][$detail];
$this->GetDBBackupInfo();
if (isset($this->CACHE['dbbackup'][$detail]))
return $this->CACHE['dbbackup'][$detail];
else
return null;
}
/**
* Return the Status Information
* @return array
*/
function GetStatus() {
if (isset($this->CACHE['status']))
return $this->CACHE['status'];
$select = $this->query('select * from STATUS',null);
$this->CACHE['status'] = array_shift($select);
$this->CACHE['cache']['status'] = time();
$_SESSION['tsm'][$this->index] = $this->CACHE;
return $this->CACHE['status'];
}
function GetStatusDetail($detail) {
if (isset($this->CACHE['status'][$detail]))
return $this->CACHE['status'][$detail];
$this->GetStatus();
if (isset($this->CACHE['status'][$detail]))
return $this->CACHE['status'][$detail];
else
return null;
}
/**
* Get TSM event information
* @param string Start date for report
* @param string End date for report
* @param string order by key.
* @return array Query result
*/
function GetEvents($reportStart='',$reportEnd='',$orderby='SCHEDULED_START') {
if (isset($this->CACHE['events']) && $reportStart == $this->CACHE['events']['start'] &&
$reportEnd == $this->CACHE['events']['end'] && $orderby == $this->CACHE['events']['orderby'])
return $this->CACHE['events'];
$TSMQuery = 'select * from EVENTS where DOMAIN_NAME is not null';
if (($reportStart) && ($reportEnd))
$TSMQuery .= sprintf(" and (SCHEDULED_START between '%s' and '%s')",$reportStart,$reportEnd);
else if ($reportStart)
$TSMQuery .= sprintf(" and SCHEDULED_START \> '%s'",$reportStart);
else if ($reportEnd)
$TSMQuery .= sprintf(" and SCHEDULED_START <= '%s'",$reportEnd);
$TSMQuery .= sprintf(' order by %s',$orderby);
$result = $this->query($TSMQuery,null);
if (isset($result[0]['ANR2034E SELECT'])) {
$this->CACHE['events'] = false;
} else {
$this->CACHE['events']['detail'] = $result;
$this->CACHE['events']['start'] = $reportStart;
$this->CACHE['events']['end'] = $reportEnd;
$this->CACHE['events']['orderby'] = $orderby;
}
$this->CACHE['cache']['events'] = time();
$_SESSION['tsm'][$this->index] = $this->CACHE;
return $this->CACHE['events'];
}
/**
* Get TSM Activity Log Client backup information.
* @param string Start date for report
* @param string End date for report
* @return array Query result
*/
function GetActlogBackupSummary($reportStart='',$reportEnd='') {
if (isset($this->CACHE['actlogbackup']) && $reportStart == $this->CACHE['actlogbackup']['start'] &&
$reportEnd == $this->CACHE['actlogbackup']['end'])
return $this->CACHE['actlogbackup'];
$tsmMSG['4952'] = 'Inspected';
$tsmMSG['4954'] = 'Backup';
$tsmMSG['4958'] = 'Update';
$tsmMSG['4957'] = 'Delete';
$tsmMSG['4959'] = 'Failed';
$tsmMSG['4960'] = 'Rebound';
$tsmMSG['4961'] = 'Transfer';
$tsmMSG['4964'] = 'ProcTime';
$tsmMSG['4967'] = 'AggRate';
$tsmMSG['4968'] = 'Compress';
$tsmMSG['4970'] = 'Expire';
$TSMQuery = sprintf('select MSGNO,NODENAME,SESSID,MESSAGE,SCHEDNAME,DOMAINNAME from ACTLOG where MSGNO in (%s)',
implode(',',array_keys($tsmMSG)));
if (($reportStart) && ($reportEnd))
$TSMQuery .= sprintf(" and (DATE_TIME between '%s' and '%s')",$reportStart,$reportEnd);
else if ($reportStart)
$TSMQuery .= sprintf(" and DATE_TIME \> '%s'",$reportStart);
else if ($reportEnd)
$TSMQuery .= sprintf(" and DATE_TIME <= '%s'",$reportEnd);
$TSMQuery .= ' order by sessid';
foreach ($this->query($TSMQuery,null) as $tsmBackup => $tsmSession) {
# TSM on AIX adds a "SESSION" at the end of each line - maybe others do as well.
if (isset($tsmSession['MESSAGE']))
$tsmSession['MESSAGE'] = preg_replace('/\(SESSION:.*\)/','',$tsmSession['MESSAGE']);
$tsmBackupSummary['detail'][$tsmSession['NODENAME']][$tsmSession['SESSID']][$tsmMSG[$tsmSession['MSGNO']]] = preg_replace('/^.*:\s*/U','',$tsmSession['MESSAGE']);
}
$tsmBackupSummary['start'] = $reportStart;
$tsmBackupSummary['end'] = $reportEnd;
$this->CACHE['actlogbackup'] = $tsmBackupSummary;
$this->CACHE['cache']['actlogbackup'] = time();
$_SESSION['tsm'][$this->index] = $this->CACHE;
return $this->CACHE['actlogbackup'];
}
function GetVolLocation($vol) {
$volumes = $this->GetVolumes();
if ($this->GetLibVolumes())
foreach ($this->GetLibVolumes() as $slot => $details) {
if ($details['VOLUME_NAME'] == $vol)
return sprintf('**%s %s**',_('LIBRARY'),$details['LIBRARY_NAME']);
}
if (isset($volumes[$vol]))
return $volumes[$vol]['LOCATION'];
# If we get here, we dont know where the volume is.
return null;
}
}
?>

330
lib/functions.custom.php Normal file
View File

@@ -0,0 +1,330 @@
<?php
# $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/functions.custom.php,v 1.2 2009/04/19 04:03:05 wurley Exp $
/**
* Classes and functions for TSM server configuration and capability
*
* @author The phpTSMadmin development team
* @package phpTSMadmin
*/
/**
* Prune the .decimals from the TSM dates.
* @param string Date
* @param string Prune key
* @return string Date in required format
*/
function tsmDate($string,$prune='') {
switch ($prune) {
case 'notime' :
$regexp = '/ [0-9]+:.*$/';
break;
case 'nosec' :
$regexp = '/:[0-9]+\.[0-9]*$/';
break;
case 'nomsec' :
$regexp = '/^([0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+)\..*/';
break;
case 'daytime' :
$regexp = '/^[0-9]+-[0-9]+-([0-9]+ [0-9]+:[0-9]+).*/';
break;
case 'monthdaytime' :
$regexp = '/^[0-9]+-([0-9]+-[0-9]+ [0-9]+:[0-9]+).*/';
break;
default :
$regexp = '/\.[0-9]*$/';
}
return (preg_replace($regexp,'$1',$string));
}
/**
* Translate backup types into meaningful strings.
* @param string TSM backup string
* @return string
*/
function tsmBackupType($string) {
switch ($string) {
case 'BACKUPINCR' : return 'INCR';
break;
case 'BACKUPFULL' : return 'FULL';
break;
case 'DBSNAPSHOT' : return 'SNAPSHOT';
break;
default : return $string;
break;
}
}
function isPrimaryPool($pool) {
global $app;
objectCache('stgps');
return $_SESSION['cache'][$app['server']->getIndex()]['stgps']->isPrimaryPool($pool);
}
function isCopyPool($pool) {
global $app;
objectCache('stgps');
return $_SESSION['cache'][$app['server']->getIndex()]['stgps']->isCopyPool($pool);
}
function getReclaim($pool) {
global $app;
objectCache('stgps');
return $_SESSION['cache'][$app['server']->getIndex()]['stgps']->getReclaim($pool);
}
function getReUse($pool) {
global $app;
objectCache('stgps');
return $_SESSION['cache'][$app['server']->getIndex()]['stgps']->getReUse($pool);
}
function getVolume($vol) {
global $app;
objectCache('volumes');
return $_SESSION['cache'][$app['server']->getIndex()]['volumes']->getVolume($vol);
}
function isLibraryDevClass($devclass) {
global $app;
objectCache('devclasses');
return $_SESSION['cache'][$app['server']->getIndex()]['devclasses']->isLibraryDevClass($devclass);
}
function LibraryDevClass($devclass) {
global $app;
objectCache('devclasses');
return $_SESSION['cache'][$app['server']->getIndex()]['devclasses']->LibraryDevClass($devclass);
}
/**
* Return the name that a cookie will be stored by the browser.
* @param int Server ID.
* @param string Name of Cookie.
* @return string Fully qualified cookie name.
*/
function cookie_name($index,$name) {
global $app;
return $app['server']->getValue('cookie','prefix').$index.$name;
}
/**
* Returns the value of cookie
* @param int Server ID
* @param string Name
* @return string|false Value of cookie (null if not set/no value)
*/
function get_cookie($index,$name) {
global $_COOKIE;
$cookie = cookie_name($index,$name);
if (isset($_COOKIE[$cookie]))
return $_COOKIE[$cookie];
else
return false;
}
/**
* Store a cookie in the user browser.
* @param int Server ID
* @param string Name of Cookie
* @param string Value for Cookie
* @param int Time for cookie to live in seconds
* @param string dir Cookie Path
* @result boolean
*/
function store_cookie($index,$name,$val,$expire=null,$dir=null) {
global $app;
$cookie_name = cookie_name($index,$name);
$cookie_time = $app['server']->getValue('cookie','time');
if ($expire == null)
$expire = ($cookie_time == 0 ? null : time() + $cookie_time);
if ($dir == null)
$dir = dirname($app['server']->getValue('server','path') ? $app['server']->getValue('server','path') : '/');
if (setcookie($cookie_name,$val,$expire,$dir))
return true;
else
return false;
}
/**
* Unset all cookies on logout.
* @param int Server ID
* @result boolean True if successful, false if not
* @todo: No routine to call this.
*/
function unset_cookie($index) {
global $app;
global $_COOKIE;
$expire = time()-3600;
foreach ($_COOKIE as $cookie => $cookie_value) {
$cookie = preg_replace("/^".$app['server']->getValue('server','path').$index.'/','',$cookie);
if ($cookie == 'PHPSESSID') continue;
$result = store_cookie($index,$cookie,'',$expire) ;
if (! $result) return false;
}
return true;
}
/**
* Initialise JPgraph
* @param boolean Must initialise or fail with an error if unable to do so
*/
function initJPGraph($need=false) {
$jpgraph = $_SESSION[APPCONFIG]->getValue('lib','jpgraph');
if (! $jpgraph)
if ($need)
die(_('Your JPGRAPH setting in config.php is pointing to a directory that does not exist. Please fix your config.php'));
else
return false;
if ((! file_exists($jpgraph.'/src/jpgraph.php')) || (! file_exists($jpgraph.'/src/jpgraph_gantt.php')))
if ($need)
die(sprintf(_('PTA was not able to find the JPGRAPH utility in the "%s" directory. Either your config.php is pointing to the wrong directory, or you havent installed JPGRAPH'),$jpgraph));
else
return false;
if (! function_exists('imagetypes') && ! function_exists('imagecreatefromstring'))
if ($need)
die(_('It seems that GD support is not available. Please add GD support to PTA.'));
else
return false;
if (! is_dir($_SESSION[APPCONFIG]->getValue('image','path')) || ! is_writable($_SESSION[APPCONFIG]->getValue('image','path')))
die(sprintf(_('The temporary path for JPGRAPH either doesnt exist or is not writable - you have it configured for %s.'),$_SESSION[APPCONFIG]->getValue('image','path')));
# When we get here, we have all the pre-reqs.
error_reporting(0);
require_once $jpgraph.'/src/jpgraph.php';
require_once $jpgraph.'/src/jpgraph_gantt.php';
require_once $jpgraph.'/src/jpgraph_line.php';
require_once $jpgraph.'/src/jpgraph_bar.php';
require_once $jpgraph.'/src/jpgraph_pie.php';
require_once $jpgraph.'/src/jpgraph_date.php';
error_reporting(E_ALL);
return true;
}
/**
* Put some HTML classes around strings containing values.
* @param string String to parse
* @param string Class to substitute
* @return string String with <span class=$class> around %s
*/
function classValue($string,$class) {
return preg_replace('/(\%[0-9.]*[sf])/',"<span class=\"$class\">$1</span>$2",$string);
}
function objectCache($object,$force=false) {
global $app;
$index = $app['server']->getIndex();
if (DEBUG_ENABLED)
debug_log('objectCache(): Entered with (%s,%s)',1,$object,isset($_SESSION['cache'][$index][$object]));
if (isset($_SESSION['cache'][$index][$object])) {
if ($_SESSION['cache'][$index][$object]->expired() || $force) {
if (DEBUG_ENABLED)
debug_log('objectCache(): Object expired (%s,%s)',1,$_SESSION['cache'][$index][$object]->cache,time());
$_SESSION['cache'][$index][$object]->load();
$_SESSION['cache'][$index][$object]->cache = time();
}
} else {
switch($object) {
case 'devclasses' :
$_SESSION['cache'][$index][$object] = new deviceClasses($index);
break;
case 'drives' :
$_SESSION['cache'][$index][$object] = new drives($index);
break;
case 'help' :
$_SESSION['cache'][$index][$object] = new help($index);
break;
case 'libraries' :
$_SESSION['cache'][$index][$object] = new libraries($index);
break;
case 'mgmtclasses' :
$_SESSION['cache'][$index][$object] = new mgmtClasses($index);
break;
case 'nodes' :
$_SESSION['cache'][$index][$object] = new nodes($index);
break;
case 'occupancy' :
$_SESSION['cache'][$index][$object] = new occupancy($index);
break;
case 'stgps' :
$_SESSION['cache'][$index][$object] = new storagePools($index);
break;
case 'summaryinfo' :
$_SESSION['cache'][$index][$object] = new summaryInfo($index);
break;
case 'volumes' :
$_SESSION['cache'][$index][$object] = new volumes($index);
break;
default:
error(sprintf('Unknown object %s',$object));
}
$_SESSION['cache'][$index][$object]->cache = time();
}
return $_SESSION['cache'][$index][$object];
}
function render_page($title,$body) {
$www = new page();
if (is_array($title)) {
foreach ($title as $key => $title) {
$block = new block();
$block->SetTitle($title);
$block->SetBody($body[$key]);
$www->block_add('body',$block);
}
} else {
$block = new block();
$block->SetTitle($title);
$block->SetBody($body);
$www->block_add('body',$block);
}
$www->body();
}
?>

1018
lib/functions.php Normal file

File diff suppressed because it is too large Load Diff

330
lib/functions.tsm.php Normal file
View File

@@ -0,0 +1,330 @@
<?php
# $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/functions.tsm.php,v 1.39 2009/04/19 04:03:05 wurley Exp $
/**
* Classes and functions for TSM server configuration and capability
*
* @author The phpTSMadmin development team
* @package phpTSMadmin
*/
/**
* Prune the .decimals from the TSM dates.
* @param string Date
* @param string Prune key
* @return string Date in required format
*/
function tsmDate($string,$prune='') {
switch ($prune) {
case 'notime' :
$regexp = '/ [0-9]+:.*$/';
break;
case 'nosec' :
$regexp = '/:[0-9]+\.[0-9]*$/';
break;
case 'nomsec' :
$regexp = '/^([0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+)\..*/';
break;
case 'daytime' :
$regexp = '/^[0-9]+-[0-9]+-([0-9]+ [0-9]+:[0-9]+).*/';
break;
case 'monthdaytime' :
$regexp = '/^[0-9]+-([0-9]+-[0-9]+ [0-9]+:[0-9]+).*/';
break;
default :
$regexp = '/\.[0-9]*$/';
}
return (preg_replace($regexp,'$1',$string));
}
/**
* Translate backup types into meaningful strings.
* @param string TSM backup string
* @return string
*/
function tsmBackupType($string) {
switch ($string) {
case 'BACKUPINCR' : return 'INCR';
break;
case 'BACKUPFULL' : return 'FULL';
break;
case 'DBSNAPSHOT' : return 'SNAPSHOT';
break;
default : return $string;
break;
}
}
function isPrimaryPool($pool) {
global $app;
objectCache('stgps');
return $_SESSION['cache'][$app['server']->getIndex()]['stgps']->isPrimaryPool($pool);
}
function isCopyPool($pool) {
global $app;
objectCache('stgps');
return $_SESSION['cache'][$app['server']->getIndex()]['stgps']->isCopyPool($pool);
}
function getReclaim($pool) {
global $app;
objectCache('stgps');
return $_SESSION['cache'][$app['server']->getIndex()]['stgps']->getReclaim($pool);
}
function getReUse($pool) {
global $app;
objectCache('stgps');
return $_SESSION['cache'][$app['server']->getIndex()]['stgps']->getReUse($pool);
}
function getVolume($vol) {
global $app;
objectCache('volumes');
return $_SESSION['cache'][$app['server']->getIndex()]['volumes']->getVolume($vol);
}
function isLibraryDevClass($devclass) {
global $app;
objectCache('devclasses');
return $_SESSION['cache'][$app['server']->getIndex()]['devclasses']->isLibraryDevClass($devclass);
}
function LibraryDevClass($devclass) {
global $app;
objectCache('devclasses');
return $_SESSION['cache'][$app['server']->getIndex()]['devclasses']->LibraryDevClass($devclass);
}
/**
* Return the name that a cookie will be stored by the browser.
* @param int Server ID.
* @param string Name of Cookie.
* @return string Fully qualified cookie name.
*/
function cookie_name($index,$name) {
global $app;
return $app['server']->getValue('cookie','prefix').$index.$name;
}
/**
* Returns the value of cookie
* @param int Server ID
* @param string Name
* @return string|false Value of cookie (null if not set/no value)
*/
function get_cookie($index,$name) {
global $_COOKIE;
$cookie = cookie_name($index,$name);
if (isset($_COOKIE[$cookie]))
return $_COOKIE[$cookie];
else
return false;
}
/**
* Store a cookie in the user browser.
* @param int Server ID
* @param string Name of Cookie
* @param string Value for Cookie
* @param int Time for cookie to live in seconds
* @param string dir Cookie Path
* @result boolean
*/
function store_cookie($index,$name,$val,$expire=null,$dir=null) {
global $app;
$cookie_name = cookie_name($index,$name);
$cookie_time = $app['server']->getValue('cookie','time');
if ($expire == null)
$expire = ($cookie_time == 0 ? null : time() + $cookie_time);
if ($dir == null)
$dir = dirname($app['server']->getValue('server','path') ? $app['server']->getValue('server','path') : '/');
if (setcookie($cookie_name,$val,$expire,$dir))
return true;
else
return false;
}
/**
* Unset all cookies on logout.
* @param int Server ID
* @result boolean True if successful, false if not
* @todo: No routine to call this.
*/
function unset_cookie($index) {
global $app;
global $_COOKIE;
$expire = time()-3600;
foreach ($_COOKIE as $cookie => $cookie_value) {
$cookie = preg_replace("/^".$app['server']->getValue('server','path').$index.'/','',$cookie);
if ($cookie == 'PHPSESSID') continue;
$result = store_cookie($index,$cookie,'',$expire) ;
if (! $result) return false;
}
return true;
}
/**
* Initialise JPgraph
* @param boolean Must initialise or fail with an error if unable to do so
*/
function initJPGraph($need=false) {
$jpgraph = $_SESSION[APPCONFIG]->getValue('lib','jpgraph');
if (! $jpgraph)
if ($need)
die(_('Your JPGRAPH setting in config.php is pointing to a directory that does not exist. Please fix your config.php'));
else
return false;
if ((! file_exists($jpgraph.'/src/jpgraph.php')) || (! file_exists($jpgraph.'/src/jpgraph_gantt.php')))
if ($need)
die(sprintf(_('PTA was not able to find the JPGRAPH utility in the "%s" directory. Either your config.php is pointing to the wrong directory, or you havent installed JPGRAPH'),$jpgraph));
else
return false;
if (! function_exists('imagetypes') && ! function_exists('imagecreatefromstring'))
if ($need)
die(_('It seems that GD support is not available. Please add GD support to PTA.'));
else
return false;
if (! is_dir($_SESSION[APPCONFIG]->getValue('image','path')) || ! is_writable($_SESSION[APPCONFIG]->getValue('image','path')))
die(sprintf(_('The temporary path for JPGRAPH either doesnt exist or is not writable - you have it configured for %s.'),$_SESSION[APPCONFIG]->getValue('image','path')));
# When we get here, we have all the pre-reqs.
error_reporting(0);
require_once $jpgraph.'/src/jpgraph.php';
require_once $jpgraph.'/src/jpgraph_gantt.php';
require_once $jpgraph.'/src/jpgraph_line.php';
require_once $jpgraph.'/src/jpgraph_bar.php';
require_once $jpgraph.'/src/jpgraph_pie.php';
require_once $jpgraph.'/src/jpgraph_date.php';
error_reporting(E_ALL);
return true;
}
/**
* Put some HTML classes around strings containing values.
* @param string String to parse
* @param string Class to substitute
* @return string String with <span class=$class> around %s
*/
function classValue($string,$class) {
return preg_replace('/(\%[0-9.]*[sf])/',"<span class=\"$class\">$1</span>$2",$string);
}
function objectCache($object,$force=false) {
global $app;
$index = $app['server']->getIndex();
if (DEBUG_ENABLED)
debug_log('objectCache(): Entered with (%s,%s)',1,$object,isset($_SESSION['cache'][$index][$object]));
if (isset($_SESSION['cache'][$index][$object])) {
if ($_SESSION['cache'][$index][$object]->expired() || $force) {
if (DEBUG_ENABLED)
debug_log('objectCache(): Object expired (%s,%s)',1,$_SESSION['cache'][$index][$object]->cache,time());
$_SESSION['cache'][$index][$object]->load();
$_SESSION['cache'][$index][$object]->cache = time();
}
} else {
switch($object) {
case 'devclasses' :
$_SESSION['cache'][$index][$object] = new deviceClasses($index);
break;
case 'drives' :
$_SESSION['cache'][$index][$object] = new drives($index);
break;
case 'help' :
$_SESSION['cache'][$index][$object] = new help($index);
break;
case 'libraries' :
$_SESSION['cache'][$index][$object] = new libraries($index);
break;
case 'mgmtclasses' :
$_SESSION['cache'][$index][$object] = new mgmtClasses($index);
break;
case 'nodes' :
$_SESSION['cache'][$index][$object] = new nodes($index);
break;
case 'occupancy' :
$_SESSION['cache'][$index][$object] = new occupancy($index);
break;
case 'stgps' :
$_SESSION['cache'][$index][$object] = new storagePools($index);
break;
case 'summaryinfo' :
$_SESSION['cache'][$index][$object] = new summaryInfo($index);
break;
case 'volumes' :
$_SESSION['cache'][$index][$object] = new volumes($index);
break;
default:
error(sprintf('Unknown object %s',$object));
}
$_SESSION['cache'][$index][$object]->cache = time();
}
return $_SESSION['cache'][$index][$object];
}
function render_page($title,$body) {
$www = new page();
if (is_array($title)) {
foreach ($title as $key => $title) {
$block = new block();
$block->SetTitle($title);
$block->SetBody($body[$key]);
$www->block_add('body',$block);
}
} else {
$block = new block();
$block->SetTitle($title);
$block->SetBody($body);
$www->block_add('body',$block);
}
$www->body();
}
?>

49
lib/menu.php Normal file
View File

@@ -0,0 +1,49 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/menu.php,v 1.2 2009/04/19 04:03:05 wurley Exp $
/**
* @package leenooksApp
* @author Deon George
*
* Abstract class which represents the Menu view ; the draw() method
* must be implemented by subclasses
*
* @see Menu_HTML
*/
abstract class Menu {
# Datastore server represented by this tree
protected $index = null;
protected function __construct($index) {
$this->index = $index;
}
static public function getInstance($index) {
$menu = get_cached_item($index,'menu');
if (! $menu) {
$menu = $_SESSION[APPCONFIG]->getValue('appearance','menu');
eval('$menu = new '.$menu.'($index);');
set_cached_item($index,'menu','null',$menu);
}
return $menu;
}
/**
* Get the server Object for this tree
*
* @return object Server Object for this tree
*/
protected function getServer() {
return $_SESSION[APPCONFIG]->getServer($this->index);
}
public function getDatastore() {
return isset($_SESSION[APPCONFIG]->datastore->object[$this->index]) ? $_SESSION[APPCONFIG]->datastore->object[$this->index] : null;
}
/**
* Displays the Menu
*/
abstract public function draw();
}
?>

165
lib/menu_html.php Normal file
View File

@@ -0,0 +1,165 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/menu_html.php,v 1.4 2009/04/19 04:03:05 wurley Exp $
/**
* This class will render a HTML version of the Menu.
*
* @package leenooksApp
* @author Deon George
*/
class menu_html extends menu {
protected $javascript = '';
public function __construct($index) {
$this->index = $index;
$this->servers = $_SESSION[APPCONFIG]->servers->Instance($this->index);
}
/**
* Displays the menu in HTML
*/
public function draw() {
if (DEBUG_ENABLED)
debug_log('Entered with ()',33,__FILE__,__LINE__,__METHOD__);
echo '<table class="menu" border=0>';
$this->draw_server_name();
$this->javascript = '';
$javascript_id = 0;
# Is the user logged in, if so, show the menu.
if ($this->servers->isLoggedIn('user')) {
$this->draw_menu();
$this->draw_logged_in_user();
if ($this->servers->isReadOnly())
printf('<tr><td class="spacer"></td><td class="links" colspan="%s">(%s)</td></tr>',$this->getDepth()+3-1,_('read only'));
else
printf('<tr><td class="blank" colspan="%s">&nbsp;</td></tr>',$this->getDepth()+3);
# Draw the menu items.
foreach ($_SESSION[APPCONFIG]->getCommandList() as $command) {
printf('<tr class="option"><td class="expander"><img src="%s" /></td><td class="item"><a title="%s" href="cmd.php?cmd=%s&amp;index=%s">%s</a>',
'images/minus.png',$command['desc'],$command['default'],$this->servers->getIndex(),$command['summary']);
}
# User not logged in, show a login link.
} else {
$this->draw_login_link();
}
# Menu Footer.
# @todo: Need to implement a mechanism to have a footer, but not display it if it is blank.
#printf('<tr><td class="foot" colspan="%s">%s</td></tr>',$this->getDepth()+3,'&nbsp;');
echo '</table>';
echo "\n\n";
$this->draw_javascript();
}
protected function draw_server_name() {
echo '<tr class="server">';
printf('<td class="icon"><img src="images/server.png" alt="%s" /></td>',_('Server'));
printf('<td class="name" colspan="%s">',$this->getDepth()+3-1);
printf('%s',htmlspecialchars($this->servers->getValue('server','name')));
if ($this->servers->isLoggedIn('user')) {
$m = sprintf(_('Inactivity will log you off at %s'),
strftime('%H:%M',time() + ($this->servers->getValue('login','timeout')*60)));
printf(' <img width=14 height=14 src="images/timeout.png" title="%s" alt="%s"/>',$m,$m);
}
echo '</td></tr>';
}
protected function draw_menu() {
$links = '';
if (is_array($_SESSION[APPCONFIG]->getValue('menu','session')))
foreach ($_SESSION[APPCONFIG]->getValue('menu','session') as $link => $title) {
if ($link = $this->menu_item($link))
$links .= sprintf('<td class="ds_option">%s</td>',$link);
}
# Finally add our logout link.
$links .= sprintf('<td class="ds_option">%s</td>',$this->get_logout_menu_item());
# Draw the quick-links below the server name:
if ($links) {
printf('<tr class="links"><td class="spacer"></td><td colspan="%s">',$this->getDepth()+3-1);
printf('<table><tr>%s</tr></table>',$links);
echo '</td></tr>';
}
}
protected function menu_item($item) {
$menu = $_SESSION[APPCONFIG]->getValue('menu','session');
if (isset($menu[$item]))
return sprintf('<a title="%s" href="cmd.php?cmd=%s&amp;index=%s"><img src="%s%s" alt="%s" /><br />%s</a>',
$menu[$item]['text'],$menu[$item]['php'],$this->servers->getIndex(),IMGDIR,$menu[$item]['icon'],$item,$item);
else
return '&nbsp;';
}
protected function get_logout_menu_item() {
global $app;
$href = sprintf('cmd.php?cmd=logout&index=%s',$this->servers->getIndex());
return sprintf('<a title="%s" href="%s"><img src="%s" alt="%s" /><br />%s</a>',
_('Logout of this server'),htmlspecialchars($href),'images/logout.png',_('logout'),_('logout'));
}
protected function draw_logged_in_user() {
if (! is_null($_SESSION[APPCONFIG]->getValue('appearance','logged_in_chars'))
&& (strlen($this->servers->getLogin('user')) > $_SESSION[APPCONFIG]->getValue('appearance','logged_in_chars'))) {
printf('<tr><td class="spacer"></td><td class="logged_in" colspan="%s"><span style="white-space: nowrap;">%s%s <acronym title="%s"><b>%s</b>...</acronym></span></td></tr>',
$this->getDepth()+3-1,_('Logged in as'),_(':'),
$this->servers->getLogin('user'),
substr($this->servers->getLogin('user'),0,$_SESSION[APPCONFIG]->getValue('appearance','logged_in_chars')));
} else
printf('<tr><td class="spacer"></td><td class="logged_in" colspan="%s"><span style="white-space: nowrap;">%s%s <b>%s</b></span></td></tr>',
$this->getDepth()+3-1,_('Logged in as'),_(':'),$this->servers->getLogin('user'));
}
protected function draw_login_link() {
global $recently_timed_out_servers;
$server = $this->getServer();
$href = htmlspecialchars(
sprintf('cmd.php?cmd=%s&index=%s',get_custom_file($server->getIndex(),'login_form',''),$this->servers->getIndex()));
echo '<tr><td class="spacer"></td>';
printf('<td class="icon"><a href="%s"><img src="images/uid.png" alt="%s" /></a></td>',$href,_('login'));
printf('<td class="logged_in" colspan="%s"><a href="%s">%s</a></td>',$this->getDepth()+3-2,$href,_('Login').'...');
echo '</tr>';
printf('<tr><td class="blank" colspan="%s">&nbsp;</td>',$this->getDepth()+3);
printf('<tr><td class="blank" colspan="%s">&nbsp;</td>',$this->getDepth()+3);
# If the server recently timed out display the message
if (is_array($recently_timed_out_servers) && in_array($this->servers->getIndex(),$recently_timed_out_servers))
printf('<tr><td class="spacer"></td><td colspan="%s" class="links">%s</td></tr>',
$this->getDepth()+3-1,_('(Session timed out. Automatically logged out.)'));
}
protected function draw_javascript() {
if ($this->javascript) {
echo "<!-- Forms for javascript submit to call to create base_dns -->\n";
echo $this->javascript;
echo "<!-- The end of the forms for javascript submit to call to create base_dns -->\n";
}
}
/**
* Work out how long the deepest "opened" menu item is.
* This is used to dynamically build our cells for our menu table.
*/
protected function getDepth() {
return 1;
}
}
?>

504
lib/page.php Normal file
View File

@@ -0,0 +1,504 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/page.php,v 1.6 2009/04/19 04:03:05 wurley Exp $
/**
* Page Rendering Functions
*
* @author Deon George (c) 2009
* @package leenooksApp
*/
/**
* This class controls the final output to the browser.
*
* @package leenooksApp
* @subpackage Page
*/
class page {
# pre-HTML headers
protected $_pageheader;
# Items to get into the <head>
protected $_head;
# Settings for this application
protected $_app;
# Default values array.
protected $_default;
public function __construct($index=null) {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with [%s]',129,__FILE__,__LINE__,__METHOD__,$index);
# To be defined in a configuration file.
$this->_app['title'] = app_name();
# Default Values for configurable items.
$this->_default['stylecss'] = CSSDIR.'style.css';
$this->_default['logo'] = IMGDIR.'logo-small.png';
$this->_default['sysmsg']['error'] = IMGDIR.'error-big.png';
$this->_default['sysmsg']['warn'] = IMGDIR.'warn-big.png';
$this->_default['sysmsg']['info'] = IMGDIR.'info-big.png';
# Capture any output so far (in case we send some headers below) - there shouldnt be any output anyway.
$preOutput = '';
# Try and work around if php compression is on, or the user has set compression in the config.
# type = 1 for user gzip, 0 for php.ini gzip.
$obStatus = ob_get_status();
if (isset($obStatus['type']) && $obStatus['type'] && $obStatus['status']) {
$preOutput = ob_get_contents();
ob_end_clean();
}
header('Content-type: text/html; charset="UTF-8"');
if (isCompress()) {
header('Content-Encoding: gzip');
if (DEBUG_ENABLED)
debug_log('Sent COMPRESSED header to browser and discarded (%s)',129,__FILE__,__LINE__,__METHOD__,$preOutput);
}
if (isset($_SESSION[APPCONFIG])
&& $_SESSION[APPCONFIG]->getValue('appearance','compress')
&& ini_get('zlib.output_compression'))
$this->setsysmsg(array('title'=>_('Warning'),'body'=>_('WARNING: You cannot have PHP compression and application compression enabled at the same time. Please unset zlib.output_compression or set $config->custom->appearance[\'compress\']=false'),'type'=>'warn'));
# Turn back on output buffering.
ob_start();
# Initial Values
$this->_pageheader[] .= '<?xml version="1.0" encoding="utf-8"?>'."\n";
$this->_pageheader[] .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN"'."\n";
$this->_pageheader[] .= '"http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">'."\n";
$this->_pageheader[] .= "\n";
$this->_pageheader[] .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="auto" lang="auto" dir="ltr">'."\n";
$this->_pageheader[] .= "\n";
$this->_app['logo'] = $this->_default['logo'];
if (! is_null($index))
$this->_app['urlcss'] = sprintf('%s%s',CSSDIR,$_SESSION[APPCONFIG]->getValue('appearance','stylesheet'));
else
$this->_app['urlcss'] = sprintf('%s%s',CSSDIR,'style.css');
$this->index = $index;
}
/* Add to the HTML Header */
public function head_add($html) {
$this->_head[] .= $html;
}
/* Print out the HTML header */
private function pageheader_print() {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with ()',129,__FILE__,__LINE__,__METHOD__);
# HTML prepage requirements.
foreach ($this->_pageheader as $line)
echo $line."\n";
# Page Title
echo '<head>';
if (isset($_SESSION[APPCONFIG]))
printf('<title>%s (%s) - %s</title>',
$this->_app['title'],app_version(),$_SESSION[APPCONFIG]->getValue('appearance','page_title'));
else
printf('<title>%s - %s</title>',$this->_app['title'],app_version());
# Style sheet.
printf('<link type="text/css" rel="stylesheet" href="%s" />',$this->_app['urlcss']);
printf('<link rel="shortcut icon" href="%s/favicon.ico" type="image/vnd.microsoft.icon" />',IMGDIR);
if (defined('JSDIR')) {
echo "\n";
printf('<script type="text/javascript" src="%smenu_hide.js"></script>',JSDIR);
echo "\n";
}
# HTML head requirements.
if (is_array($this->_head) && count ($this->_head))
foreach ($this->_head as $line)
echo $line."\n";
echo '</head>';
echo "\n";
}
private function head_print() {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with ()',129,__FILE__,__LINE__,__METHOD__);
if (isset($_SESSION[APPCONFIG]))
$pagetitle = $_SESSION[APPCONFIG]->getValue('appearance','page_title') ? ' - '.$_SESSION[APPCONFIG]->getValue('appearance','page_title') : '';
else
$pagetitle = '';
echo '<tr class="pagehead">';
echo '<td colspan=3><div id="ajHEAD"><table border=0><tr>';
printf('<td align="left"><a href="%s" target="_blank"><img src="%s" alt="Logo" class="logo" /></a></td>','#',$this->_app['logo']);
echo '<td align="right" class="imagetop">';
$empty = true;
if (function_exists('cmd_control_pane'))
foreach (cmd_control_pane('top') as $cmd => $cmddetails) {
$cmds = preg_split('/:/',$cmd);
if (defined('APPCONFIG') && isset($_SESSION[APPCONFIG]) && method_exists($_SESSION[APPCONFIG],'isCommandAvailable'))
if ($_SESSION[APPCONFIG]->isCommandAvailable('all',$cmds)) {
if ((isset($cmddetails['enable']) && trim($cmddetails['enable'])) || ! isset($cmddetails['enable'])) {
if (! $empty)
echo ' ';
printf('<a %s>%s</a>',$cmddetails['link'],$cmddetails['image']);
$empty = false;
}
}
}
if ($empty)
echo '&nbsp;';
echo '</td>';
echo '</tr></table></div></td>';
echo '</tr>';
echo "\n";
}
private function control_print() {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with ()',129,__FILE__,__LINE__,__METHOD__);
echo '<table class="control" border=0>';
echo '<tr><td>';
$empty = true;
if (function_exists('cmd_control_pane'))
foreach (cmd_control_pane('main') as $cmd => $cmddetails) {
$cmds = preg_split('/:/',$cmd);
if (defined('APPCONFIG') && isset($_SESSION[APPCONFIG]) && method_exists($_SESSION[APPCONFIG],'isCommandAvailable'))
if ($_SESSION[APPCONFIG]->isCommandAvailable('all',$cmds)) {
if ((isset($cmddetails['enable']) && trim($cmddetails['enable'])) || ! isset($cmddetails['enable'])) {
if (! $empty)
echo ' | ';
printf('<a %s>%s</a>',$cmddetails['link'],
$_SESSION[APPCONFIG]->getValue('appearance','control_icons') ? $cmddetails['image'] : $cmddetails['title']);
$empty = false;
}
}
}
echo '</td>';
if ($empty)
echo '<td>&nbsp;</td>';
echo '</tr>';
echo '</table>';
}
protected function menu() {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with ()',129,__FILE__,__LINE__,__METHOD__);
if (! isset($_SESSION[APPCONFIG]))
return;
if (is_null($this->index))
$this->index = min(array_keys($_SESSION[APPCONFIG]->getServerList()));
if (count($_SESSION[APPCONFIG]->getServerList()) > 1) {
echo '<form name="server_select" action="cmd.php" method="post">';
echo '<table class="server_select"><tr><td>';
printf('%s%s<br />%s',_('Server Select'),_(':'),
server_select_list($this->index,false,'index',true,sprintf("onchange=\"menu_unhide('index',%s)\"",$this->index)));
echo '</td></tr></table>';
echo '</form>';
echo "\n\n";
}
foreach ($_SESSION[APPCONFIG]->getServerList() as $index => $server) {
printf('<div id="SID_%s" style="display: %s">',$server->getIndex(),($server->getIndex() == $this->index) ? 'block' : 'none');
$menu = menu::getInstance($server->getIndex());
$menu->draw();
echo '</div>';
echo "\n\n";
}
}
public function block_add($side,$object) {
if (! is_object($object))
error(sprintf('block_add called with [%s], but it is not an object',serialize($object)));
$this->_block[$side][] = $object;
}
private function block_print($side) {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with ()',129,__FILE__,__LINE__,__METHOD__);
if (! isset($this->_block[$side]))
return;
printf('<td class="%s" colspan=2>',$side);
foreach ($this->_block[$side] as $object)
echo $object->draw($side);
echo '</td>';
}
private function sysmsg() {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with ()',129,__FILE__,__LINE__,__METHOD__);
if (isset($this->sysmsg)) {
foreach ($this->sysmsg as $index => $details) {
switch ($details['type']) {
case 'error':
$icon = $this->_default['sysmsg']['error'];
break;
case 'warn':
$icon = $this->_default['sysmsg']['warn'];
break;
case 'info':
default:
$icon = $this->_default['sysmsg']['info'];
break;
}
if (isset($details['title']))
printf('<tr><td class="icon" rowspan=2 align="right"><img src="%s" alt="%s" /></td><td class="head" align="right">%s</td></tr>',
$icon,$details['type'],$details['title']);
if (isset($details['body']))
if (is_array($details['body'])) {
echo '<tr><td class="body">';
foreach ($details['body'] as $line)
printf('%s<br />',$line);
echo '</td></tr>';
} else
printf('<tr><td class="body">%s</td></tr>',$details['body']);
}
}
}
public function body() {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with ()',129,__FILE__,__LINE__,__METHOD__);
# Add the Session System Messages
if (isset($_SESSION['sysmsg']) && is_array($_SESSION['sysmsg'])) {
foreach ($_SESSION['sysmsg'] as $msg)
$this->setsysmsg($msg);
unset($_SESSION['sysmsg']);
}
if (isset($this->sysmsg)) {
echo '<table class="sysmsg">';
$this->sysmsg();
echo '</table>';
echo "\n";
}
if (isset($this->_block['body'])) {
foreach ($this->_block['body'] as $object)
echo $object->draw('body');
}
}
private function footer_print() {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with ()',129,__FILE__,__LINE__,__METHOD__);
printf('<tr class="foot"><td><small>%s</small></td><td colspan=2><div id="ajFOOT">%s</div>%s</td></tr>',
isCompress() ? '[C]' : '&nbsp;',
app_version(),
'');
}
/**
* Only show a particular page frame - used by an AJAX call
*/
public function show($frame,$compress=false) {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with (%s)',129,__FILE__,__LINE__,__METHOD__,$compress);
# If the body is called via AJAX, and compression is enable, we need to compress the output
if ($compress && ob_get_level() && isCompress()) {
ob_end_clean();
ob_start();
}
switch ($frame) {
case 'BODY' :
$this->body();
break;
case 'MENU' :
$this->menu();
break;
default :
error(sprintf('show called with unknown frame [%s]',$frame),'error','index.php');
}
if ($compress && ob_get_level() && isCompress()) {
$output = ob_get_contents();
ob_end_clean();
if (DEBUG_ENABLED)
debug_log('Sending COMPRESSED output to browser[(%s),%s]',129,__FILE__,__LINE__,__METHOD__,
strlen($output),$output);
print gzencode($output);
}
}
public function display($filter=array()) {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with [%s]',129,__FILE__,__LINE__,__METHOD__,$filter);
# Control what is displayed.
$display = array(
'HEAD'=>true,
'CONTROL'=>true,
'MENU'=>true,
'FOOT'=>true
);
$display = array_merge($display,$filter);
# HTML Header
$this->pageheader_print();
# Start of body
# Page Header
echo '<body>';
echo "\n";
echo '<table class="page" border=0 width=100%>';
if ($display['HEAD'])
$this->head_print();
# Control Line
if ($display['CONTROL']) {
echo '<tr class="control"><td colspan=3>';
echo '<div id="ajCONTROL">';
$this->control_print();
echo '</div></td></tr>';
echo "\n";
}
# Left Block
echo '<tr>';
if ($display['MENU']) {
echo '<td class="menu" colspan=2>';
echo '<div id="ajMENU">';
$this->menu();
echo '</div>';
echo '</td>';
}
echo '<td class="body" width=80%>';
echo '<div id="ajBODY">';
echo "\n";
$this->body();
echo '</div>';
echo '</td>';
echo '</tr>';
echo "\n";
# Page Footer
if ($display['FOOT'])
$this->footer_print();
# Finish HTML
echo '</table>';
echo '</body>';
echo '</html>';
# compress output
if (ob_get_level() && isCompress()) {
$output = ob_get_contents();
ob_end_clean();
if (DEBUG_ENABLED)
debug_log('Sending COMPRESSED output to browser[(%s),%s]',129,__FILE__,__LINE__,__METHOD__,
strlen($output),$output);
print gzencode($output);
}
}
public function setsysmsg($data) {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with [%s]',129,__FILE__,__LINE__,__METHOD__,$data);
if (! is_array($data))
return;
if (isset($this->sysmsg))
$msgnum = count($this->sysmsg) + 1;
else
$msgnum = 1;
foreach (array('title','body','type') as $index)
if (isset($data[$index]))
$this->sysmsg[$msgnum][$index] = $data[$index];
}
}
/**
* This class draws a block.
*
* @package leenooksApp
* @subpackage Page
*/
class block {
private $title;
private $body;
private $foot;
public function __construct() {
}
public function setTitle($html) {
$this->title = $html;
}
public function setBody($html) {
$this->body = $html;
}
public function setFooter($html) {
$this->foot = $html;
}
public function draw($side) {
$output = '';
$output .= sprintf('<table class="%s">',$side);
if (isset($this->body['title']))
$output .= sprintf('<tr><td class="head">%s</td></tr>',$this->title);
if (isset($this->body['body']))
$output .= sprintf('<tr><td>%s</td></tr>',$this->body);
if (isset($this->body['footer']))
$output .= sprintf('<tr><td class="foot">%s</td></tr>',$this->foot);
$output .= '</table>';
return $output;
}
}
?>

21
lib/page_pta.php Normal file
View File

@@ -0,0 +1,21 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/page_pta.php,v 1.1 2008/01/13 08:05:12 wurley Exp $
/**
* Page Rendering Functions
*
* @package phpTSMadmin
*/
class page_pta extends page {
public function __construct() {
parent::__construct();
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED)
debug_log('Entered with [%s]',129,__FILE__,__LINE__,__METHOD__,$server_id);
# To be defined in a configuration file.
$this->_app['title'] = 'phpTSMadmin';
}
}
?>

185
lib/session_functions.php Normal file
View File

@@ -0,0 +1,185 @@
<?php
// $Header: /cvsroot/phptsmadmin/phpTSMadmin/lib/session_functions.php,v 1.4 2009/04/19 03:51:30 wurley Exp $
/**
* A collection of functions to handle sessions.
*
* @author Deon George (c) 2009
* @package leenooksApp
* @subpackage Session
*/
/** The session ID that this application will use for all sessions */
define('APP_SESSION_ID','APPSESSID');
/** Enables session paranoia, which causes SIDs to change each page load (EXPERIMENTAL!) */
define('app_session_id_paranoid', false);
/** Flag to indicate whether the session has already been initialized (this constant gets stored in $_SESSION) */
define('app_session_id_init', 'app_initialized');
/** The minimum first char value IP in hex for IP hashing. */
define('app_session_id_ip_min', 8);
/** The maximum first char value of the IP in hex for IP hashing. */
define('app_session_id_ses_max', 36);
/**
* Creates a new session id, which includes an IP hash.
*
* @return string the new session ID string
*/
function app_session_get_id() {
if (DEBUG_ENABLED)
debug_log('Entered with ()',1,__FILE__,__LINE__,__METHOD__);
$id_md5 = md5(rand(1,1000000));
$ip_md5 = md5($_SERVER['REMOTE_ADDR']);
$id_hex = hexdec($id_md5[0]) + 1;
$ip_hex = hexdec($ip_md5[0]);
if ($ip_hex <= app_session_id_ip_min)
$ip_len = app_session_id_ip_min;
else
$ip_len = $ip_hex - 1;
$new_id = substr($id_md5, 0, $id_hex) .
substr($ip_md5, $ip_hex, $ip_len) .
substr($id_md5, $id_hex, app_session_id_ses_max - ($id_hex + $ip_len));
return $new_id;
}
/**
* Checks if the session belongs to an IP
*
* @return boolean True, if the session is valid
*/
function app_session_verify_id() {
if (DEBUG_ENABLED)
debug_log('Entered with ()',1,__FILE__,__LINE__,__METHOD__);
$check_id = session_id();
$ip_md5 = md5($_SERVER['REMOTE_ADDR']);
$id_hex = hexdec($check_id[0]) + 1;
$ip_hex = hexdec($ip_md5[0]);
if ($ip_hex <= app_session_id_ip_min)
$ip_len = app_session_id_ip_min;
else
$ip_len = $ip_hex - 1;
$ip_ses = substr($check_id, $id_hex, $ip_len);
$ip_ver = substr($ip_md5, $ip_hex, $ip_len);
return ($ip_ses == $ip_ver);
}
function app_session_param() {
/* If cookies were disabled, build the url parameter for the session id.
* It will be append to the url to be redirect */
return (SID != '') ? sprintf('&%s=%s',session_name(),session_id()) : '';
}
/**
* The only function which should be called by a user
*
* @see common.php
* @see APP_SESSION_ID
* @return boolean Returns true if the session was started the first time
*/
function app_session_start() {
$sysmsg = null;
# If we have a sysmsg before our session has started, then preserve it.
if (isset($_SESSION['sysmsg']))
$sysmsg = $_SESSION['sysmsg'];
/* If session.auto_start is on in the server's PHP configuration (php.ini), then
* we will have problems loading our schema cache since the session will have started
* prior to loading the SchemaItem (and descedants) class. Destroy the auto-started
* session to prevent this problem.
*/
if (ini_get('session.auto_start'))
@session_destroy();
# Do we already have a session?
if (@session_id())
return;
@session_name(APP_SESSION_ID);
@session_start();
# Do we have a valid session?
$is_initialized = is_array($_SESSION) && array_key_exists(app_session_id_init,$_SESSION);
if (! $is_initialized) {
if (app_session_id_paranoid) {
ini_set('session.use_trans_sid',0);
@session_destroy();
@session_id(app_session_get_id());
@session_start();
ini_set('session.use_trans_sid',1);
}
$_SESSION[app_session_id_init]['name'] = app_name();
$_SESSION[app_session_id_init]['version'] = app_version();
$_SESSION[app_session_id_init]['config'] = filemtime(CONFDIR.'config.php');
}
@header('Cache-control: private'); // IE 6 Fix
if (app_session_id_paranoid && ! app_session_verify_id())
error('Session inconsistent or session timeout','error','index.php');
# Check we have the correct version of the SESSION cache
if (isset($_SESSION['cache']) || isset($_SESSION[app_session_id_init])) {
if (! is_array($_SESSION[app_session_id_init])) $_SESSION[app_session_id_init] = array();
if (! isset($_SESSION[app_session_id_init]['version']) || ! isset($_SESSION[app_session_id_init]['config']) || ! isset($_SESSION[app_session_id_init]['name'])
|| $_SESSION[app_session_id_init]['name'] !== app_name()
|| $_SESSION[app_session_id_init]['version'] !== app_version()
|| $_SESSION[app_session_id_init]['config'] != filemtime(CONFDIR.'config.php')) {
$_SESSION[app_session_id_init]['name'] = app_name();
$_SESSION[app_session_id_init]['version'] = app_version();
$_SESSION[app_session_id_init]['config'] = filemtime(CONFDIR.'config.php');
unset($_SESSION['cache']);
unset($_SESSION['USER']);
unset($_SESSION[APPCONFIG]);
# Our configuration information has changed, so we'll redirect to index.php to get it reloaded again.
system_message(array(
'title'=>_('Configuration cache stale.'),
'body'=>_('Your configuration has been automatically refreshed.'),
'type'=>'info','special'=>true));
$config_file = CONFDIR.'config.php';
$config = check_config($config_file);
if (! $config)
debug_dump_backtrace('config is empty?',1);
} else {
# Sanity check, specially when upgrading from a previous release.
if (isset($_SESSION['cache']))
foreach (array_keys($_SESSION['cache']) as $id)
if (isset($_SESSION['cache'][$id]['tree']['null']) && ! is_object($_SESSION['cache'][$id]['tree']['null']))
unset($_SESSION['cache'][$id]);
}
}
# If we came via index.php, then set our $config.
if (! isset($_SESSION[APPCONFIG]) && isset($config))
$_SESSION[APPCONFIG] = $config;
# Restore our sysmsg's if there were any.
if ($sysmsg) {
if (! isset($_SESSION['sysmsg']) || ! is_array($_SESSION['sysmsg']))
$_SESSION['sysmsg'] = array();
array_push($_SESSION['sysmsg'],$sysmsg);
}
}
/**
* Stops the current session.
*/
function app_session_close() {
@session_write_close();
}
?>

1906
lib/tsm_classes.php Normal file

File diff suppressed because it is too large Load Diff