Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

cleanup, renamiing, documentation

  • Loading branch information...
commit 5bbde0cb7c6078633a595f63c018cb19ebb254b8 1 parent 63c921e
@evantahler authored
View
2  .gitignore
@@ -1,7 +1,7 @@
favicon.gif
favicon.ico
API/CONFIG.php
-API/DB/TABLES.php
+API/DB/SCHEMA.php
API/log/*
SPEC/log/*
SERVER/log/*
View
36 API/CACHE.php
@@ -37,44 +37,16 @@ function GetCache($Key)
elseif($CONFIG['CacheType'] == "DB")
{
+ // Look in DirectDBFunctions for this DB Driver
function SetCache($Key, $Value, $ThisCacheTime = null)
{
- global $CONFIG, $DBObj;
- if ($ThisCacheTime == null) { $ThisCacheTime = $CONFIG['CacheTime']; }
-
- $ExpireTime = time() + $ThisCacheTime;
-
- $Status = $DBObj->GetStatus();
- if ($Status === true)
- {
- $Connection = $DBObj->GetConnection();
- $SQL = 'INSERT INTO `'.$CONFIG['CacheTable'].'` (`Key`, `Value`, `ExpireTime`) VALUES ("'.mysql_real_escape_string($Key,$Connection).'", "'.mysql_real_escape_string(serialize($Value),$Connection).'", "'.mysql_real_escape_string($ExpireTime,$Connection).'");' ;
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
- if ($Status === true){return true;}
- else { return false; }
- }
- else { return false; }
+ return _DBSetCache($Key, $Value, $ThisCacheTime);
}
+ // Look in DirectDBFunctions for this DB Driver
function GetCache($Key)
{
- global $CONFIG, $DBObj;
-
- $Status = $DBObj->GetStatus();
- if ($Status === true)
- {
- $Connection = $DBObj->GetConnection();
- $SQL = 'SELECT `Value` FROM `'.$CONFIG['CacheTable'].'` WHERE (`Key` = "'.mysql_real_escape_string($Key,$Connection).'" AND `ExpireTime` >= "'.mysql_real_escape_string(time(),$Connection).'") LIMIT 1;' ;
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
- if ($Status === true){
- $Results = $DBObj->GetResults();
- return unserialize($Results[0]['Value']);
- }
- else { return false; }
- }
- else { return false; }
+ return _DBGetCache($Key);
}
}
View
18 API/CONFIG.php.example
@@ -12,7 +12,7 @@ RESERVERD VARIABLES THAT ARE SET BY THIS CONFIG FILE OR IN OTHER PARTS OF THE AP
- $POST_VARIABLES : Collection of names of variables the API should ingest
- $ACTIONS : Hash of API's Actions
- $ERROR : The globabl state variable (100 is the OK state)
-- $DBObj : The database connection object
+- $DBOBJ : The database connection object
- $OUTPUT : The array to be formatted and returned to the user
- $TABLES : The table description object
***********************************************/
@@ -27,8 +27,8 @@ unset($path);
// Set the ERROR. This is used by all steps to ensure that nothing has perviously gone awry, and allows the next step to excecute. All steps will first check to make sure that ERROR == 100.
$ERROR = 100;
-$CONFIG['systemTimeZone'] = "America/Los_Angeles";
-date_default_timezone_set($CONFIG['systemTimeZone']);
+$CONFIG['SystemTimeZone'] = "America/Los_Angeles";
+date_default_timezone_set($CONFIG['SystemTimeZone']);
$CONFIG['DefaultOutputType'] = "JSON" ; // XML, PHP, VAR, SOAP, LINE, CONSOLE, or JSON
$CONFIG['XML_ROOT_NODE'] = "XML"; // what is the root node of your XML output called?
$CONFIG['RequestLimitPerHour'] = 1000; // limit how many times a specific IP can use the API per hour. Set it to 0 to have no limit
@@ -58,17 +58,17 @@ $CONFIG['LogTable'] = "log";
/*********************************************************/
// database
-$CONFIG["DBType"] = "MYSQL";
+$CONFIG["DBType"] = "MYSQL"; // DB types require a 'driver' to be defined within DB/DRIVERS. Check the MYSQL folder for examples.
+$CONFIG['TableConfigFile'] = $CONFIG['App_dir']."DB/SCHEMA.php"; // The DB is periodically read and schema is written here for faster subsequent access
+$CONFIG['TableConfigRefreshTime'] = 60; // time in seconds for this application to re-poll mySQL for table layout information. 0 will never poll
+$CONFIG['DBLogFile'] = $CONFIG['LogFolder']."SQL.txt"; // comment me out for no logging of mySQL commands
$CONFIG['DB'] = "daveapi"; // the name of the database in use
+$CONFIG['LOG_DB'] = $CONFIG['DB']; // There can be a seperate DB in use for logging. The LogTable table is expected to be within this database.
$CONFIG['dbhost'] = "127.0.0.1";
$CONFIG['dbuser'] = "root";
$CONFIG['dbpass'] = "";
-$CONFIG['LOG_DB'] = $CONFIG['DB']; // There can be a seperate DB in use for logging. The LogTable table is expected to be within this database.
-
-$CONFIG['MySQLLogFile'] = $CONFIG['LogFolder']."SQL.txt"; // comment me out for no logging of mySQL commands
-
/*********************************************************/
// CRON
$CONFIG['CronLogFile'] = $CONFIG['LogFolder']."CRON_LOG.txt";
@@ -76,7 +76,7 @@ $CONFIG['MaxLogFileSize'] = 1048576 * 1; // 1MB
$CONFIG['LogsToCheck'] = array(); // log files that might get big that you want to automatically truncate
$CONFIG['LogsToCheck'][] = $CONFIG['CronLogFile'];
-$CONFIG['LogsToCheck'][] = $CONFIG['MySQLLogFile'];
+$CONFIG['LogsToCheck'][] = $CONFIG['DBLogFile'];
/*********************************************************/
// CACHE
View
2  API/CRON.php
@@ -13,7 +13,7 @@
$parts = explode("/",__FILE__);
$ThisFile = $parts[count($parts) - 1];
chdir(substr(__FILE__,0,(strlen(__FILE__) - strlen($ThisFile))));
-require_once("load_enviorment.php"); unset($parts); unset($ThisFile);
+require_once("LoadEnv.php"); unset($parts); unset($ThisFile);
load_tasks();
View
8 API/CheckAPIKey.php
@@ -20,12 +20,12 @@
if ($result === false)
{
$SQL = 'SELECT * FROM `developers` WHERE (`APIKey` = "'.$PARAMS["APIKey"].'") LIMIT 1;';
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
- if ($Status === true){ $Results = $DBObj->GetResults();}
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true){ $Results = $DBOBJ->GetResults();}
else{ $ERROR = $Status; }
}
else { $ERROR = $Status; }
View
17 API/CommonFunctions.php
@@ -53,6 +53,23 @@ function run_task($TaskName, $PARAMS = array())
return $TaskLog."\r\n";
}
+function reload_tables()
+{
+ global $ERROR, $DBOBJ, $CONFIG, $TABLES;
+
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true)
+ {
+ $TABLES = array();
+ @unlink($CONFIG['TableConfigFile']);
+ require($CONFIG['App_dir']."DB/DRIVERS/".$CONFIG["DBType"]."/TableConfig.php"); // requiring again will force a re-load
+ }
+ else
+ {
+ $ERROR = "DB Cannot be reached: ".$Status;
+ }
+}
+
function create_session()
{
$key = md5( uniqid() );
View
42 API/DB/DRIVERS/MYSQL/ConnectToDatabase.php
@@ -5,22 +5,42 @@
https://github.com/evantahler/PHP-DAVE-API
Evan Tahler | 2011
-I am the mySQL connection class
+I am the mySQL connection class. To create a simmilar class for other DB types, please note the functions that that DBConnection class should contain and thier implamentation:
-Here's an example:
+- __construct():
+ - Can be passsed an additional $DB than the default.
+ - Returns true on sucess
+ - Returns false on failure, logs error to $This->Status
+- mysql_log(): Will log "queries" to file
+- CheckForSpecialStrings(): Will inspect queries for special strings ($CONFIG['SpecialStrings']) and replace. This is to fix situations where user might post "0" as input, etc
+- query(): preforms the DB operation
+ - Returns true on sucess
+ - Returns false on failure, logs error to $This->Status
+- GetLastInsert(): returns the auto incramanet ID of the row added
+- NumRowsEffected(): returns a count of the rows effected by the "Edit" command
+- GetConnection(): returns the connction object if applicable
+- GetStatus(): returns the last status message
+- GetResults(): returns the result of the last query()
+- close(): closes the DB connection
- $DBObj = new DBConnection();
- $Status = $DBObj->GetStatus();
+//////////////
+
+Example useage:
+
+ $DBOBJ = new DBConnection();
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
- if ($Status === true){ $Results = $DBObj->GetResults();}
- // Do stuff with the $Results array
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true){
+ $Results = $DBOBJ->GetResults();
+ // Do stuff with the $Results array
+ }
else{ $ERROR = $Status; }
}
else { $ERROR = $Status; }
- $DBObj->close();
+ $DBOBJ->close();
use the GetLastInsert() function to get the deatils of an entry you just added.
@@ -66,9 +86,9 @@ private function mysql_log($line)
if ($host == ""){$host = "local_system";}
$line = date("Y-m-d H:i:s")." | ".$host." | ".$line;
- if (strlen($CONFIG['MySQLLogFile']) > 0)
+ if (strlen($CONFIG['DBLogFile']) > 0)
{
- $LogFileHandle = fopen($CONFIG['MySQLLogFile'], 'a');
+ $LogFileHandle = fopen($CONFIG['DBLogFile'], 'a');
if($LogFileHandle)
{
fwrite($LogFileHandle, ($line."\r\n"));
View
91 API/DB/DRIVERS/MYSQL/DAVE.php
@@ -8,11 +8,16 @@
I define the functions and classes to handle the general-case database actions of Delete, Add, View, and Edit (DAVE).
The 4 major functions will return an array. The first value is true or false indicating if the SQL action worked. The second object is either an array of results, or an error message.
+See additional notes below.
***********************************************/
+/*
+Table should be defned in $TABLES
+$VARS will be the params of the row to be added. If unspecified, $PARAMS is used by default)
+*/
function _ADD($Table, $VARS = null)
{
- Global $TABLES, $DBObj, $Connection, $PARAMS;
+ Global $TABLES, $DBOBJ, $Connection, $PARAMS;
if ($VARS == null){$VARS = $PARAMS;}
@@ -25,7 +30,7 @@ function _ADD($Table, $VARS = null)
$SQLKeys = array();
$SQLValues= array();
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status !== true)
{
return array(false,$Status);
@@ -46,10 +51,10 @@ function _ADD($Table, $VARS = null)
if (in_array($var, $UniqueVars) && strlen($val) > 0) // unique
{
$SQL = 'SELECT COUNT(1) FROM `'.$Table.'` WHERE (`'.$var.'` = "'.$val.'") ;';
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
if ($Status === true){
- $results = $DBObj->GetResults();
+ $results = $DBOBJ->GetResults();
if ($results[0]['COUNT(1)'] > 0)
{
return array(false,"There is already an entry of '".$val."' for ".$var);
@@ -91,11 +96,11 @@ function _ADD($Table, $VARS = null)
}
$SQL .= " ); ";
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $NewKey = $DBObj->GetLastInsert();
+ $NewKey = $DBOBJ->GetLastInsert();
return array(true,array( $TABLES[$Table]['META']['KEY'] => $NewKey));
}
else{return array(false,$Status); }
@@ -108,9 +113,13 @@ function _ADD($Table, $VARS = null)
/***********************************************/
+/*
+Table should be defned in $TABLES
+$VARS will be the params of the row to be added. VARS should include a key/value pair which includes the primary key for the DB. If unspecified, $PARAMS is used by default)
+*/
function _EDIT($Table, $VARS = null)
{
- Global $TABLES, $DBObj, $Connection, $PARAMS;
+ Global $TABLES, $DBOBJ, $Connection, $PARAMS;
if ($VARS == null){$VARS = $PARAMS;}
@@ -123,7 +132,7 @@ function _EDIT($Table, $VARS = null)
$SQLKeys = array();
$SQLValues= array();
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status !== true)
{
return array(false,$Status);
@@ -143,11 +152,11 @@ function _EDIT($Table, $VARS = null)
}
}
$SQL .= ' ) ;';
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $results = $DBObj->GetResults();
+ $results = $DBOBJ->GetResults();
if (count($results) == 1)
{
$VARS[$TABLES[$Table]['META']['KEY']] = $results[0][$TABLES[$Table]['META']['KEY']];
@@ -176,10 +185,10 @@ function _EDIT($Table, $VARS = null)
if (in_array($var, $UniqueVars) && strlen($val) > 0) // unique
{
$SQL = 'SELECT COUNT(1) FROM `'.$Table.'` WHERE (`'.$var.'` = "'.$val.'" AND `'.$TABLES[$Table]['META']['KEY'].'` != "'.$VARS[$TABLES[$Table]['META']['KEY']].'") ;';
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
if ($Status === true){
- $results = $DBObj->GetResults();
+ $results = $DBOBJ->GetResults();
if ($results[0]['COUNT(1)'] > 0)
{
return array(false,"There is already an entry of '".$val."' for ".$var);
@@ -216,11 +225,11 @@ function _EDIT($Table, $VARS = null)
}
$SQL .= ' WHERE ( `'.$TABLES[$Table]['META']['KEY'].'` = "'.$VARS[$TABLES[$Table]['META']['KEY']].'" ); ';
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $NewKey = $DBObj->GetLastInsert();
+ $NewKey = $DBOBJ->GetLastInsert();
return _VIEW($Table, $VARS); // do a view again to return fresh data
}
else{ return array(false,$Status); }
@@ -243,10 +252,22 @@ function _EDIT($Table, $VARS = null)
/***********************************************/
-//function _VIEW($Table, $select = null, $join = null, $where_additions = null, $sort = null, $SQL_Override = false)
+/*
+Table should be defned in $TABLES
+$VARS will be the params of the row to be added. VARS should include a key/value pair which includes either the primary key for the DB or one of the unique cols for the table. If unspecified, $PARAMS is used by default)
+Settins is an array that can contain:
+- $Settings["select"]: a replacement select statement (rather than "*"). Example: "FirstName as Name, Address as Addy". Only Name and Addy will be returned.
+- $Settings["join"]: Join statement (first "JOIN" is added automatically).
+- $Settings["where_additions"]: Specific where statement. Example: Birtday = "1984-08-27"
+- $Settings["sort"]: sort statment. Example: "Order by Date DESC"
+- $Settings["UpperLimit"]: used for LIMIT statement. Defaults to 100
+- $Settings["LowerLimit"]: used for LIMIT statement. Defaults to 0
+- $Settings["SQL_Override"]: normally, DAVE wants to only view a single row, and will error unless that row can be defined properly with unique values. set this true to bypass these checks, and view many rows at once
+
+*/
function _VIEW($Table, $VARS = null, $Settings = null )
{
- Global $TABLES, $DBObj, $Connection, $PARAMS;
+ Global $TABLES, $DBOBJ, $Connection, $PARAMS;
if ($VARS == null){$VARS = $PARAMS;}
// Additonal _VIEW Options and Configurations
@@ -327,12 +348,12 @@ function _VIEW($Table, $VARS = null, $Settings = null )
if ($UpperLimit == "") {$UpperLimit = 100; }
$SQL .= " LIMIT ".$LowerLimit.",".($UpperLimit - $LowerLimit)." ";
//
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
- if ($Status === true){ return array(true, $DBObj->GetResults()); }
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true){ return array(true, $DBOBJ->GetResults()); }
else{ return array(false,$Status); }
}
else { return array(false,$Status); }
@@ -345,9 +366,13 @@ function _VIEW($Table, $VARS = null, $Settings = null )
/***********************************************/
+/*
+Table should be defned in $TABLES
+$VARS will be the params of the row to be added. If unspecified, $PARAMS is used by default)
+*/
function _DELETE($Table, $VARS = null)
{
- Global $TABLES, $DBObj, $Connection, $PARAMS;
+ Global $TABLES, $DBOBJ, $Connection, $PARAMS;
if ($VARS == null){$VARS = $PARAMS;}
@@ -379,23 +404,23 @@ function _DELETE($Table, $VARS = null)
$SQL .= " ) ;"; // There is no limit to allow more than one removal
$SQL2 .= " ) ;";
//
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $DBObj->Query($SQL2);
- $Status = $DBObj->GetStatus();
+ $DBOBJ->Query($SQL2);
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $results = $DBObj->GetResults();
+ $results = $DBOBJ->GetResults();
if ($results[0]['COUNT(1)'] < 1)
{
- return array(false,"The item you are requesting to delete is not found");
+ return array(false,"More than one item matches these parameters. Only one row can be deleted at a time.");
}
}
else{ return array(false,"The item you are requesting to delete is not found"); }
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
if ($Status === true){ return array(true, true); }
else{ return array(false,$Status); }
}
View
198 API/DB/DRIVERS/MYSQL/DirectDBFunctions.php
@@ -5,37 +5,33 @@
Evan Tahler | 2011
There are certain required global functions for DAVE that are very related to the DB type you are using. Those are defined here. If they make no sense for your DB type, then return true. They still need to be defined.
+
+- GetAPIRequestsCount()
+- LogAPIRequest()
+- _DBSetCache()
+- _DBGetCache()
+- CreateDBSaveState()
+- RestoreDBSaveState()
+
***********************************************/
-function reload_tables()
-{
- global $ERROR, $DBObj, $CONFIG, $TABLES;
-
- $Status = $DBObj->GetStatus();
- if ($Status === true)
- {
- $TABLES = array();
- @unlink($CONFIG['TableConfigFile']);
- require($CONFIG['App_dir']."DB/DRIVERS/".$CONFIG["DBType"]."/TableConfig.php"); // requiring again will force a re-load
- }
- else
- {
- $ERROR = "DB Cannot be reached: ".$Status;
- }
-}
+/*
+I querey the LOG table within the database for a given $IP and lookup how many requests they have made so far within this timeframe
-function get_api_requests_count()
+$SQL = 'SELECT COUNT(*) as "total" FROM `'.$CONFIG['LOG_DB'].'`.`'.$CONFIG['LogTable'].'` WHERE (`IP` = "'.$IP.'" AND `TimeStamp` > "'.date('Y-m-d H:i:s',time()-(60*60)).'") ;';
+*/
+function GetAPIRequestsCount()
{
- global $IP, $CONFIG, $DBObj;
+ global $IP, $CONFIG, $DBOBJ;
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
$SQL = 'SELECT COUNT(*) as "total" FROM `'.$CONFIG['LOG_DB'].'`.`'.$CONFIG['LogTable'].'` WHERE (`IP` = "'.$IP.'" AND `TimeStamp` > "'.date('Y-m-d H:i:s',time()-(60*60)).'") ;';
- $DBObj->Query($SQL);
- $Status = $DBObj->GetStatus();
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
if ($Status === true){
- $Results = $DBObj->GetResults();
+ $Results = $DBOBJ->GetResults();
return (int)$Results[0]['total'];
}
else{ return $Status; }
@@ -43,24 +39,172 @@ function get_api_requests_count()
else { return $Status; }
}
-function log_api_request()
+/*
+I insert a record for an API requset for a given $IP, and log important information:
+- Action
+- APIKey
+- DeveloperID
+- ERROR
+- IP
+- Params (JSON or PHP-serailized hash)
+
+$SQL= 'INSERT INTO `'.$CONFIG['LOG_DB'].'`.`'.$CONFIG['LogTable'].'` (`Action`, `APIKey`, `DeveloperID`, `ERROR`, `IP`, `Params`) VALUES ("'.mysql_real_escape_string($PARAMS["Action"],$Connection).'", "'.mysql_real_escape_string($PARAMS["APIKey"],$Connection).'", "'.mysql_real_escape_string($PARAMS["DeveloperID"],$Connection).'", "'.mysql_real_escape_string($ERROR,$Connection).'", "'.mysql_real_escape_string($IP,$Connection).'" , "'.mysql_real_escape_string(json_encode($PARAMS),$Connection).'");';
+*/
+function LogAPIRequest()
{
- global $CONFIG, $PARAMS, $DBObj, $IP;
+ global $CONFIG, $PARAMS, $DBOBJ, $IP;
- $Connection = $DBObj->GetConnection();
+ $Connection = $DBOBJ->GetConnection();
if (count($CONFIG) > 0)
{
if (!(in_array($PARAMS["Action"],$CONFIG['NoLogActions'])) && !(in_array($PARAMS["APIKey"],$CONFIG['NoLogAPIKeys'])))
{
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
$SQL= 'INSERT INTO `'.$CONFIG['LOG_DB'].'`.`'.$CONFIG['LogTable'].'` (`Action`, `APIKey`, `DeveloperID`, `ERROR`, `IP`, `Params`) VALUES ("'.mysql_real_escape_string($PARAMS["Action"],$Connection).'", "'.mysql_real_escape_string($PARAMS["APIKey"],$Connection).'", "'.mysql_real_escape_string($PARAMS["DeveloperID"],$Connection).'", "'.mysql_real_escape_string($ERROR,$Connection).'", "'.mysql_real_escape_string($IP,$Connection).'" , "'.mysql_real_escape_string(json_encode($PARAMS),$Connection).'");';
- $a = $DBObj->Query($SQL);
+ $a = $DBOBJ->Query($SQL);
+ }
+ }
+ }
+}
+
+/*
+I am the DB-based method of storing CACHE objects. I will be used in definitions found in CACHE.php
+*/
+function _DBSetCache($Key, $Value, $ThisCacheTime = null)
+{
+ global $CONFIG, $DBOBJ;
+ if ($ThisCacheTime == null) { $ThisCacheTime = $CONFIG['CacheTime']; }
+
+ $ExpireTime = time() + $ThisCacheTime;
+
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true)
+ {
+ $Connection = $DBOBJ->GetConnection();
+ $SQL = 'INSERT INTO `'.$CONFIG['CacheTable'].'` (`Key`, `Value`, `ExpireTime`) VALUES ("'.mysql_real_escape_string($Key,$Connection).'", "'.mysql_real_escape_string(serialize($Value),$Connection).'", "'.mysql_real_escape_string($ExpireTime,$Connection).'");' ;
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true){return true;}
+ else { return false; }
+ }
+ else { return false; }
+}
+
+/*
+I am the DB-based method of getting back CACHE objects. I will be used in definitions found in CACHE.php
+*/
+function _DBGetCache($Key)
+{
+ global $CONFIG, $DBOBJ;
+
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true)
+ {
+ $Connection = $DBOBJ->GetConnection();
+ $SQL = 'SELECT `Value` FROM `'.$CONFIG['CacheTable'].'` WHERE (`Key` = "'.mysql_real_escape_string($Key,$Connection).'" AND `ExpireTime` >= "'.mysql_real_escape_string(time(),$Connection).'") LIMIT 1;' ;
+ $DBOBJ->Query($SQL);
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true){
+ $Results = $DBOBJ->GetResults();
+ return unserialize($Results[0]['Value']);
+ }
+ else { return false; }
+ }
+ else { return false; }
+}
+
+/*
+I create a restorable copy of the entire working database. This may be the creation of "backup" tables, a file-based dump of the database, etc. This backup will be restored with RestoreDBSveState. This backup should leave the current state of the data and schema (if applicable) available in the "normal" tables, as well as copy it to the backup. For mySQL, we create backup tables denoted with ~~ before the table name.
+*/
+function CreateDBSaveState($PARAMS = array())
+{
+ global $CONFIG, $TABLES, $DBOBJ;
+
+ reload_tables();
+
+ $output = array();
+ $TablesToSave = array();
+ if (strlen($PARAMS['table']) > 0)
+ {
+ $TablesToSave[] = $PARAMS['table'];
+ }
+ else
+ {
+ foreach($TABLES as $table => $data)
+ {
+ if (substr($table,0,2) != "~~")
+ {
+ $TablesToSave[] = $table;
}
}
}
+
+ foreach($TablesToSave as $table)
+ {
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true)
+ {
+ $output[] = "saving `".$table."` to `~~".$table."`";
+ $DBOBJ->Query("DROP TABLE IF EXISTS `~~".$table."`;");
+ $DBOBJ->Query("CREATE TABLE `~~".$table."` LIKE `".$table."`;");
+ $DBOBJ->Query("INSERT INTO `~~".$table."` SELECT * FROM `".$table."`;");
+ }
+ else
+ {
+ $output[] = "DB Error: ".$Status;
+ break;
+ }
+ }
+ return $output;
+}
+
+/*
+I restore a copy of the entire working database (creted with CreateDBSaveState). I will erase any modifications (D's,A's,V's, or E's) since the backup state was created. For mySQL, we look for any tables with the ~~ name indicating that they are a backup. We then drop the existing table, and rename the backup.
+*/
+function RestoreDBSveState($PARAMS = array())
+{
+ global $CONFIG, $TABLES, $DBOBJ;
+
+ reload_tables();
+
+ $output = array();
+ $TablesToRestore = array();
+ if (strlen($PARAMS['table']) > 0)
+ {
+ $TablesToRestore[] = "~~".$PARAMS['table'];
+ }
+ else
+ {
+ foreach($TABLES as $table => $data)
+ {
+ if (substr($table,0,2) == "~~")
+ {
+ $TablesToRestore[] = $table;
+ }
+ }
+ }
+
+ foreach($TablesToRestore as $table)
+ {
+ $Status = $DBOBJ->GetStatus();
+ if ($Status === true)
+ {
+ $output[] = "restoring `".$table."` to `".substr($table,2)."`";
+ $DBOBJ->Query("DROP TABLE IF EXISTS `".substr($table,2)."`;");
+ $DBOBJ->Query("CREATE TABLE `".substr($table,2)."` LIKE `".$table."`;");
+ $DBOBJ->Query("INSERT INTO `".substr($table,2)."` SELECT * FROM `".$table."`;");
+ $DBOBJ->Query("DROP TABLE `".$table."`;");
+ }
+ else
+ {
+ $output[] = "DB Error: ".$Status;
+ break;
+ }
+ }
+ return $output;
}
?>
View
12 API/DB/DRIVERS/MYSQL/TableConfig.php
@@ -5,7 +5,7 @@
https://github.com/evantahler/PHP-DAVE-API
Evan Tahler | 2011
-I inspect the state of your mySQL database and build the array descirbing all the colums and thier attributes. I will also log this to a file for quicked access next time. If /API/DB/TABLES.php doesn't exist, I'll create it for other parts of the API to use.
+I inspect the state of your mySQL database and build the array descirbing all the colums and thier attributes. I will also log this to a file for quicked access next time. If /API/DB/SCHEMA.php doesn't exist, I'll create it for other parts of the API to use.
***********************************************/
@@ -31,12 +31,12 @@
if ($ToReload)
{
$OUTPUT["TableRelaod"] = "true";
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
$SQL= 'SHOW TABLES;';
- $DBObj->Query($SQL);
- $out = $DBObj->GetResults();
+ $DBOBJ->Query($SQL);
+ $out = $DBOBJ->GetResults();
$TableList = array();
foreach ($out as $sub){
$name = $sub["Tables_in_".$CONFIG['DB']];
@@ -45,8 +45,8 @@
foreach ($TableList as $ThisTable)
{
$SQL= 'DESCRIBE `'.$CONFIG['DB'].'`.`'.$ThisTable.'`;';
- $DBObj->Query($SQL);
- $Response = $DBObj->GetResults();
+ $DBOBJ->Query($SQL);
+ $Response = $DBOBJ->GetResults();
foreach ($Response as $col)
{
if ($col['Key'] == "PRI")
View
12 API/DB/DRIVERS/MYSQL/init.php
@@ -13,20 +13,14 @@
// go no further if we don't know about databases
if (class_exists("DBConnection")) {
-
- /*********************************************************/
- // Table information
- $CONFIG['TableConfigFile'] = $CONFIG['App_dir']."DB/TABLES.php";
- $CONFIG['TableConfigRefreshTime'] = 60; // time in seconds for this application to re-poll mySQL for table layout information. 0 will never poll
- $DBObj = new DBConnection();
- $Status = $DBObj->GetStatus();
+ $DBOBJ = new DBConnection(); // keep this variable name
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $Connection = $DBObj->GetConnection();
+ $Connection = $DBOBJ->GetConnection();
require_once($_driver_db_path."TableConfig.php");
require_once($_driver_db_path."DAVE.php");
-
}
else
{
View
2  API/load_enviorment.php → API/LoadEnv.php
@@ -22,7 +22,7 @@
require_once("GetPostVars.php");
require_once("Actions.php");
- date_default_timezone_set($CONFIG['systemTimeZone']);
+ date_default_timezone_set($CONFIG['SystemTimeZone']);
}
else
{
View
2  API/TASKS.php
@@ -12,7 +12,7 @@
$parts = explode("/",__FILE__);
$ThisFile = $parts[count($parts) - 1];
chdir(substr(__FILE__,0,(strlen(__FILE__) - strlen($ThisFile))));
-require_once("load_enviorment.php"); unset($parts); unset($ThisFile);
+require_once("LoadEnv.php"); unset($parts); unset($ThisFile);
require_once("helper_functions/parseArgs.php");
View
8 API/Tasks/CleanCache.php
@@ -13,18 +13,18 @@ class CleanCache extends task
public function run($PARAMS = array())
{
- global $CONFIG, $DBObj;
+ global $CONFIG, $DBOBJ;
if (self::check_DBObj())
{
/////////////////////////////////////////////////////////////////////////
// Check the CACHE DB table for old entries, and remove them
$SQL= 'DELETE FROM `'.$CONFIG['DB'].'`.`'.$CONFIG['CacheTable'].'` WHERE (`ExpireTime` < "'.(time() - $CONFIG['CacheTime']).'") ;';
- $Status = $DBObj->GetStatus();
+ $Status = $DBOBJ->GetStatus();
if ($Status === true)
{
- $DBObj->Query($SQL);
- $this->task_log('Deleted '.$DBObj->NumRowsEffected()." entries from the CACHE DB");
+ $DBOBJ->Query($SQL);
+ $this->task_log('Deleted '.$DBOBJ->NumRowsEffected()." entries from the CACHE DB");
}
/////////////////////////////////////////////////////////////////////////
View
6 API/Tasks/CleanLog.php
@@ -13,13 +13,13 @@ class CleanLog extends task
public function run($PARAMS = array())
{
- global $CONFIG, $DBObj;
+ global $CONFIG, $DBOBJ;
if (self::check_DBObj())
{
$SQL= 'DELETE FROM `'.$CONFIG['LOG_DB'].'`.`'.$CONFIG['LogTable'].'` WHERE (`TimeStamp` < "'.date('Y-m-d H:i:s',(time() - $CONFIG['LogAge'])).'") ;';
- $DBObj->Query($SQL);
- $this->task_log('Deleted '.$DBObj->NumRowsEffected()." entries from the LOG Table in the ".$CONFIG['LOG_DB']." DB");
+ $DBOBJ->Query($SQL);
+ $this->task_log('Deleted '.$DBOBJ->NumRowsEffected()." entries from the LOG Table in the ".$CONFIG['LOG_DB']." DB");
}
}
}
View
6 API/Tasks/CleanSessions.php
@@ -13,13 +13,13 @@ class CleanSessions extends task
public function run($PARAMS = array())
{
- global $CONFIG, $DBObj;
+ global $CONFIG, $DBOBJ;
if (self::check_DBObj())
{
$SQL= 'DELETE FROM `SESSIONS` WHERE (`created_at` < "'.date('Y-m-d H:i:s',(time() - $CONFIG['SessionAge'])).'") ;';
- $DBObj->Query($SQL);
- $this->task_log('Deleted '.$DBObj->NumRowsEffected()." entries from the SESSIONS Table in the DB");
+ $DBOBJ->Query($SQL);
+ $this->task_log('Deleted '.$DBOBJ->NumRowsEffected()." entries from the SESSIONS Table in the DB");
}
}
}
View
38 API/Tasks/CreateDBSaveState.php
@@ -13,42 +13,8 @@ class CreateDBSaveState extends task
public function run($PARAMS = array())
{
- global $CONFIG, $TABLES, $DBObj;
-
- reload_tables();
-
- $TablesToSave = array();
- if (strlen($PARAMS['table']) > 0)
- {
- $TablesToSave[] = $PARAMS['table'];
- }
- else
- {
- foreach($TABLES as $table => $data)
- {
- if (substr($table,0,2) != "~~")
- {
- $TablesToSave[] = $table;
- }
- }
- }
-
- foreach($TablesToSave as $table)
- {
- $Status = $DBObj->GetStatus();
- if ($Status === true)
- {
- $this->task_log("saving `".$table."` to `~~".$table."`");
- $DBObj->Query("DROP TABLE IF EXISTS `~~".$table."`;");
- $DBObj->Query("CREATE TABLE `~~".$table."` LIKE `".$table."`;");
- $DBObj->Query("INSERT INTO `~~".$table."` SELECT * FROM `".$table."`;");
- }
- else
- {
- $this->task_log("DB Error: ".$Status);
- break;
- }
- }
+ $resp = CreateDBSaveState($PARAMS); // Defined by DB Driver
+ foreach($resp as $line){ $this->task_log($line); }
}
}
View
2  API/Tasks/RemoveLargeLogs.php
@@ -13,7 +13,7 @@ class RemoveLargeLogs extends task
public function run($PARAMS = array())
{
- global $CONFIG, $DBObj;
+ global $CONFIG, $DBOBJ;
clearstatcache();
$i = 0;
View
39 API/Tasks/RestoreDBSaveState.php
@@ -13,43 +13,8 @@ class RestoreDBSaveState extends task
public function run($PARAMS = array())
{
- global $CONFIG, $TABLES, $DBObj;
-
- reload_tables();
-
- $TablesToRestore = array();
- if (strlen($PARAMS['table']) > 0)
- {
- $TablesToRestore[] = "~~".$PARAMS['table'];
- }
- else
- {
- foreach($TABLES as $table => $data)
- {
- if (substr($table,0,2) == "~~")
- {
- $TablesToRestore[] = $table;
- }
- }
- }
-
- foreach($TablesToRestore as $table)
- {
- $Status = $DBObj->GetStatus();
- if ($Status === true)
- {
- $this->task_log("restoring `".$table."` to `".substr($table,2)."`");
- $DBObj->Query("DROP TABLE IF EXISTS `".substr($table,2)."`;");
- $DBObj->Query("CREATE TABLE `".substr($table,2)."` LIKE `".$table."`;");
- $DBObj->Query("INSERT INTO `".substr($table,2)."` SELECT * FROM `".$table."`;");
- $DBObj->Query("DROP TABLE `".$table."`;");
- }
- else
- {
- $this->task_log("DB Error: ".$Status);
- break;
- }
- }
+ $resp = RestoreDBSveState($PARAMS); // Defined by DB Driver
+ foreach($resp as $line){ $this->task_log($line); }
}
}
View
6 API/Tasks/TruncateTable.php
@@ -13,7 +13,7 @@ class TruncateTable extends task
public function run($PARAMS = array())
{
- global $CONFIG, $DBObj;
+ global $CONFIG, $DBOBJ;
$stop = false;
if (strlen($PARAMS['table']) == 0)
@@ -34,8 +34,8 @@ public function run($PARAMS = array())
if (self::check_DBObj() && $stop == false)
{
$SQL= 'TRUNCATE TABLE `'.$ThisDB.'`.`'.$PARAMS['table'].'`;';
- $DBObj->Query($SQL);
- if ($DBObj->NumRowsEffected() == 0)
+ $DBOBJ->Query($SQL);
+ if ($DBOBJ->NumRowsEffected() == 0)
{
$this->task_log($PARAMS['table']." table truncated from the ".$ThisDB." DB");
}
View
6 API/Tasks/_BASE.php
@@ -16,7 +16,7 @@ class CleanCache extends task
public function run($PARAMS = array())
{
- global $CONFIG, $DBObj;
+ global $CONFIG, $DBOBJ;
// PUT YOUR ACTION CODE HERE
@@ -66,8 +66,8 @@ public function get_task_log()
public function check_DBObj()
{
- global $DBObj;
- $Status = $DBObj->GetStatus();
+ global $DBOBJ;
+ $Status = $DBOBJ->GetStatus();
if (!($Status === true))
{
$this->task_log("DB Error: ".$Status);
View
24 API/index.php
@@ -16,7 +16,7 @@
$parts = explode("/",__FILE__);
$ThisFile = $parts[count($parts) - 1];
chdir(substr(__FILE__,0,(strlen(__FILE__) - strlen($ThisFile))));
-require_once("load_enviorment.php"); unset($parts); unset($ThisFile);
+require_once("LoadEnv.php"); unset($parts); unset($ThisFile);
// don't cache these API pages
if (!headers_sent()) { header("Cache-Control: no-cache, must-revalidate"); }
@@ -49,12 +49,12 @@
{
if ($CONFIG['CorrectLimitLockPass'] != $PARAMS["LimitLockPass"])
{
- $_api_requests_so_far = get_api_requests_count();
- if (!is_int($_api_requests_so_far)){ $ERROR = $_api_requests_so_far; exit;}
+ $_api_requests_so_far = GetAPIRequestsCount();
+ if (!is_int($_api_requests_so_far)){ $OUTPUT['ERROR'] = $_api_requests_so_far; require('Output.php'); exit;}
$OUTPUT['api_requests_remaining'] = $CONFIG['RequestLimitPerHour'] - $_api_requests_so_far;
if ($OUTPUT['api_requests_remaining'] <= 0)
{
- $DBObj->close();
+ $DBOBJ->close();
$OUTPUT['ERROR'] = "You have exceeded your allotted ".$CONFIG['RequestLimitPerHour']." requests this hour.";
require('Output.php');
exit;
@@ -65,11 +65,11 @@
// start transaction for connection if needed
if (isset($PARAMS['Rollback']))
{
- if ($PARAMS['Rollback'] == $CONFIG['RollbackPhrase'] && ($DBObj instanceof DBConnection) == true)
+ if ($PARAMS['Rollback'] == $CONFIG['RollbackPhrase'] && ($DBOBJ instanceof DBConnection) == true)
{
- if ($DBObj->GetStatus() == true)
+ if ($DBOBJ->GetStatus() == true)
{
- $DBObj->Query("START TRANSACTION;");
+ $DBOBJ->Query("START TRANSACTION;");
}
}
else
@@ -138,18 +138,18 @@
$OUTPUT['ServerAddress'] = $CONFIG['ServerAddress'];
// end transaction for connection if needed
-if ($PARAMS['Rollback'] == $CONFIG['RollbackPhrase'] && ($DBObj instanceof DBConnection) == true)
+if ($PARAMS['Rollback'] == $CONFIG['RollbackPhrase'] && ($DBOBJ instanceof DBConnection) == true)
{
- if ($DBObj->GetStatus() == true)
+ if ($DBOBJ->GetStatus() == true)
{
- $DBObj->Query("ROLLBACK;");
+ $DBOBJ->Query("ROLLBACK;");
$OUTPUT["Rollback"] = "true";
}
}
// output and cleanup
require('Output.php');
-log_api_request();
-@$DBObj->close();
+LogAPIRequest();
+@$DBOBJ->close();
?>
View
2  SERVER/SERVER.php
@@ -21,7 +21,7 @@
chdir($path); unset($path);
require("server_config.php");
-date_default_timezone_set($SERVER['systemTimeZone']);
+date_default_timezone_set($SERVER['SystemTimeZone']);
$verbose = false;
if ($ARGS["v"] || $ARGS["verbose"]) {$verbose = true;}
View
2  SERVER/server_config.php
@@ -15,7 +15,7 @@
$SERVER['domain'] = "localhost";
$SERVER['root_path'] = "../API/"; // from location of SERVER.php. Ensure that php user has permissions on this path.
$SERVER['PHP_Path'] = "/usr/bin/php";
-$SERVER['systemTimeZone'] = "America/Los_Angeles";
+$SERVER['SystemTimeZone'] = "America/Los_Angeles";
$SERVER['log_file'] = "log/SERVER_LOG.txt";
$SERVER['timeout'] = 10; //how long to wait (seconds) before returning to the client with a 500 error
View
2  SPEC/spec_helper.php
@@ -12,7 +12,7 @@
error_reporting (E_ALL ^ E_NOTICE);
chdir("../../API/");
-require_once("load_enviorment.php");
+require_once("LoadEnv.php");
require_once("helper_functions/colors.php");
if (!class_exists(DaveTest))
View
2  readme.markdown
@@ -82,7 +82,7 @@ You can get started on your local machine in 5 minutes! This tutorial is for Un
* `git clone git://github.com/evantahler/PHP-DAVE-API.git /path/where/you/want/it` OR just hit the `download` button above
* Rename `/API/CONFIG.example.php` to `/API/CONFIG.php`
* Configure CONFIG.php. Assuming we will be running mySQL locally as root with no password, all you should need to change is:
- * `$CONFIG['systemTimeZone']` (check http://www.php.net/manual/en/timezones.php for how to define your timezone)
+ * `$CONFIG['SystemTimeZone']` (check http://www.php.net/manual/en/timezones.php for how to define your timezone)
* `$CONFIG['App_dir']` (this is where the /API folder is)
* setup mySQL for DAVE
* create a mysql database called "daveapi"
Please sign in to comment.
Something went wrong with that request. Please try again.