Rev 67 | Rev 69 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
<?php
class Camp {
protected static $dbStructure;
//public static $myName;
//protected static $viewName = 'view_device_location_owner_type';
/**
* Builds an instance and loads data from database
*
* #parameter int $id The id of the record to load
*/
public function __construct( $id = 0 ) {
if ( $id ) {
$this->loadFromDB( $id );
$_SESSION['workingon'][get_called_class()] = $id;
}
} // __construct
public function loadFromDB( $id ) {
global $dbConnection;
$this->data = array();
$fields = array();
$calculatedFields = array();
foreach ( static::$dbStructure['table']['fields'] as $key => $data ) {
switch ( $data['type'] ) {
case '1:1H' : // one to one with history
$calculatedFields[] = $data['fieldname'];
$calculatedFields[] = $data['displayColumn'];
break;
case '1:M' : // one to many
$calculatedFields[] = $data['fieldname'];
break;
default: // standard
$fields[] = $data['fieldname'];
}
}
$query = sprintf( "select %s from %s where %s = %s",
implode( ',', $fields ),
static::$dbStructure['table']['tableName'],
static::$dbStructure['table']['primaryKey'],
$id
);
//print "<pre> Constructor using query\n$query</pre>";
//print "<pre>Constructor finding dbstructure of\n" . print_r( static::$dbStructure, true) . '</pre>';
if ( ( $this->data = $dbConnection->getOneRow( $query ) ) === false )
print DBQuery::error2String();
//print "<pre>" . print_r( $calculatedFields, true ) . "</pre>"; die;
//print "<pre>" . print_r( $this->data, true ) . "</pre>"; die;
if ( count( $calculatedFields ) ) {
$query = sprintf( 'select distinct %s from %s %s',
implode( ',', $calculatedFields ),
static::$dbStructure['view']['viewName'],
static::makeWhereClause( array(
static::$dbStructure['table']['fields']['id']['fieldname'] .
' = ' .
$this->data[static::$dbStructure['table']['primaryKey']] )
)
);
//print "<pre>$query</pre>"; die;
$result = $dbConnection->getOneRow( $query );
foreach ( $calculatedFields as $field ) {
$this->data[$field] = empty( $result[$field] ) ? '' : $result[$field];
} // foreach
}
//print "<pre>Data after loadFromDB\n" . print_r($this->data, true) . "</pre>"; die;
} // loadFromDB
/**
* gets the contents of $fieldname
*
* @parameter string $fieldname name of the database field to retrieve
*
* @return string The value of $fieldname stored in structure
*/
public function __get( $fieldname ) {
if ( empty( $this->data ) )
$this->data = array();
return
isset( $this->data[static::$dbStructure['table']['fields'][$fieldname]['fieldname']] ) ?
$this->data[static::$dbStructure['table']['fields'][$fieldname]['fieldname']] :
null;
} // __get
/**
* Gets stats for an extended class.
*
* Gets number of active and inactive rows for a class, using the
* view ($viewName)
*
* @return int[] array of integers which is a count
*/
public static function getStats () {
global $dbConnection;
global $activeOnly;
$return = array();
$restrictions = array();
$trueClass = get_called_class();
$saveActive = $activeOnly;
$activeOnly = false;
/*
$query = sprintf(
'select count(*) num,isnull(removed) active from %s %s group by isnull(removed) order by isnull(removed) desc',
static::$dbStructure['table']['tableName'],
self::makeWhereClause()
);
$result = $dbConnection->doSQL( $query );
//print '<pre>' . print_r( $result, true ) . "</pre>"; die;
foreach ( $result['returnData'] as $row ) {
if ( $row['active'] == 1 ) {
$return['active'] = $row['num'];
} elseif ( $row['active'] == 0 ) {
$return['inactive'] = $row['num'];
}
}
*/
$active = sprintf(
'select count(distinct %s) from %s %s',
static::$dbStructure['table']['primaryKey'],
static::$dbStructure['view']['viewName'],
self::makeWhereClause()
);
$activeOnly = false;
$inactive = sprintf(
'select count(distinct %s) from %s %s',
static::$dbStructure['table']['primaryKey'],
static::$dbStructure['view']['viewName'],
self::makeWhereClause( array( strtolower( $trueClass ) . "_removed is not null" ) )
);
//print "<pre>Active\n$active</pre><pre>Inactive\n$inactive</pre>"; die;
$return['active'] = $dbConnection->getOneDBValue( $active );
$return['inactive'] = $dbConnection->getOneDBValue( $inactive );
$activeOnly = $saveActive;
return $return;
}
/**
* Creates a where clause
*
* Merges $restrictions with any restrictions which may be in place
* for the current user. Also sets 'class_removed is null' if
* $activeOnly (global) is set
*
* @parameter string[] $restrictions array of conditionals
*
* @return string all restricions ANDED together
*/
public static function makeWhereClause( $restrictions = array(), $restrictGlobals = array(), $tablename = null ) {
global $activeOnly;
//print "<pre>" . print_r( $restrictions, true ) . "</pre>";
$trueClass = get_called_class();
foreach ( $_SESSION['restrictions'] as $class => $restriction ) {
$restrictions[] = $_SESSION['restrictions'][$class];
}
if ( $activeOnly ) {
$restrictions[] = ( $tablename ? $tablename . '.' : strtolower( $trueClass ) . '_' ) . 'removed is null';
}
/*
if ( isset( $restrictGlobals['workingon'] ) && isset( $_SESSION['workingon'] ) ) {
foreach ( $_SESSION['workingon'] as $class => $id ) {
$restrictions[] = strtolower( $class ) . "_id = $id";
}
}
*/
return count( $restrictions ) ? 'where ' . implode( ' and ', $restrictions ) : '';
} //
/**
* Creates a list of all records for a particular class and returns
* a UL with all LI's set as links (A's) to displaying a record.
*
* @parameter string[] $filter array of conditionals to limit if $list not set
* @parameter string[] $list An optional list of data to be displayed
*
* @return string A UL with each LI containing a link to an entry
*/
public static function showSelectionList( $filter = array(), $list = array(), $noAdd = false ) {
global $url;
$return = array();
$module = get_called_class();
unset ( $_SESSION['workingon'][get_called_class()] );
if ( empty( $list ) ) {
$list = self::getAll( $filter );
}
//print "<pre>showSelectionList\n" . print_r( $list, true ) . "</pre>"; die;
foreach ( $list as $id => $name ) {
if ( $id )
$return[] = "<a href='$url?module=$module&id=$id'>$name</a>";
}
//print "<pre>noadd is $noAdd</pre>"; die;
if ( ! $noAdd && $_SESSION['user']->isAuthorized( strtolower($module) . '_add') )
$return[] = "<br /><a href='$url?module=$module&action=add'>Add New</a>";
return count($return) ? "<ul>\n<li>" . implode( "</li>\n<li>", $return ) . "</li>\n</ul>" : '';
}
/**
* Gets all matching rows
*
* Does an SQL call to retrieve ID and Name for all rows matching
* $filter and $_REQUEST['to_find'].
*
* @parameter string[] $filter Optional list of conditionals for where clause
*
* @return array[] An array of indexes and names matching query
*/
public static function getAll( $filter = array(), $restrictGlobals = array() ) {
global $activeOnly;
global $dbConnection;
//print "<pre>" . print_r( $filter, true ) . "</pre>";
if ( isset( $_REQUEST['to_find'] ) ) {
$filter[] = sprintf( " %s like '%%%s%%'", static::$dbStructure['view']['selectionDisplay'], $_REQUEST['to_find']) ;
}
$return = array();
$query = sprintf( 'select distinct %s id, %s name from %s %s',
static::$dbStructure['view']['primaryKey'],
static::$dbStructure['view']['selectionDisplay'],
static::$dbStructure['view']['viewName'],
self::makeWhereClause( $filter, $restrictGlobals )
);
$query .= " order by " . static::$dbStructure['view']['selectionDisplay'];
//print "<pre>$query</pre>\n";
$result = $dbConnection->doSQL( $query );
$result = $result['returnData'];
foreach ( $result as $row ) {
$return[$row['id']] = $row['name'];
}
return $return;
}
/**
* Returns the "name" of an instance
*
* Normally, this is $this->name, but some classes may want to put
* in additional data
*
* @return string Display name of this instance
*/
public function __toString() {
return $this->name;
}
/**
* Returns an HTML structure which can display a record
*
* Note that if the instance has children, they will be displayed
* also. Additionally, if it has fields marked as type 'calculated'
* it will perform the limited calculations.
*
* @return string HTML to display record
*/
public function display() {
//print '<pre>' . print_r( $this->data, true) . '</pre>'; die;
global $url;
$return = array();
$save = '';
/* get the records for this, including from other tables */
foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
if ( isset( $record['display'] ) && $record['display'] === false ) // we don't try to show links
continue;
if ( $record['type'] == '1:1H' ) { // this one is supposed to be set up as a link
$return[] = sprintf(
"<td>%s</td><td><a href='$url?module=%s&id=%s'>%s</a></td>",
$record['displayName'],
$record['class'],
$this->data[$record['fieldname']],
$this->data[$record['displayColumn']]
);
} else { // just pulling data from the table itself
$return[] = '<td>' . $record['displayName'] . "</td>\n<td>" . $this->data[$record['fieldname']] . '</td>';
}
}
if ( $_SESSION['user']->isAuthorized( strtolower(get_called_class()) . '_edit') )
$return[] = sprintf( "<td colspan='2'><a href='$url?module=%s&id=%s&action=edit'>Edit</a></td>",
get_called_class(),
$this->data[static::$dbStructure['table']['primaryKey']]
);
$return = "<div class='show_record'>\n<table class='show_record'>\n<tr>" . implode("</tr>\n<tr>", $return ) . "</tr>\n</table>\n</div>";
/* Now, get the children records */
if ( isset( $_REQUEST['to_find'] ) ) {
$save = $_REQUEST['to_find'];
unset( $_REQUEST['to_find'] );
}
foreach ( static::$dbStructure['children'] as $class => $record) {
if ( isset( $record['filter'] ) ) { // we'll parse it against $this->data to fill in any variables
global $dbConnection;
$record['filter'] = $dbConnection->templateReplace( $record['filter'], $this->data );
//print "<pre>$filter\n" . print_r( $this->data, true) . "</pre>"; die;
} else {
$record['filter'] = static::$dbStructure['table']['primaryKey'] . ' = ' . $this->data[static::$dbStructure['table']['primaryKey']];
}
if ( ! isset( $record['name'] ) )
$record['name'] = $class;
//print "<pre>record\n" . print_r( $record, true) . "</pre>"; die;
$found = $class::showSelectionList( array( $record['filter'] ), array(), isset( $record['noAdd'] ) );
//print "<pre>[$found]</pre>"; die;
if ( $found )
$return .= "<div class='show_record'>\n<h3>$record[name]</h3>\n" . $found . '</div>';
}
if ( $save !== null ) {
$_REQUEST['to_find'] = $save;
}
return $return;
} // display
/**
* Function is basically a placeholder in case a extended class
* needs to do some additional processing when editing
*
* In some cases, the edit function can not handle additional fields.
* See the Device class, where device_type is a table with many-to-many
* linkages to device. Since this type of thing is very rare, I decided
* to just allow edit and post to call an additional function in
* those cases.
*
* Based on the action requested, will either return an HTML string
* which will be placed in the edit screen (for edit), or an array
* of SQL to be executed to update/add rows (for post).
*
* If the action is edit, there should be a <td></td> around the
* whole thing
*/
protected function editAdditionalFields() {
if ( $_REQUEST['action'] == 'edit' ) {
return '';
} elseif ($_REQUEST['action'] == 'post' ) {
return array();
}
}
/**
* Allow device_types to be edited also
*/
protected function oneToManyEdit( $key, $record ) {
global $dbConnection;
$id = $this->__get('id') === null ? 0 : $this->__get('id');
$query = $dbConnection->templateReplace (
sprintf(
"select
~~foreignTable~~.~~foreignColumn~~ id,
~~foreignTable~~.~~foreignDisplayColumn~~ name,
not isnull(~~linkageColumn~~) checked
from
~~foreignTable~~ ~~foreignTable~~
left outer join (
select
~~linkageColumn~~,
~~foreignColumn~~
from
~~linkageTable~~
where
~~linkageColumn~~ = %s
) current using ( ~~foreignColumn~~ )
order by ~~foreignDisplayColumn~~
", $id
),
$record
);
//print "<pre>$query</pre>"; die;
$data = $dbConnection->doSQL( $query );
$data = $data['returnData'];
// save current state in data
$this->data[$key] = array();
foreach ( $data as $row ) {
if ( count( $row ) > 1 )
$this->data[$key][$row['id']] = $row['checked'];
}
//print "<pre>" . print_r($this->data, true) . "</pre>"; die;
//print "<pre>" . print_r($query, true) . "</pre>"; die;
$html = $dbConnection->htmlCheckBoxes( array( 'data' => $data, 'arrayName' => $key ) );
//print "<pre>" . print_r($html, true) . "</pre>"; die;
return $html;
} // oneToManyEdit
protected function edit() {
global $dbConnection;
// save everything we have right now
//$this->beforeEdit = $this->data;
$return = array();
//print "<pre>In Edit\n" . print_r( $this->data, true ) . "</pre>"; die;
foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
//print "<pre>Processing $record[displayName]\n</pre>";
if ( isset( $record['display'] ) && $record['display'] === false ) // we don't do things which aren't supposed to be shown
continue;
switch ( $record['type'] ) {
case '1:1H':
//print "<pre>Doing 1:1H\n</pre>";
// get a list of all options
$list = $record['class']::getAll( array(), array( 'workingon' => true ));
//print "<pre> list is\n" . print_r( $list, true ) . "</pre>";
$selectedRow = isset( $this->data[$record['fieldname']] ) ? $this->data[$record['fieldname']] : null;
//print "<pre>Selected value is $selectedRow</pre>";
$select = $dbConnection->htmlSelect( array (
'data' => $list,
'name' => $record['foreignColumn'],
'nullok' => true,
'selected' => isset( $selectedRow ) ? $selectedRow : -1,
//'class' =>
)
);
$return[] = sprintf(
"<td>%s</td><td>%s</td>",
$record['displayName'],
$select
);
break;
case '1:M' :
//print "<pre>Doing 1:M\n</pre>";
$checkBoxes = $this->oneToManyEdit( $key, $record );
$return[] = "<td>$record[displayName]</td>\n<td>$checkBoxes</td>";
break;
default:
//print "<pre>Adding $record[displayName]\n</pre>";
if ( isset( $record['canEdit'] ) && $record['canEdit'] == false ) {
$return[] = sprintf(
"<td>%s</td><td>%s</td>",
$record['displayName'],
isset( $this->data[$record['fieldname']] ) ? $this->data[$record['fieldname']] : ''
);
} else {
$return[] = sprintf(
"<td>%s</td><td><input type='text' name='%s' value='%s'></td>",
$record['displayName'],
$record['fieldname'],
$this->data[$record['fieldname']]
);
} // if..else
} // switch
} // foreach
//$return[] = $this->editAdditionalFields();
//print "<pre>In Edit, return is\n" . print_r( $return, true ) . "</pre>";
$return[] = "<td colspan='2'><input type='submit' name='Save' value='Save'></td>";
$hiddens = sprintf( "<input type='hidden' name='module' value='%s'>\n", get_called_class() ) .
sprintf( "<input type='hidden' name='id' value='%s'>\n", isset( $this->data[static::$dbStructure['table']['primaryKey']] ) ? $this->data[static::$dbStructure['table']['primaryKey']] : 0 ) .
"<input type='hidden' name='action' value='post'>\n";
return "<div class='show_record'>\n<form><table class='show_record'>\n<tr>" . implode("</tr>\n<tr>", $return ) . "</tr>\n</table>\n$hiddens</form></div>";
} // edit
/**
* Adds new row in linkage table after marking old row as inactive
*
* Returns two queries which should be executed to update a linkage table
*
* The "History" part of this is that the old rows are not removed.
* Instead, they are marked as removed and this new row is added.
*
* This function assumes the table has two date columns, created and removed
* created should be default current_timestamp so we do not manually update
* it here.
*/
public function post1to1History( $linkageTable, $myColumn, $linkedToColumn, $newValue ) {
$queries = array();
if ( $newValue != -1 ) {
$queries[] = sprintf(
"update %s set removed = date(now()) where %s = %s and removed is null",
$linkageTable,
$myColumn,
$this->__get('id')
);
$queries[] = sprintf(
"insert into %s ( %s, %s ) values ( %s, %s )",
$linkageTable,
$myColumn,
$linkedToColumn,
$this->__get('id'),
$newValue
);
}
return $queries;
}
protected function oneToManyPost( $key, $record ) {
global $dbConnection;
$request = $_REQUEST[$key];
$queries = array();
foreach ( $this->data[$key] as $index => $checked ) {
if ( $checked && empty( $request[$index] ) ) { // we unchecked something
$queries[] = $dbConnection->templateReplace(
sprintf(
'delete from ~~linkageTable~~ where ~~linkageColumn~~ = %s and ~~foreignColumn~~ = %s',
$this->__get('id'),
$index
),
$record
);
} elseif ( ! $checked && isset( $request[$index] ) ) { // we checked something
$queries[] = $dbConnection->templateReplace(
sprintf(
'insert into ~~linkageTable~~ (~~linkageColumn~~, ~~foreignColumn~~ ) values (%s, %s)',
$this->__get('id'),
$index
),
$record
);
} // if..elseif
} // foreach
return $queries;
}
/**
* Posts the results of a previous form
*
* After a form is filled in, will search for any values which have
* changed. It will generate a separate SQL statement for each of them
* and execute the queries in in batch
*
* Once this is done, will reload the values from the database, so
* we immediately know if there was a problem.
*/
protected function post() {
global $dbConnection;
//print "<pre>Function Post\n" . print_r($_REQUEST, true) . '</pre>'; die;
// first, if this is a new record, just insert a blank one and get the ID.
// A little bit of overhead, but it allows us
if ( empty( $this->data[static::$dbStructure['table']['primaryKey']] ) ) {
// by default, we pre-populate some fields and that means they won't get updated, so init structure
foreach ( $this->data as $key => $record ) {
if ( ! is_array( $this->data[$key] ) && $this->data[$key] )
$this->data[$key] = '';
}
$insertQuery = $dbConnection->insertQuery(
static::$dbStructure['table']['tableName'],
array( static::$dbStructure['table']['selectionDisplay'] => 'Blank Record' ) );
$this->data[static::$dbStructure['table']['primaryKey']] = $dbConnection->insert( $insertQuery );
//print "<pre>\n" . print_r( $this->data , true ) . "</pre>"; die;
}
$queries = array();
$fields = array();
foreach ( static::$dbStructure['table']['fields'] as $key => $record ) {
if ( isset( $record['display'] ) && $record['display'] === false ) // we don't try to show links
continue;
if ( isset( $record['canEdit'] ) && ! $record['canEdit'] )
continue;
if ( $_REQUEST[$record['fieldname']] != $this->data[$record['fieldname']] ) { // they have changed a value
switch ( $record['type'] ) {
case '1:1H' :
$queries = array_merge( $queries,
$this->post1to1History(
$record['linkageTable'],
$record['linkageColumn'],
$record['foreignColumn'],
$_REQUEST[$record['fieldname']]
)
);
break;
case '1:M' :
$queries = array_merge( $queries, $this->oneToManyPost( $key, $record ) );
break;
default:
$fields[$record['fieldname']] = $_REQUEST[$record['fieldname']];
} // case
} // if data has changed
} // foreach
//print "<pre>Fields\n" . print_r( $this->data, true ) . "</pre>"; die;
if ( count( $fields ) ) {
$queries[] = $dbConnection->updateQuery(
static::$dbStructure['table']['tableName'],
array( static::$dbStructure['table']['primaryKey'] => $this->data[static::$dbStructure['table']['primaryKey']] ),
$fields );
} // if there are fields
/*
print "<pre>Request" . print_r( $_REQUEST, true ) . "</pre>";
print "<pre>Data" . print_r( $this->data, true ) . "</pre>";
print "<pre>Queries" . print_r( $queries, true ) . "</pre>"; die;
*/
$dbConnection->runSQLScript( $queries );
$this->loadFromDB( $this->data[static::$dbStructure['table']['primaryKey']] );
} // post
/**
* Simple controller. Will determine what action is going on, then
* call the correct method, returning the HTML required
*/
public function run() {
if ( isset( $_REQUEST['action'] ) ) {
switch ( $_REQUEST['action'] ) {
case 'add':
// prepopulate some fields with what we've been working on
$this->data = array();
foreach ( static::$dbStructure['table']['fields'] as $fieldname => $record ) {
if ( isset( $record['class'] ) && isset( $_SESSION['workingon'][$record['class']] ) ) {
$this->data[$record['fieldname']] = $_SESSION['workingon'][$record['class']];
} else {
$this->data[$fieldname] = '';
} // if..else
} // foreach
$this->data['id'] = 0;
//print '<pre>' . print_r( $this->data, true ) . '</pre>'; die;
// now, fall through and do the edit
case 'edit':
$return = $this->edit();
break;
case 'post':
$this->post();
// fall through and display the record
default:
$return = $this->display();
} // switch
} else {
$return = $this->display();
}
return $return;
}
} // abstract class Camp
?>