Develop:FreeNATS
Contents
- 1 Developing Server-Side PHP with FreeNATS
- 2 The $NATS Object
- 2.1 Useful Properties
- 2.2 Useful Methods
- 2.2.1 Event - logs an event to the system log
- 2.2.2 GetAlerts - get current alerts
- 2.2.3 GetNode - get array of node information
- 2.2.4 SetNode - set fields on the node
- 2.2.5 EnableNode - enable/disable testing on a node
- 2.2.6 DisableNode - disable testing on a node
- 2.2.7 GetGroup - get group array information
- 2.2.8 GetNodeTests - get array of enabled test ids for the node
- 2.2.9 GetTest - get test information in an array
- 2.2.10 AddEventHandler - register an event handler
- 2.3 $NATS Sub-Objects
- 3 $NATS->DB Database Engine
- 4 $NATS->Cfg - Configuration Engine
- 5 $NATS_Session - Session Manager
- 6 Test Modules (Tests)
Developing Server-Side PHP with FreeNATS
When developing server-side PHP such as event handlers or test modules there are a number of environment objects and functions available for you to use.
The $NATS Object
The $NATS object is the current instance of the TFreeNATS class. If you want to look at the methods etc manually have a look at the server/base/freenats.inc.php file.
Using the NATS object you can fetch information, log system events and even perform direct database queries.
Some of the functionality is provided by properties and methods of the $NATS object and some are sub-objects.
Useful Properties
$NATS->Version $NATS->Release
System version (e.g. 1.00.6) and release type (e.g. a) respectively.
$NATS->init
bool to show if system is initialised or not
Useful Methods
Event - logs an event to the system log
Puts an entry into the system log (if the log level is low enough for the site config)
$NATS->Event( $event_text, [ $loglevel=1 , [ $module="NONE" , [ $category="NONE" ] ] ] )
Logs the text in $event_text with the optional log level (1 is fatal/major, 10 is debug information) and optional module name and category. Events are only logged if their level is equal to or less than the log.level variable setting.
If a user is logged in the username is automatically recorded in the log as well.
GetAlerts - get current alerts
Returns an array of sub-arrays of the format
"nodeid" => nodeid "alertlevel" => numeric alert level
of any alerts or false if there are no alerts
$alerts=$NATS->GetAlerts();
if ($alerts===false) echo "No Alerts";
else echo "There are ".count($alerts)." Alerts";
GetNode - get array of node information
Returns an array of node info from the fnnode table with some extra fields for the specified nodeid
$node=$NATS->GetNode("mynode");
echo "mynode hostname is ".$node['hostname'];
SetNode - set fields on the node
Takes an array where the keys are field names and the values the values to update them to.
$data=array(
"hostname" => "new.hostname.com", "pingtest" => 1 );
$NATS->SetNode("mynode",$data); Would set the hostname and turn on ping testing for mynode.
Don't use this to update test values or alert levels! They will just break or be reset when the main system runs. Only use this function to update node configuration settings.
EnableNode - enable/disable testing on a node
$NATS->EnableNode ( $nodeid , [ $enabled = true ] )
Use this function to enable or disable a node
$NATS->EnableNode("mynode");
$NATS->EnableNode("othernode",false);
Would enable mynode and disable othernode.
DisableNode - disable testing on a node
$NATS->DisableNode( $nodeid )
Wrapped for EnableNode but sets enabled to false
GetGroup - get group array information
$group=$NATS->GetGroup( $groupid )
Get group information in an array (similar to GetNode for nodes)
GetNodeTests - get array of enabled test ids for the node
$tests=$NATS->GetNodeTests( $nodeid )
Returns a one-dimensional array of the test ids of enabled tests (both local and nodeside) for the node (suitable for use with GetTest)
GetTest - get test information in an array
$test=$NATS->GetTest( $testid )
Similar to GetNode/GetGroup but will return data for the test specified. Takes a full test ID including class i.e. LXX for local tests or NYY for nodeside tests. Queries the relevant table and adds some extra fields.
AddEventHandler - register an event handler
$NATS->AddEventHandler( $event, $function )
Adds a handler of $function for the event in $event. See developing events for more information.
$NATS Sub-Objects
The NATS object has a number of sub-objects which are documented below including:
- Database Engine (DB)
- Configuration Engine (Cfg)
- Test Modules (Tests)
$NATS->DB Database Engine
You can use the $NATS->DB object to directly perform SQL queries on the database using the FreeNATS system login.
Using DB directly especially for updates is not recommended - you should use the relevant API or request it to be implemented to ensure you code continues to function correctly in later releases
Safety and ss()
It is recommended you protect all user input for a query using ss() which does a safe_string for the relevant database environment (currently only MySQL is supported).
$query="UPDATE ".$table." SET value=".ss($USER_INPUT)." WHERE key=1234";
Direct Queries
You can perform direct SQL queries using the $NATS->DB->Query($sql) method. The query will return a result identifier if appropriate.
Query data is returned using the Fetch_Array() method and some other methods are also available, for example:
// First a SELECT query
$query="SELECT * FROM fnnode WHERE nodeenabled=1";
$result=$NATS->DB->Query($query);
if ($NATS->DB->Num_Rows($result)<=0)
echo "Sorry no nodes!
";
else
{ while ($node = $NATS->DB->Fetch_Array($result)) { echo $node['nodeid']."
"; } }
$NATS->DB->Free($result);
// Now an update $query="UPDATE fnnode SET hostname=\"".ss($USER_INPUT)."\" WHERE nodeid=\"mynode\""; $NATS->DB->Query($query); if ($NATS->DB->Error())
echo "Query Returned An Error";
else if ($NATS->DB->Affected_Rows()<=0)
echo "Query Affected No Rows";
else
echo "Query Success";
$NATS->Cfg - Configuration Engine
You can read and write system configuration variables (normally set through the admin interface) through the Cfg sub-object of NATS.
Reading Variables
$NATS->Cfg->Get( $variable , [ $default = "" ] )
Returns the contents of the variable or a blank string (or whatever you have passed if a default is specified) if the variable doesn't exist.
if ( $NATS->Cfg->Get("some.variable",0) == 1 )
// do the action
else
// don't do the action
Setting Variables
$NATS->Cfg->Set( $variable, $value, [ $perm = true ] )
Sets the variable to the specified value. If perm is true (or unspecified) then the change is saved to the database and permanent otherwise it's just present for this current instance of FreeNATS (the current program execution cycle).
$NATS->Cfg->Set("some.variable",1); // sets some.variable to 1 now and in the database
$NATS->Cfg->Set("other.variable",1,false); // sets other.variable to 1 for now only
$NATS_Session - Session Manager
Once you have started NATS then the $NATS_Session session manager object will be available. This is used by FreeNATS to authenticate, register and check user sessions.
Manual Login or Session Registration
You can manually perform a login optionally checking the password against the FreeNATS user database (allowing third-party authentication for a valid FreeNATS user) with the $NATS_Session->Create() and $NATS_Session->Register() methods.
Create takes the NATS DB object, a username and a password. These are checked against the user database (fnuser table with passwords MD5 encoded). On success the session is registered and a sessionid returned, on failure false is returned.
Register takes the NATS DB object and a username only (the validation having been done on the credentials elsewhere). It attempts to register the session for that user. If the user is valid the session is registered (put into the database and cookies sent to the browser). Returns a sessionid on success or false on failure.
Please note the cookies are set for the domain/directory and below only and so can't just be called by some other off-site (to the browser) script.
To see how the authentication against the database works see the server/web/login.php file in distributions.
To use the Register() method in custom authentication please see the custom login example script.
Checking a Session
Sessions are checked using the $NATS_Session->Check method which takes the NATS DB object and returns true for a valid session or false if invalid. Certain other things are set once the session is checked such as user information.
This is the code that sits above most NATS interface pages:
ob_start();
require("include.php");
$NATS->Start();
if (!$NATS_Session->Check($NATS->DB))
{
header("Location: ./?login_msg=Invalid+Or+Expired+Session");
exit();
}
ob_end_flush();
Additionally admin pages etc have a line like:
if ($NATS_Session->userlevel<9) UL_Error("Admin Interface");
Which checks the userlevel is high enough (available once the session is validated). UL_Error just kicks the user back to the main screen with an appropriate error.
Logging Out / Destroying a Session
To destroy a session call the $NATS_Session->Destroy() method and pass the NATS DB object. The session must have been initialised (checked) first. For example a logoff script could go:
require("include.php");
$NATS->Start();
if ($NATS_Session->Check($NATS->DB)) // get session info
{ $NATS_Session->Destroy($NATS->DB); }
echo "You are logged out";
Test Modules (Tests)
Tests modules are registered and managed through the Tests sub-object of $NATS.
Please see the developing server-side tests documentation for information on how to register modules.