PHP Classes and Functions Available Globally on FMP's Web Server


Class: fmplib_db

This class emulates phplib's db_SQL class.  See
http://www.sanisoft.com/phplib/manual/DB_sql.php.  As written, this
class require PHP version 5.

Instance variables are:

Host:
  Host on which SQL server is running

Database:
  Name of database or instance to use on that server.

User:
  The username to use for connections.

Password:
  The password to use for connection.

Row:
  Number of the current result row starting at 0,

Auto_free:
  Boolean: Flag for early result memory release.

Errno:
  Integer: error number of last database operation (not
  implemented)
  
Error:
  String error message of the last db operation (not implemented).

Record:
  A hash array of the current result row.

Debug:
  Boolean: If set, the database class will output all queries and
  additional diagnostic output.

type:
  Contant string: The name of the database interface, e.g. "mysql"
  or "oracle"

mysqli:
  Database handle for mysqli instance on the specified database



Instance methods:

fmplib_db::__constructor(string $type = "mysql"):
  Constructor.  DB type defaults to MySQL.

fmplib_db::query(string $query):
  Query string to send to the SQL engine

fmplib_db::next_record():
  Advances the cursor through the current query result and updates
  the Record, Row, Errno and Error instance variables.

fmplib_db::all_records():
        Returns a hash of all records matching the previous query, or False
        if there are no matches.

fmplib_db::num_rows():
  Returns the number of rows returned by the current SELECT query
  (not available in all DB interfaces).

fmplib_db::nf():
  Same as num_rows().

fmplib_db::affected_rows():
  Returns the number of rows affected by the current INSERT, UPDATE
  or DELETE query.

fmplib_db::np():
  Prints the number of rows returned by the current query.

fmplib_db::num_fields():
  Returns the number of columns returned by the current query.

fmplib_db::f(string $field):
  Returns the string value of referenced field.

fmplib_db::p(string $field):
        Prints the string value of the referenced field.

fmplib_db::seek(integer $pos):
  Positions the Row pointer within the result set.

fmplib_db::get_db():
  Returns the MDB2 database object.

fmplib_db::real_escape_string($string):
  Returns a string properly escaped for use with the database
  connection created by instantiation of this class on a mysql
  database.  This requires mysqli support
  	

Class: fmplib_session

Instances of this class operate in two different modes, depending on
whether or not a PHP session is already in progress
(is_array($_SESSION)).  If a session has been previously started,
class methods are limited to registering and unregistering variables
and retrieving information about the previously started session.   

Other classes may also initiate a session, or a session may be
auto-started if session.auto_start is turned on, and it would be
inappropriate for a session class to modify these settings outside
of other classes, such as the PEAR Auth class, which also depend on
session continuity.  Setup of a session management profile should be
done before instantiation of any class, including this one, which
establishes a session.

This class is intended purely as a programming aid to assist in the
objectification of session data and session-related methods and as a
storage location for session information.  Class methods follow
those in PHPlib's session class inasmuch as possible, however full
emulation of PHPlib's session class is not possible in current
versions of PHP, nor are methods supported in this class which might
conflict with other session related methods or mechanisms internal
to other classes.

The code herein is covered under the terms of the GNU General Public
License, Version 3, a copy of which can be found at
<http://www.gnu.org/licenses/gpl-3.0.txt>.

This class requires PHP5 or greater

 COOKIE vs. GET

 Columns:  session.u_c    = session.use_cookies
           session.u_o_c  = session.use_only_cookies
           session.u_t_s  = session.use_trans_sid

 Results:  C = session set by cookie
           U = session set in URL
           B = session not set - broken!

 SERVER                                          | BROWSER RESULT
 session.u_c        session.u_o_c   session.u_t_s  cook_on  cook_off
 -------------------------------------------------------------
 true               true            false          C        B         Default setting for max security    CC
 true               true            true           U->C     B         Uses URL until cookie estab.
 false              true            false          B        B                        
 false              true            true           U        B
 true               false           false          C        B
 true               false           true           U->C     U         Uses URL until cookie estab.        CU
 false              false           false          B        B         Cookie set if allowed, sess broken
 false              false           true           U        U                                             UU, UC


Publicly accessible methods
---------------------------

fmplib_session::__construct()

Synopsis:

Description:

  Class constructor.  Initializes instance variables, 


fmplib_session::__destruct()

Synopsis:

Description:

  Class destructor.  Freezes all registered variables


fmplib_session::name()

Synopsis:

  string = name()

Description:

  Returns the session name as currently registered with the PHP
  session.


fmplib_session::new_id()

Synopsis:

  bool new_id()

Description:

  If a dominant session has been instantiated, replaces the current
  session id with a new one, and deletes the current session
  information.  If the session is not dominant, does nothing and
  returns false.


fmplib_session::get_id()

Synopsis:

  string get_id()

Description:

  Returns the current session ID, as registered with the current
  fmplib_session object.


fmplib_session::register()

Synopsis:

  void register(mixed $varnames)

Description:
  
  Registers variables identified by $varnames with the current
  session under $_SESSION["fmplib"]["data"].  $varnames may be a
  comma separated string or an array list of names, represented as
  strings, e.g. "foo" or "foo,bar,baz" or {"foo","bar","baz"}.
  Registered variables become persistent.
  

fmplib_session::unregister()

Synopsis:

  bool unregister(mixed $varnames)

Description:

  Unregisters variables identified by $varnames from the current
  session under $_SESSION["fmplib"]["data"].  $varnames may be a
  comma separated string or an array list of names, represented as
  strings, e.g. "foo" or "foo,bar,baz" or {"foo","bar","baz"}.
  Unregistered variables are no longer persistent.  Always returns
  true.


fmplib_session::put_id()

Synopsis:

  bool put_id()

Description:
 
  If and only if this instance is attached to a dominant session,
  delete the cookie holding the session id.  Return true if the
  session is dominant and uses cookies and cookie can be deleted.
  Otherwise return false.
  

fmplib_session::delete()

Synopsis:

  bool delete()

Description:

  If the instance of this class is attached to a dominant session,
  destroy the session by calling session_destroy().  In any case,
  $_SESSION["fmplib"] is unset.


fmplib_session::url()

Synopsis:

  string url(string $url)

Description:

  If using URL-based session data, return $url with the session data
  appended, otherwise just return $url unaltered.


fmplib_session::purl()

Synopsis:

  void purl($url)

Description:

  print $url.  See fmplib_session::url() above.


fmplib_session::self_url()

Synopsis:

  string self_url()

Description:

  Returns URL of corrent page with session information appended to
  the query string.


fmplib_session::get_hidden_session()

Synopsis:

  string get_hidden_session()

Description:

  Returns a form hidden input element containing the session id


fmplib_session::get_hidden_id()

Synopsis:

  string get_hidden_id()

Description:

  Synonym for get_hidden_session()


fmplib_session::hidden_id()

Synopsis:

  void hidden_id()

Description:

  Synonym for fmplib_session::hidden_session()


fmplib_session::serialize()

Synopsis:

  string serialize()

Description:

  Get the serialized string of all session variables.


fmplib_session::deserialize()

Synopsis:

  bool deserialize(string &$data_string)

Description:

  Decodes the session data in $data_string, setting variables stored in the
  session.


fmplib_session::freeze()

Synopsis:

  void freeze()

Description:

  Freezes all registered things (scalar variables, arrays, objects)
  by saving all registered things to $_SESSION["fmplib"]["data"].


fmplib_session::reimport_get_vars()

Synopsis:

  void reimport_get_vars()

Description:

  Reimport $_GET variables into the global namespace previously
  overriden by session variables. 


fmplib_session::reimport_post_vars()

Synopsis:

  void reimport_post_vars()

Description:

      Reimport $_POST variables into the global namespace previously
      overriden by session variables.  @see  reimport_get_vars(),
      reimport_cookie_vars()


fmplib_session::reimport_cookie_vars()

Synopsis:

  void reimport_cookie_vars()

Description:

  Reimport $_COOKIE variables into the global namespace previously
  overriden by session variables.  @see  reimport_post_vars(),
  reimport_get_vars().
  

fmplib_session::reimport_any_vars()

Synopsis:

  void reimport_any_vars(string $arrayname)

Description:

  Import any array specified by $arrayname into the $_GLOBAL scope.

  	

Class: fmplib_uservar

This class implements a simple user variable storage class which can
be used in place of phplib's user variables, which seem to have
problems.  It requires the following table:

CREATE TABLE `uservar` (
  `username` varchar(20) default NULL,
  `variables` blob
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

This class is abstract and can't be instantiated, nor can its methods
be called statically.  The derived class must define $db_classname to 
be a previously defined fmplib_db subclass with proper access tokens 
defined.

It implements five simple methods:

void fmplib_uservar(string $name):
   Constructor:  This establishes and registers the name associated
   with the stored variables.   This should generally be the
   logged-in username, possibly concatenated with the script name.
   All variables associated with this name in the uservar table are
   restored and registered.

void register($varname):
   Registers the named variable and its current value in the $GLOBAL
   array associated with the registered name of the class instance.
   If a class derived from this class is instantiated within a
   function call, all variables must be declared global prior to
   calling register() on them or their value will be lost.

void unregister($varname):
   Unregisters a variable name.

void freeze():
   Deletes any variables previously stored in the database under the
   registered name, updates the $GLOBAL array of regsiterd
   variables, serializes it, and stores it permanently in the
   uservar table.  This function must be called somewhere in your
   program prior to exiting.  

void thaw():
   Restores variables associated with the regitered name, as does
   the class constructor.  Normally this method won't be needed
   since its functionality is a large subset of the class
   constructor.

  	

Class: PermAuth

Class to retrieve and use permissions based on authorized user.
PermAuth extends the PEAR::Auth class.  See
http://pear.php.net/package/Auth for more information on the base
class.
       
REQUIRES PHP version 5 or greater

Addional options supported (see Auth documentation):
    aPerms      - Perm definition=>value array;
    permfield   - Name of field containing perms (default "perms")
    permtable   - Name of table containing perms (default same as $options["table"] or "auth") 
    permusercol - Name of table field containing perm user (default same as $option["usernamecol"] or "username")

Permissions are stored as strings in a comma-separated data field
(permfield).

PermAuth::getPerm()

Synopsis:
  
  require_once("MDB.php");

  array PermAuth::getPerm()

Description:
  
  Returns an ordered array of the perm strings for the currently
  logged-in user.


PermAuth::hasPerm()

Synopsis:

  boolean PermAuth::hasPerm(string $testperm [, boolean $bitfield = True])

Description:
 
  Determines whether the currently logged-in user has the permission
  $testperm.  Two different methods are available to compute this.  If
  $bitfield = True (the default), the permission values of the
  current user (as defined in the $aPerms array) are ORed and the
  result is ANDed with the perm value of $testperm.  If the result
  is > 0, the method returns True, otherwise False.  If $bitfield is
  False, the maximum permission value of the current user is
  compared numerically with the value of $testperm.  If the current
  user's max perm value is greater than or equal to the value of
  $testperm, the method returns True, otherwise False.

  If the perms array ($aPerms) assigns bitmasks with all bits set to
  the defined perms (1, 3, 7, 15, etc.) these two methods are
  equivalent.  If the defined perms contain numbers without respect
  to bit positions (1, 2, 3, 4, 5 etc.) then the methods yield
  different results.  Fairly complex permissions schema can be set
  up using bitfields.

Parameters:

  string $testperm

    Permission string against which to test the permissions of the
    currently logged-in user.  $testperm should correspond to a key
    in $aPerms, otherwise the method will always return False.

  boolean $bitfield

    If True, permissions are considered bitfields and a bitwise
    comparison (logical AND) of $testperm with the ORed combination
    of user perm values determines the return value of the method.
    If $bitfield is False, the maximum user perm value is compared
    numerically with $testperm to determine the result.
  

Function: sanitize

This isn't a class, but a function which can be called to perform a hack check on user input fields. What follows is the code preamble comments.
# define modes for sanitize()
# 
define("V_EMAIL", 1);
define("V_HEADER", 2);

# To use the sanitize function, include "sanitize.inc" in your PHP 
# application.
#
# sanitize($array)
#
# sanitize() accepts an associative array of variable names (expressed 
# as strings) associated with a defined type which is either V_EMAIL
# (email address) or V_HEADER (other text header).  The function
# validates the varible associated with the string, in the first case
# as a valid simple email address and in the second case as a string
# free of newlines which might be used to spoof the PHP mail()
# function into inserting additional headers (see
# http://us2.php.net/manual/en/function.mail.php#59661)
#
# sanitize returns True if all variables in $array are sanitary,
# otherwise it returns False. 
# 
# Example:
#    include("sanitize.inc");
#    $sanitize_arr = array ("sender" => V_EMAIL, "subject" => V_HEADER);
#    if (sanitize($sanitize_arr)) {
#        [all data is sanitary, so process it]
#    } else {
#        [There is an error in either $sender or $subject.  Declare an input error and don't process it.]
#    }
#