Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Cleaning up directories and minor fixes. Reducing the number of reser…

…ved variables the API requires: - : To be set with all relevant, sanitized user input to the API

-  : Holds configuration options
-  : Collection of names of variables the API should ingest
-  : Hash of API's Actions
-  : The globabl state variable (100 is the OK state)
-  : The database connection object
-  : The array to be formatted and returned to the user
-  : The table description object
  • Loading branch information...
commit a06b625d951c7aec992fa2140bd2d73dff918ccc 1 parent 4f7db5a
Evan Tahler authored
Showing with 414 additions and 364 deletions.
  1. +6 −6 .gitignore
  2. 0  {PHP-DAVE-API → API}/.htaccess
  3. +18 −21 {PHP-DAVE-API → API}/AccessTools/APIRequest.php
  4. 0  {PHP-DAVE-API/helper_functions → API/AccessTools}/index.php
  5. +1 −1  {PHP-DAVE-API/Actions → API/Actions/examples}/CacheTest.php
  6. +2 −2 {PHP-DAVE-API/Actions → API/Actions/examples}/CookieTest.php
  7. 0  {PHP-DAVE-API/Actions → API/Actions/examples}/DescribeActions.php
  8. 0  {PHP-DAVE-API/Actions → API/Actions/examples}/DescribeTables.php
  9. +2 −2 {PHP-DAVE-API/Actions → API/Actions/examples}/Geocode.php
  10. 0  {PHP-DAVE-API/Actions → API/Actions/examples}/LogIn.php
  11. 0  {PHP-DAVE-API/Actions → API/Actions/examples}/ObjectTest.php
  12. +2 −9 {PHP-DAVE-API/Actions → API/Actions/examples}/SlowAction.php
  13. 0  {PHP-DAVE-API/Actions → API/Actions/examples}/UserAdd.php
  14. 0  {PHP-DAVE-API/Actions → API/Actions/examples}/UserDelete.php
  15. 0  {PHP-DAVE-API/Actions → API/Actions/examples}/UserEdit.php
  16. 0  {PHP-DAVE-API/Actions → API/Actions/examples}/UserView.php
  17. 0  {PHP-DAVE-API/MaxMind → API/Actions/examples}/index.php
  18. +20 −18 {PHP-DAVE-API → API}/CACHE.php
  19. +186 −0 API/CONFIG.php.example
  20. +17 −17 {PHP-DAVE-API → API}/CRON.php
  21. +2 −1  {PHP-DAVE-API → API}/CheckAPIKey.php
  22. +2 −2 {PHP-DAVE-API → API}/CommonFunctions.php
  23. +9 −10 {PHP-DAVE-API → API}/ConnectToDatabase.php
  24. +2 −2 {PHP-DAVE-API → API}/DAVE.php
  25. +8 −9 {PHP-DAVE-API → API}/DB/TableConfig.php
  26. 0  {PHP-DAVE-API → API}/DB/index.php
  27. 0  {PHP-DAVE-API → API}/GetPostVars.php
  28. 0  {PHP-DAVE-API → API}/MaxMind/COPYRIGHT.txt
  29. 0  {PHP-DAVE-API → API}/MaxMind/LICENSE.txt
  30. 0  {PHP-DAVE-API → API}/MaxMind/geoip.inc
  31. 0  {PHP-DAVE-API → API}/MaxMind/geoipcity.inc
  32. 0  {PHP-DAVE-API → API}/MaxMind/geoipregionvars.php
  33. 0  {PHP-DAVE-API/Actions → API/MaxMind}/index.php
  34. 0  {PHP-DAVE-API → API}/MaxMind/timezone.php
  35. 0  {PHP-DAVE-API → API}/MaxMind/timezone.txt
  36. 0  {PHP-DAVE-API → API}/Objects/User.php
  37. 0  {PHP-DAVE-API → API}/Objects/_BASE.php
  38. +5 −18 {PHP-DAVE-API → API}/Output.php
  39. +22 −0 API/WriteToLog.php
  40. 0  {PHP-DAVE-API → API}/config_cleaner.php
  41. 0  {PHP-DAVE-API → API}/crossdomain.xml
  42. 0  {PHP-DAVE-API → API}/helper_functions/AES.php
  43. 0  {PHP-DAVE-API → API}/helper_functions/CURL_POST.php
  44. 0  {PHP-DAVE-API → API}/helper_functions/CheckForBadWord.php
  45. 0  {PHP-DAVE-API → API}/helper_functions/GetGoFromIP.php
  46. 0  {PHP-DAVE-API → API}/helper_functions/ValidStateZip.php
  47. 0  {PHP-DAVE-API → API}/helper_functions/colors.php
  48. 0  {PHP-DAVE-API → API}/helper_functions/formatBytes.php
  49. 0  {PHP-DAVE-API → API}/helper_functions/http.php
  50. 0  {PHP-DAVE-API/AccessTools → API/helper_functions}/index.php
  51. 0  {PHP-DAVE-API → API}/helper_functions/microtime_float.php
  52. 0  {PHP-DAVE-API → API}/helper_functions/parseArgs.php
  53. 0  {PHP-DAVE-API → API}/helper_functions/secondsToWords.php
  54. +8 −9 {PHP-DAVE-API → API}/index.php
  55. 0  {PHP-DAVE-API → API}/static.html
  56. +0 −181 PHP-DAVE-API/CONFIG.php.example
  57. +0 −22 PHP-DAVE-API/WriteToLog.php
  58. +28 −14 {PHP-DAVE-API → SERVER}/SERVER.php
  59. +36 −5 {PHP-DAVE-API → SERVER}/script_runner.php
  60. +22 −0 SERVER/server_config.php
  61. 0  {PHP-DAVE-API/spec → SPEC}/TEST.php
  62. +1 −1  {PHP-DAVE-API/spec → SPEC}/actions/DescribeActions.php
  63. +9 −8 {PHP-DAVE-API/spec → SPEC}/spec_helper.php
  64. +3 −3 {PHP-DAVE-API/spec → SPEC}/system/general.php
  65. +3 −3 {PHP-DAVE-API/spec → SPEC}/system/output_types.php
12 .gitignore
View
@@ -1,8 +1,8 @@
favicon.gif
favicon.ico
-PHP-DAVE-API/CONFIG.php
-PHP-DAVE-API/CONFIG.php.backup
-PHP-DAVE-API/CONFIG.php.orig
-PHP-DAVE-API/DB/TABLES.php
-PHP-DAVE-API/MaxMind/GeoLiteCity.dat
-PHP-DAVE-API/LOG/*
+API/CONFIG.php
+API/DB/TABLES.php
+API/MaxMind/GeoLiteCity.dat
+API/LOG/*
+SPEC/LOG/*
+SERVER/LOG/*
0  PHP-DAVE-API/.htaccess → API/.htaccess
View
File renamed without changes
39 PHP-DAVE-API/AccessTools/APIRequest.php → API/AccessTools/APIRequest.php
View
@@ -7,29 +7,26 @@
I am an example class that can be used by another PHP application (perhaps the application that renders the consumer-facing website) to connect to the DAVE API
-***********************************************/
-
-// I am an example. Uncomment me to try me out
-/*
-$PostArray = array(
- "Action" => "A_DUMMY_ACTION",
- "OutputType" => "PHP"
-);
+EXAMPLE USE:
+ $PostArray = array(
+ "Action" => "A_DUMMY_ACTION",
+ "OutputType" => "PHP"
+ );
-$API_URL = "127.0.0.1/API/"; // local host
-$APIRequest = new APIRequest($IP, $API_URL, $PostArray);
-$APIDATA = $APIRequest->DoRequest();
-if ($APIDATA != false)
-{
- echo "Your request came from ".$APIDATA['IP']." and took ".$APIDATA['ComputationTime']." seconds.";
-}
-else
-{
- echo 'Something is wrong with your URL or DAVE API configuration';
-}
-echo "\r\n\r\n";
-*/
+ $API_URL = "127.0.0.1/API/"; // local host
+ $APIRequest = new APIRequest($IP, $API_URL, $PostArray);
+ $APIDATA = $APIRequest->DoRequest();
+ if ($APIDATA != false)
+ {
+ echo "Your request came from ".$APIDATA['IP']." and took ".$APIDATA['ComputationTime']." seconds.";
+ }
+ else
+ {
+ echo 'Something is wrong with your URL or DAVE API configuration';
+ }
+ echo "\r\n\r\n";
+***********************************************/
class APIRequest
{
protected $PostArray, $response, $API_URL;
0  PHP-DAVE-API/helper_functions/index.php → API/AccessTools/index.php
View
File renamed without changes
2  PHP-DAVE-API/Actions/CacheTest.php → API/Actions/examples/CacheTest.php
View
@@ -11,7 +11,7 @@
// I'll use HASH as the variable to log by IP address;
if ($ERROR == 100)
{
- if ($CacheType == "")
+ if ($CONFIG['CacheType'] == "")
{
$ERROR = "The cache is not configured on this server";
}
4 PHP-DAVE-API/Actions/CookieTest.php → API/Actions/examples/CookieTest.php
View
@@ -9,8 +9,8 @@
***********************************************/
$NewUpperLimit = rand();
$NewLowerLimit = rand();
-_setcookie("UpperLimit", $NewUpperLimit, time() + 60);
-_setcookie("LowerLimit", $NewLowerLimit, time() + 60);
+_setcookie("UpperLimit", $NewUpperLimit);
+_setcookie("LowerLimit", $NewLowerLimit);
$OUTPUT["COOKIE_TEST"]["OldUpperLimit"] = $PARAMS['UpperLimit'];
$OUTPUT["COOKIE_TEST"]["NewUpperLimit"] = $NewUpperLimit;
0  PHP-DAVE-API/Actions/DescribeActions.php → API/Actions/examples/DescribeActions.php
View
File renamed without changes
0  PHP-DAVE-API/Actions/DescribeTables.php → API/Actions/examples/DescribeTables.php
View
File renamed without changes
4 PHP-DAVE-API/Actions/Geocode.php → API/Actions/examples/Geocode.php
View
@@ -33,7 +33,7 @@
date_default_timezone_set($localTimeZone);
setlocale(LC_TIME, $country_code3);
$LocalTime = strftime("%T %F");
- date_default_timezone_set($systemTimeZone);
+ date_default_timezone_set($CONFIG['systemTimeZone']);
setlocale(LC_TIME, "C");
$SystemTime = strftime("%T %F");
@@ -47,7 +47,7 @@
$OUTPUT['city'] = $city;
$OUTPUT['localTimeZone'] = $localTimeZone;
$OUTPUT['LocalTime'] = $LocalTime;
- $OUTPUT['systemTimeZone'] = $systemTimeZone;
+ $OUTPUT['systemTimeZone'] = $CONFIG['systemTimeZone'];
$OUTPUT['SystemTime'] = $SystemTime;
}
else
0  PHP-DAVE-API/Actions/LogIn.php → API/Actions/examples/LogIn.php
View
File renamed without changes
0  PHP-DAVE-API/Actions/ObjectTest.php → API/Actions/examples/ObjectTest.php
View
File renamed without changes
11 PHP-DAVE-API/Actions/SlowAction.php → API/Actions/examples/SlowAction.php
View
@@ -5,16 +5,9 @@
https://github.com/evantahler/PHP-DAVE-API
Evan Tahler | 2011
-I am a slow action which can be used for profiling or parallelization testing. You can pass me UpperLimit in seconds to tell me how long to sleep for, or I'll use 10 sec as a default
+I am a slow action which can be used for profiling or parallelization testing. I will sleep for 10 seconds before returning.
***********************************************/
-
-if (!($PARAMS["UpperLimit"] > 0)){
- $sleep_time = 10;
-} else {
- $sleep_time = $PARAMS["UpperLimit"];
-}
-
-sleep($sleep_time);
+sleep(10);
$OUTPUT["SLEEP_TIME"] = $sleep_time;
0  PHP-DAVE-API/Actions/UserAdd.php → API/Actions/examples/UserAdd.php
View
File renamed without changes
0  PHP-DAVE-API/Actions/UserDelete.php → API/Actions/examples/UserDelete.php
View
File renamed without changes
0  PHP-DAVE-API/Actions/UserEdit.php → API/Actions/examples/UserEdit.php
View
File renamed without changes
0  PHP-DAVE-API/Actions/UserView.php → API/Actions/examples/UserView.php
View
File renamed without changes
0  PHP-DAVE-API/MaxMind/index.php → API/Actions/examples/index.php
View
File renamed without changes
38 PHP-DAVE-API/CACHE.php → API/CACHE.php
View
@@ -12,16 +12,16 @@
***********************************************/
-if($CacheType == "MemCache")
+if($CONFIG['CacheType'] == "MemCache")
{
// start memcache if memcache is on
$memcache = new Memcache;
- $memcache->connect('localhost', 11211);
+ $memcache->connect($CONFIG['MemCacheHost'], 11211);
function SetCache($Key, $Value, $ThisCacheTime = null)
{
- global $CacheTime;
- if ($ThisCacheTime == null) { $ThisCacheTime = $CacheTime; }
+ global $CONFIG;
+ if ($ThisCacheTime == null) { $ThisCacheTime = $CONFIG['CacheTime']; }
$memcache->set($Key, $Value, false, $ThisCacheTime);
}
@@ -35,19 +35,20 @@ function GetCache($Key)
/***********************************************/
-elseif($CacheType == "DB")
+elseif($CONFIG['CacheType'] == "DB")
{
function SetCache($Key, $Value, $ThisCacheTime = null)
{
- global $CacheTime, $CacheTable, $DBObj, $Connection;
- if ($ThisCacheTime == null) { $ThisCacheTime = $CacheTime; }
+ global $CONFIG, $DBObj;
+ if ($ThisCacheTime == null) { $ThisCacheTime = $CONFIG['CacheTime']; }
$ExpireTime = time() + $ThisCacheTime;
$Status = $DBObj->GetStatus();
if ($Status === true)
{
- $SQL = 'INSERT INTO `'.$CacheTable.'` (`Key`, `Value`, `ExpireTime`) VALUES ("'.mysql_real_escape_string($Key,$Connection).'", "'.mysql_real_escape_string(serialize($Value),$Connection).'", "'.mysql_real_escape_string($ExpireTime,$Connection).'");' ;
+ $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;}
@@ -58,12 +59,13 @@ function SetCache($Key, $Value, $ThisCacheTime = null)
function GetCache($Key)
{
- global $CacheTime, $CacheTable, $DBObj, $Connection;
+ global $CONFIG, $DBObj;
$Status = $DBObj->GetStatus();
if ($Status === true)
{
- $SQL = 'SELECT `Value` FROM `'.$CacheTable.'` WHERE (`Key` = "'.mysql_real_escape_string($Key,$Connection).'" AND `ExpireTime` >= "'.mysql_real_escape_string(time(),$Connection).'") LIMIT 1;' ;
+ $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){
@@ -78,15 +80,15 @@ function GetCache($Key)
/***********************************************/
-elseif($CacheType == "FlatFile")
+elseif($CONFIG['CacheType'] == "FlatFile")
{
function SetCache($Key, $Value, $ThisCacheTime = null)
{
- global $CacheTime, $CacheFolder;
- if ($ThisCacheTime == null) { $ThisCacheTime = $CacheTime; }
+ global $CONFIG;
+ if ($ThisCacheTime == null) { $ThisCacheTime = $CONFIG['CacheTime']; }
$COUNTAINER = array((time() + $ThisCacheTime),$Value);
- $TheFile = $CacheFolder.$Key.".cache";
+ $TheFile = $CONFIG['CacheFolder'].$Key.".cache";
$fh = fopen($TheFile, 'w') or die("can't open cache file for write");
fwrite($fh, serialize($COUNTAINER));
fclose($fh);
@@ -97,9 +99,9 @@ function SetCache($Key, $Value, $ThisCacheTime = null)
function GetCache($Key)
{
- global $CacheFolder;
+ global $CONFIG;
clearstatcache();
- $TheFile = $CacheFolder.$Key.".cache";
+ $TheFile = $CONFIG['CacheFolder'].$Key.".cache";
if (!file_exists($TheFile))
{
return false;
@@ -129,8 +131,8 @@ function GetCache($Key)
{
function SetCache($Key, $Value, $ThisCacheTime = null)
{
- global $CacheTime;
- if ($ThisCacheTime == null) { $ThisCacheTime = $CacheTime; }
+ global $CONFIG;
+ if ($ThisCacheTime == null) { $ThisCacheTime = $CONFIG['CacheTime']; }
return true;
}
186 API/CONFIG.php.example
View
@@ -0,0 +1,186 @@
+<?php
+/***********************************************
+DAVE PHP API
+https://github.com/evantahler/PHP-DAVE-API
+Evan Tahler | 2011
+
+I hold all the configuration variables for the API
+
+RESERVERD VARIABLES THAT ARE SET BY THIS CONFIG FILE OR IN OTHER PARTS OF THE APP INITILIZATION:
+- $PARAMS : To be set with all relevant, sanitized user input to the API
+- $CONFIG : Holds configuration options
+- $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
+- $OUTPUT : The array to be formatted and returned to the user
+- $TABLES : The table description object
+***********************************************/
+
+$CONFIG = array();
+
+// show errors on scrern
+ini_set("display_errors","1");
+error_reporting (E_ALL ^ E_NOTICE);
+
+// working directory
+$path = substr(__FILE__,0,(strlen(__FILE__) - strlen("CONFIG.php")));
+chdir($path);
+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['DefaultOutputType'] = "JSON" ; // XML, PHP, VAR, SOAP, 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
+$CONFIG['CorrectLimitLockPass'] = "Sekret"; // If a user provides the phrase as the param "LimitLockPass", even with a request limit per hour set above, they will not be limited on the requests that they can make.
+
+//define some things about this API node
+$CONFIG['ServerAddress'] = "127.0.0.1";
+$CONFIG['ServerName'] = "DAVE_API_SERVER";
+
+// mySQL database
+$CONFIG['DB'] = "daveapi"; // the name of the database in use
+$CONFIG['dbhost'] = "127.0.0.1";
+$CONFIG['dbuser'] = "root";
+$CONFIG['dbpass'] = "";
+$CONFIG['MySQLLogFile'] = "LOG/SQL.txt";
+
+/*********************************************************/
+// Files and Folders
+$CONFIG['PHP_Path'] = "/usr/bin/php"; // where is the PHP excecutable?
+$CONFIG['App_dir'] = "/var/www/html/API/"; // the location of this application
+
+/*********************************************************/
+// CRON
+@mkdir("LOG");
+$CONFIG['CronLogFile'] = "LOG/CRON_LOG.txt";
+$CONFIG['MaxLogFileSize'] = 1048576 * 1; // 1MB
+
+$CONFIG['LogsToCheck'] = array(); // log files that might get big that you want to automatically truncate
+$CONFIG['LogsToCheck'][] = $CONFIG['App_dir'].$CONFIG['CronLogFile'];
+$CONFIG['LogsToCheck'][] = $CONFIG['App_dir'].$CONFIG['MySQLLogFile'];
+
+/*********************************************************/
+// CACHE
+$CONFIG['CacheType'] = "DB"; // Options are "", "MemCache", "FlatFile", or "DB";
+$CONFIG['CacheTime'] = 10; // time to keep a cached value (in seconds)
+$CONFIG['CacheTable'] = "CACHE"; // if using the DB method
+$CONFIG['CacheFolder'] = "CACHE/"; // chmod 777, if using FlatFile mode
+$CONFIG['MemCacheHost'] = '127.0.0.1'; // The Server name or IP address of the memcache host, if CacheType = MemCache
+
+/*********************************************************/
+// Log
+$CONFIG['LogTable'] = "LOG";
+$CONFIG['LogAge'] = 60*60*24; // time to keep log entries in the DB (in seconds)
+// If you want to ignore certain Actions, list them here (For logging purposes)
+$CONFIG['NoLogActions'] = array();
+$CONFIG['NoLogActions'][] = "A_Blocked_Action";
+//If you want to ignore certain APIKeys, list them here (For logging purposes)
+$CONFIG['NoLogAPIKeys'] = array();
+$CONFIG['NoLogAPIKeys'][] = "A_Blocked_APIKey";
+
+/*********************************************************/
+// Sessions
+$CONFIG['SessionAge'] = 60*60*24; // how long to keep session information in the DB (in seconds)
+
+/*********************************************************/
+// Safe Mode: Use this to force the MD5 Checks to occur
+// md5($DeveloperID{secret}.$APIKey.$Rand).
+$CONFIG['SafeMode'] = true; //can be "true" or "false"
+
+/*********************************************************/
+// Special Strings
+// In order to ensure input is handled properly, this API required that you use the reserved (definable) special terms below to indicate you mean either an empty string "" or the numeral 0 with input. HTML GET and POST may treat these values as empty, so the special strings are required. GET, POST, or COOKIE INPUT OF "0" OR "" WILL BE IGNORED for this reason!
+// defined as array(TheTerm, ActualReplaceValue)
+
+$CONFIG['SpecialStrings'] = array();
+$CONFIG['SpecialStrings'][] = array('{clear}',"");
+$CONFIG['SpecialStrings'][] = array('{CLEAR}',"");
+$CONFIG['SpecialStrings'][] = array('%%CLEAR%%',"");
+$CONFIG['SpecialStrings'][] = array('%%clear%%',"");
+$CONFIG['SpecialStrings'][] = array('{zero}',"0");
+$CONFIG['SpecialStrings'][] = array('{ZERO}',"0");
+$CONFIG['SpecialStrings'][] = array('%%ZERO%%',"0");
+$CONFIG['SpecialStrings'][] = array('%%zero%%',"0");
+
+// go no further if we don't know about databases
+if (class_exists("DBConnection")) {
+
+ /*********************************************************/
+ // load object classes. Assumes each file in the /Objects directory contains object classes
+ require_once("Objects/_BASE.php");
+ foreach (glob("Objects/*.php") as $filename)
+ {
+ require_once($filename);
+ }
+
+ /*********************************************************/
+ // Table information
+ $CONFIG['TableConfigFile'] = "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();
+ if ($Status === true)
+ {
+ $Connection = $DBObj->GetConnection();
+ require("DB/TableConfig.php");
+ }
+ else
+ {
+ $ERROR = "DB Cannot be reached: ".$Status;
+ }
+
+ /*********************************************************/
+ // Actions, defined as "verb", then "page location", then "Public" or "Private" indicatiing if an APIKey is needed to access the function
+
+ $ACTIONS = array();
+
+ // default actions
+ $ACTIONS[] = array('DescribeActions', 'Actions/examples/DescribeActions.php', 'Public');
+ $ACTIONS[] = array('DescribeTables', 'Actions/examples/DescribeTables.php', 'Public');
+
+ // some basic actions
+ $ACTIONS[] = array('GeoCode', 'Actions/examples/Geocode.php', 'Public');
+ $ACTIONS[] = array('CacheTest', 'Actions/examples/CacheTest.php', 'Public');
+ $ACTIONS[] = array('ObjectTest', 'Actions/examples/ObjectTest.php', 'Public');
+
+ // Demo actions for building a user system
+ $ACTIONS[] = array('UserAdd', 'Actions/examples/UserAdd.php', 'Public');
+ $ACTIONS[] = array('UserView', 'Actions/examples/UserView.php', 'Public');
+ $ACTIONS[] = array('UserEdit', 'Actions/examples/UserEdit.php', 'Public');
+ $ACTIONS[] = array('UserDelete', 'Actions/examples/UserDelete.php', 'Public');
+ $ACTIONS[] = array('LogIn', 'Actions/examples/LogIn.php', 'Public');
+ $ACTIONS[] = array('CookieTest', 'Actions/examples/CookieTest.php', 'Public');
+ $ACTIONS[] = array('SlowAction', 'Actions/examples/SlowAction.php', 'Public');
+
+ /*********************************************************/
+
+ // Variables that might not be in the TABLLES. List any extra parameters your application might need
+ $POST_VARIABLES = array();
+
+ $POST_VARIABLES[] = "Action";
+ $POST_VARIABLES[] = "APIKey";
+ $POST_VARIABLES[] = "IP";
+ $POST_VARIABLES[] = "UpperLimit";
+ $POST_VARIABLES[] = "LowerLimit";
+ $POST_VARIABLES[] = "Date";
+ $POST_VARIABLES[] = "TimeStamp";
+ $POST_VARIABLES[] = "Rand";
+ $POST_VARIABLES[] = "Hash";
+ $POST_VARIABLES[] = "DeveloperID";
+ $POST_VARIABLES[] = "OutputType";
+ $POST_VARIABLES[] = "Callback";
+ $POST_VARIABLES[] = "LimitLockPass";
+ $POST_VARIABLES[] = "Password";
+
+ /*********************************************************/
+ require('config_cleaner.php');
+
+}
+
+?>
34 PHP-DAVE-API/CRON.php → API/CRON.php
View
@@ -17,7 +17,7 @@
require("DAVE.php");
require("CACHE.php");
require("CommonFunctions.php");
-date_default_timezone_set($systemTimeZone);
+date_default_timezone_set($CONFIG['systemTimeZone']);
$CRON_OUTPUT = "";
@@ -25,9 +25,9 @@
/////////////////////////////////////////////////////////////////////////
// Check the CACHE DB table for old entries, and remove them
-if($CacheType == "DB")
+if($CONFIG['CacheType'] == "DB")
{
- $SQL= 'DELETE FROM `'.$DB.'`.`'.$CacheTable.'` WHERE (`ExpireTime` < "'.(time() - $CacheTime).'") ;';
+ $SQL= 'DELETE FROM `'.$CONFIG['DB'].'`.`'.$CONFIG['CacheTable'].'` WHERE (`ExpireTime` < "'.(time() - $CONFIG['CacheTime']).'") ;';
$Status = $DBObj->GetStatus();
if ($Status === true)
{
@@ -37,14 +37,14 @@
}
/////////////////////////////////////////////////////////////////////////
// Check the CACHE Folder table for old entries, and remove them
-if($CacheType == "FlatFile")
+if($CONFIG['CacheType'] == "FlatFile")
{
- $files = scandir($CacheFolder);
+ $files = scandir($CONFIG['CacheFolder']);
$counter = 0;
foreach ($files as $num => $fname)
{
- $ThisFile = $CacheFolder.$fname;
- if (file_exists($ThisFile) && ((time() - filemtime($ThisFile)) > $CacheTime) && $fname != "." && $fname != ".." && $fname != ".svn")
+ $ThisFile = $CONFIG['CacheFolder'].$fname;
+ if (file_exists($ThisFile) && ((time() - filemtime($ThisFile)) > $CONFIG['CacheTime']) && $fname != "." && $fname != ".." && $fname != ".svn")
{
unlink($ThisFile);
$counter++;
@@ -54,21 +54,21 @@
}
/////////////////////////////////////////////////////////////////////////
-// Clear the LOG of old LOG entries, acording to $LogAge
+// Clear the LOG of old LOG entries, acording to $CONFIG['LogAge']
$Status = $DBObj->GetStatus();
if ($Status === true)
{
- $SQL= 'DELETE FROM `'.$LogTable.'` WHERE (`TimeStamp` < "'.date('Y-m-d H:i:s',(time() - $LogAge)).'") ;';
+ $SQL= 'DELETE FROM `'.$CONFIG['LogTable'].'` WHERE (`TimeStamp` < "'.date('Y-m-d H:i:s',(time() - $CONFIG['LogAge'])).'") ;';
$DBObj->Query($SQL);
$CRON_OUTPUT .= 'Deleted '.$DBObj->NumRowsEffected()." entries from the LOG. \r\n";
}
/////////////////////////////////////////////////////////////////////////
-// Clear the LOG of old LOG entries, acording to $SessionAge
+// Clear the LOG of old LOG entries, acording to $CONFIG['SessionAge']
$Status = $DBObj->GetStatus();
if ($Status === true)
{
- $SQL= 'DELETE FROM `SESSIONS` WHERE (`created_at` < "'.date('Y-m-d H:i:s',(time() - $SessionAge)).'") ;';
+ $SQL= 'DELETE FROM `SESSIONS` WHERE (`created_at` < "'.date('Y-m-d H:i:s',(time() - $CONFIG['SessionAge'])).'") ;';
$DBObj->Query($SQL);
$CRON_OUTPUT .= 'Deleted '.$DBObj->NumRowsEffected()." expired Sessions. \r\n";
}
@@ -77,13 +77,13 @@
// Delete Big Log Files, list set in CONFIG
clearstatcache();
$i = 0;
-while ($i < count($LogsToCheck))
+while ($i < count($CONFIG['LogsToCheck']))
{
- if (filesize($LogsToCheck[$i]) > $MaxLogFileSize)
+ if (filesize($CONFIG['LogsToCheck'][$i]) > $CONFIG['MaxLogFileSize'])
{
- $CRON_OUTPUT .= 'Log: '.$LogsToCheck[$i].'is too big, killing'."\r\n";
- unlink($LogsToCheck[$i]);
- $fh = fopen($LogsToCheck[$i], 'w');
+ $CRON_OUTPUT .= 'Log: '.$CONFIG['LogsToCheck'][$i].'is too big, killing'."\r\n";
+ unlink($CONFIG['LogsToCheck'][$i]);
+ $fh = fopen($CONFIG['LogsToCheck'][$i], 'w');
fclose($fh);
chmod($Logs[$i], 0777);
}
@@ -98,7 +98,7 @@
// End the log output
$CRON_OUTPUT .= "\r\n\r\n";
echo $CRON_OUTPUT;
-$fh = fopen($App_dir.$CronLogFile, 'a');
+$fh = fopen($CONFIG['App_dir'].$CONFIG['CronLogFile'], 'a');
fwrite($fh, $CRON_OUTPUT);
fclose($fh);
3  PHP-DAVE-API/CheckAPIKey.php → API/CheckAPIKey.php
View
@@ -1,3 +1,4 @@
+
<?php
/***********************************************
@@ -45,7 +46,7 @@
// Check that the sequrity HASH worked out
// the hash should be md5($DeveloperID{secret}.$APIKey.$Rand), IN THIS ORDER!!!!
-if ($SafeMode == true)
+if ($CONFIG['SafeMode'] == true)
{
if ($ERROR == 100)
{
4 PHP-DAVE-API/CommonFunctions.php → API/CommonFunctions.php
View
@@ -25,13 +25,13 @@ function humanize_actions()
function reload_tables()
{
- global $ERROR, $DBObj, $TableConfigFile, $TABLES;
+ global $ERROR, $DBObj, $CONFIG, $TABLES;
$Status = $DBObj->GetStatus();
if ($Status === true)
{
$TABLES = array();
- @unlik($TableConfigFile);
+ @unlik($CONFIG['TableConfigFile']);
require("DB/TableConfig.php");
}
else
19 PHP-DAVE-API/ConnectToDatabase.php → API/ConnectToDatabase.php
View
@@ -32,13 +32,12 @@ class DBConnection
public function __construct($OtherDB = "")
{
- global $dbhost, $dbuser, $dbpass, $DB, $MySQLLogFile;
+ global $CONFIG;
$this->Status = true;
if ($OtherDB != "") { $this->DataBase = $OtherDB ; }
- else { $this->DataBase = $DB; }
-
- $this->Connection = @mysql_connect($dbhost, $dbuser, $dbpass);
+ else { $this->DataBase = $CONFIG['DB']; }
+ $this->Connection = mysql_connect($CONFIG['dbhost'], $CONFIG['dbuser'], $CONFIG['dbpass']);
if(!empty($this->Connection))
{
$DatabaseSelected=mysql_select_db($this->DataBase);
@@ -54,22 +53,22 @@ public function __construct($OtherDB = "")
}
else
{
- $this->Status = "Connection Error (mySQL) | Connection or Access permission error";
+ $this->Status = "Connection Error (mySQL) | Connection Access or permission error";
return false;
}
}
private function mysql_log($line)
{
- global $IP, $MySQLLogFile;
+ global $IP, $CONFIG;
$host = $IP;
if ($host == ""){$host = "local_system";}
$line = date("Y-m-d H:i:s")." | ".$host." | ".$line;
- if (strlen($MySQLLogFile) > 0)
+ if (strlen($CONFIG['MySQLLogFile']) > 0)
{
- $LogFileHandle = fopen($MySQLLogFile, 'a');
+ $LogFileHandle = fopen($CONFIG['MySQLLogFile'], 'a');
if($LogFileHandle)
{
fwrite($LogFileHandle, ($line."\r\n"));
@@ -80,8 +79,8 @@ private function mysql_log($line)
private function CheckForSpecialStrings($string)
{
- global $SpecialStrings;
- foreach ($SpecialStrings as $term)
+ global $CONFIG;
+ foreach ($CONFIG['SpecialStrings'] as $term)
{
$string = str_replace($term[0],$term[1],$string);
}
4 PHP-DAVE-API/DAVE.php → API/DAVE.php
View
@@ -474,9 +474,9 @@ function _getUniqueTableVars($Table)
function _isSpecialString($string)
{
- global $SpecialStrings;
+ global $CONFIG;
$found = false;
- foreach ($SpecialStrings as $term)
+ foreach ($CONFIG['SpecialStrings'] as $term)
{
if (stristr($string,$term[0]) !== false)
{
17 PHP-DAVE-API/DB/TableConfig.php → API/DB/TableConfig.php
View
@@ -13,15 +13,15 @@
$TABLES = array();
$ToReload = false;
-if (!file_exists($TableConfigFile)) {
+if (!file_exists($CONFIG['TableConfigFile'])) {
$ToReload = true;
}
else
{
- require_once($TableConfigFile);
- if ($TableConfigRefreshTime > 0)
+ require_once($CONFIG['TableConfigFile']);
+ if ($CONFIG['TableConfigRefreshTime'] > 0)
{
- if ($TableBuildTime + $TableConfigRefreshTime < time()) {
+ if ($TableBuildTime + $CONFIG['TableConfigRefreshTime'] < time()) {
$ToReload = true;
$TABLES = array(); // clear it, just to be safe
}
@@ -31,7 +31,6 @@
if ($ToReload)
{
$OUTPUT["TableRelaod"] = "true";
- $DBObj = new DBConnection();
$Status = $DBObj->GetStatus();
if ($Status === true)
{
@@ -40,7 +39,7 @@
$out = $DBObj->GetResults();
$TableList = array();
foreach ($out as $sub){
- $name = $sub["Tables_in_".$DB];
+ $name = $sub["Tables_in_".$CONFIG['DB']];
if ($name != "CACHE" && $name != "LOG") { $TableList[] = $name; }
}
foreach ($TableList as $ThisTable)
@@ -63,7 +62,7 @@
}
}
$TABLES["TableBuildTime"] = time();
- @unlink($TableConfigFile);
+ @unlink($CONFIG['TableConfigFile']);
$TableStringOutput = "";
$TableStringOutput .= "<?php \r\n";
$TableStringOutput .= "// TABLE DESCRIPTION GENERATED AT ".date("Y-m-d H:i:s")."\r\n";
@@ -91,10 +90,10 @@
$TableStringOutput .= "// END \r\n";
$TableStringOutput .= "?>";
- $fh = fopen($TableConfigFile, 'w');
+ $fh = fopen($CONFIG['TableConfigFile'], 'w');
fwrite($fh, $TableStringOutput);
fclose($fh);
- chmod($TableConfigFile,0777);
+ chmod($CONFIG['TableConfigFile'],0777);
}
else
{
0  PHP-DAVE-API/DB/index.php → API/DB/index.php
View
File renamed without changes
0  PHP-DAVE-API/GetPostVars.php → API/GetPostVars.php
View
File renamed without changes
0  PHP-DAVE-API/MaxMind/COPYRIGHT.txt → API/MaxMind/COPYRIGHT.txt
View
File renamed without changes
0  PHP-DAVE-API/MaxMind/LICENSE.txt → API/MaxMind/LICENSE.txt
View
File renamed without changes
0  PHP-DAVE-API/MaxMind/geoip.inc → API/MaxMind/geoip.inc
View
File renamed without changes
0  PHP-DAVE-API/MaxMind/geoipcity.inc → API/MaxMind/geoipcity.inc
View
File renamed without changes
0  PHP-DAVE-API/MaxMind/geoipregionvars.php → API/MaxMind/geoipregionvars.php
View
File renamed without changes
0  PHP-DAVE-API/Actions/index.php → API/MaxMind/index.php
View
File renamed without changes
0  PHP-DAVE-API/MaxMind/timezone.php → API/MaxMind/timezone.php
View
File renamed without changes
0  PHP-DAVE-API/MaxMind/timezone.txt → API/MaxMind/timezone.txt
View
File renamed without changes
0  PHP-DAVE-API/Objects/User.php → API/Objects/User.php
View
File renamed without changes
0  PHP-DAVE-API/Objects/_BASE.php → API/Objects/_BASE.php
View
File renamed without changes
23 PHP-DAVE-API/Output.php → API/Output.php
View
@@ -1,16 +1,15 @@
<?php
-
/***********************************************
DAVE PHP API
https://github.com/evantahler/PHP-DAVE-API
Evan Tahler | 2011
I handle formatting the $OUTPUT object into XML, JSON, etc
-
***********************************************/
+
if ($PARAMS["OutputType"] == "")
{
- $PARAMS["OutputType"] = $DefaultOutputType;
+ $PARAMS["OutputType"] = $CONFIG['DefaultOutputType'];
}
if ($PARAMS["OutputType"] == "VAR")
@@ -66,9 +65,9 @@ function _DepthArrayPrint($Array,$depth,$container=null)
}
//
echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
- echo '<'.$XML_ROOT_NODE.'>'."\r\n";
+ echo '<'.$CONFIG['XML_ROOT_NODE'].'>'."\r\n";
_DepthArrayPrint($OUTPUT,1);
- echo '</'.$XML_ROOT_NODE.'>'."\r\n";
+ echo '</'.$CONFIG['XML_ROOT_NODE'].'>'."\r\n";
}
elseif ($PARAMS["OutputType"] == "JSON")
@@ -84,21 +83,9 @@ function _DepthArrayPrint($Array,$depth,$container=null)
}
}
-elseif ($PARAMS["OutputType"] == "SOAP")
-{
- // coming soon
- echo "SOAP support coming soon";
-
- //$server = new SoapServer("tmp.wsdl");
- //ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache
- //$server->addFunction($Action);
- //$server->handle();
-
-}
-
else
{
- echo 'I am sorry, but I do not regonize that OutputType. Leave that parameter blank for the default option.';
+ echo 'I am sorry, but I do not know that OutputType. Leave OutputType blank for the default option.';
}
flush();
22 API/WriteToLog.php
View
@@ -0,0 +1,22 @@
+<?php
+
+/***********************************************
+DAVE PHP API
+https://github.com/evantahler/PHP-DAVE-API
+Evan Tahler | 2011
+
+Even when an action fails, we should log that it happened. This is importnat to bloc IPs that access the IP too much, etc. This page should not use the safety string or do error checks, because we want it to always happen even if there is an error.
+
+***********************************************/
+
+if (!(in_array($PARAMS["Action"],$CONFIG['NoLogActions'])) && !(in_array($PARAMS["APIKey"],$CONFIG['NoLogAPIKeys'])))
+{
+ $Status = $DBObj->GetStatus();
+ if ($Status === true)
+ {
+ $SQL= 'INSERT INTO `'.$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).'");';
+ $DBObj->Query($SQL);
+ }
+}
+
+?>
0  PHP-DAVE-API/config_cleaner.php → API/config_cleaner.php
View
File renamed without changes
0  PHP-DAVE-API/crossdomain.xml → API/crossdomain.xml
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/AES.php → API/helper_functions/AES.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/CURL_POST.php → API/helper_functions/CURL_POST.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/CheckForBadWord.php → API/helper_functions/CheckForBadWord.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/GetGoFromIP.php → API/helper_functions/GetGoFromIP.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/ValidStateZip.php → API/helper_functions/ValidStateZip.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/colors.php → API/helper_functions/colors.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/formatBytes.php → API/helper_functions/formatBytes.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/http.php → API/helper_functions/http.php
View
File renamed without changes
0  PHP-DAVE-API/AccessTools/index.php → API/helper_functions/index.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/microtime_float.php → API/helper_functions/microtime_float.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/parseArgs.php → API/helper_functions/parseArgs.php
View
File renamed without changes
0  PHP-DAVE-API/helper_functions/secondsToWords.php → API/helper_functions/secondsToWords.php
View
File renamed without changes
17 PHP-DAVE-API/index.php → API/index.php
View
@@ -27,7 +27,6 @@
require("CACHE.php");
require("CommonFunctions.php");
require("GetPostVars.php");
-date_default_timezone_set($systemTimeZone);
// Get IP (if not provided)
if (empty($IP) || $IP == "")
@@ -45,28 +44,28 @@
}
// check if this user has made too many requests this hour
-if ($RequestLimitPerHour > 0)
+if ($CONFIG['RequestLimitPerHour'] > 0)
{
- if ($CorrectLimitLockPass != $PARAMS["LimitLockPass"])
+ if ($CONFIG['CorrectLimitLockPass'] != $PARAMS["LimitLockPass"])
{
$Status = $DBObj->GetStatus();
if ($Status === true)
{
- $SQL = 'SELECT COUNT(*) as "total" FROM `'.$LogTable.'` WHERE (`IP` = "'.$IP.'" AND `TimeStamp` > "'.date('Y-m-d H:i:s',time()-(60*60)).'") ;';
+ $SQL = 'SELECT COUNT(*) as "total" FROM `'.$CONFIG['LogTable'].'` WHERE (`IP` = "'.$IP.'" AND `TimeStamp` > "'.date('Y-m-d H:i:s',time()-(60*60)).'") ;';
$DBObj->Query($SQL);
$Status = $DBObj->GetStatus();
if ($Status === true){
$Results = $DBObj->GetResults();
- if ($Results[0]['total'] > $RequestLimitPerHour)
+ if ($Results[0]['total'] > $CONFIG['RequestLimitPerHour'])
{
$DBObj->close();
- $OUTPUT['ERROR'] = "You have exceeded your allotted ".$RequestLimitPerHour." requests this hour.";
+ $OUTPUT['ERROR'] = "You have exceeded your allotted ".$CONFIG['RequestLimitPerHour']." requests this hour.";
require('Output.php');
exit;
}
else
{
- $OUTPUT['api_requests_remaining'] = $RequestLimitPerHour - $Results[0]['total'];
+ $OUTPUT['api_requests_remaining'] = $CONFIG['RequestLimitPerHour'] - $Results[0]['total'];
}
}
else{ $ERROR = $Status; }
@@ -130,8 +129,8 @@
$OUTPUT['ComputationTime'] = $ComputationElapsedTime;
$OUTPUT['IP'] = $IP;
$OUTPUT['ERROR'] = $ERROR;
-$OUTPUT['ServerName'] = $ServerName;
-$OUTPUT['ServerAddress'] = $ServerAddress;
+$OUTPUT['ServerName'] = $CONFIG['ServerName'];
+$OUTPUT['ServerAddress'] = $CONFIG['ServerAddress'];
// output
require('Output.php');
0  PHP-DAVE-API/static.html → API/static.html
View
File renamed without changes
181 PHP-DAVE-API/CONFIG.php.example
View
@@ -1,181 +0,0 @@
-<?php
-
-/***********************************************
-DAVE PHP API
-https://github.com/evantahler/PHP-DAVE-API
-Evan Tahler | 2011
-
-I hold all the configuration variables for the API
-***********************************************/
-
-// show errors on scrern
-ini_set("display_errors","1");
-error_reporting (E_ALL ^ E_NOTICE);
-
-// SERVER (set me for but the API and SERVER (even if you don't need SERVER))
-$SERVER = array();
-$SERVER['public_port'] = 3000;
-$SERVER['internal_port'] = 3001;
-$SERVER['poll_timeout'] = 10000; // in micro-seconds. If you set me too large, your servers will have slow resposne time, Setting me too fast will burn CPU.
-$SERVER['log_file'] = "LOG/SERVER_LOG.txt";
-$SERVER['max_clients'] = 100;
-$SERVER['domain'] = "localhost";
-
-// working directory
-$path = substr(__FILE__,0,(strlen(__FILE__) - strlen("CONFIG.php")));
-chdir($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;
-$systemTimeZone = "America/Los_Angeles";
-$DefaultOutputType = "JSON" ; // XML, PHP, VAR, SOAP, or JSON
-$XML_ROOT_NODE = "XML"; // what is the root node of your XML output called?
-$RequestLimitPerHour = 1000; // limit how many times a specific IP can use the API per hour. Set it to 0 to have no limit
-$CorrectLimitLockPass = "Sekret"; // If a user provides the phrase as the param "LimitLockPass", even with a request limit per hour set above, they will not be limited on the requests that they can make.
-
-//define some things about this API node
-$ServerAddress = $_SERVER["SERVER_ADDR"];
-$ServerName = $_SERVER["SERVER_NAME"];
-
-// mySQL database
-$DB = "daveapi"; // the name of the database in use
-$dbhost = "localhost";
-$dbuser = "root";
-$dbpass = "";
-
-/*********************************************************/
-// Files and Folders
-$PHP_Path = "/usr/bin/php"; // where is the PHP excecutable?
-$App_dir = "/var/www/html/API/"; // the location of this application
-
-/*********************************************************/
-// CRON
-@mkdir("LOG");
-$CronLogFile = "LOG/CRON_LOG.txt";
-$MySQLLogFile = "LOG/SQL.txt";
-$MaxLogFileSize = 1048576 * 1; // 1MB
-
-$LogsToCheck = array(); // log files that might get big that you want to automatically truncate
-$LogsToCheck[] = $App_dir.$CronLogFile;
-$LogsToCheck[] = $App_dir.$MySQLLogFile;
-
-/*********************************************************/
-// CACHE
-$CacheType = "DB"; // Options are "", "MemCache", "FlatFile", or "DB";
-$CacheTime = 10; // time to keep a cached value (in seconds)
-$CacheTable = "CACHE"; // if using the DB method
-$CacheFolder = "CACHE/"; // chmod 777, if using FlatFile mode
-$MemCacheHost = 'localhost'; // The Server name or IP address of the memcache host, if CacheType = MemCache
-
-/*********************************************************/
-// Log
-$LogTable = "LOG";
-$LogAge = 60*60*24; // time to keep log entries in the DB (in seconds)
-// If you want to ignore certain Actions, list them here (For logging purposes)
-$NoLogActions = array();
-$NoLogActions[] = "A_Blocked_Action";
-//If you want to ignore certain APIKeys, list them here (For logging purposes)
-$NoLogAPIKeys = array();
-$NoLogActions[] = "A_Blocked_APIKey";
-
-/*********************************************************/
-// Sessions
-$SessionAge = 60*60*24; // how long to keep session information in the DB (in seconds)
-
-/*********************************************************/
-// Safe Mode: Use this to force the MD5 Checks to occur
-// md5($DeveloperID{secret}.$APIKey.$Rand).
-$SafeMode = true; //can be "true" or "false"
-
-/*********************************************************/
-// Special Strings
-// In order to ensure input is handled properly, this API required that you use the reserved (definable) special terms below to indicate you mean either an empty string "" or the numeral 0 with input. HTML GET and POST may treat these values as empty, so the special strings are required. GET, POST, or COOKIE INPUT OF "0" OR "" WILL BE IGNORED for this reason!
-// defined as array(TheTerm, ActualReplaceValue)
-
-$SpecialStrings = array();
-$SpecialStrings[] = array('{clear}',"");
-$SpecialStrings[] = array('{CLEAR}',"");
-$SpecialStrings[] = array('%%CLEAR%%',"");
-$SpecialStrings[] = array('%%clear%%',"");
-$SpecialStrings[] = array('{zero}',"0");
-$SpecialStrings[] = array('{ZERO}',"0");
-$SpecialStrings[] = array('%%ZERO%%',"0");
-$SpecialStrings[] = array('%%zero%%',"0");
-
-// go no further if we don't know about databases
-if (class_exists("DBConnection")) {
-
- /*********************************************************/
- // load object classes. Assumes each file in the /Objects directory contains object classes
- require_once("Objects/_BASE.php");
- foreach (glob("Objects/*.php") as $filename)
- {
- require_once($filename);
- }
-
- /*********************************************************/
- // Table information
- $TableConfigFile = "DB/TABLES.php";
- $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();
- if ($Status === true)
- {
- $Connection = $DBObj->GetConnection();
- require("DB/TableConfig.php");
- }
- else
- {
- $ERROR = "DB Cannot be reached: ".$Status;
- }
-
- /*********************************************************/
- // Actions, defined as "verb", then "page location", then "Public" or "Private" indicatiing if an APIKey is needed to access the function
-
- $ACTIONS = array();
-
- // default actions
- $ACTIONS[] = array('DescribeActions', 'Actions/DescribeActions.php', 'Public');
- $ACTIONS[] = array('DescribeTables', 'Actions/DescribeTables.php', 'Public');
-
- // some basic actions
- $ACTIONS[] = array('GeoCode', 'Actions/Geocode.php', 'Public');
- $ACTIONS[] = array('CacheTest', 'Actions/CacheTest.php', 'Public');
- $ACTIONS[] = array('ObjectTest', 'Actions/ObjectTest.php', 'Public');
-
- // Demo actions for building a user system
- $ACTIONS[] = array('UserAdd', 'Actions/UserAdd.php', 'Public');
- $ACTIONS[] = array('UserView', 'Actions/UserView.php', 'Public');
- $ACTIONS[] = array('UserEdit', 'Actions/UserEdit.php', 'Public');
- $ACTIONS[] = array('UserDelete', 'Actions/UserDelete.php', 'Public');
- $ACTIONS[] = array('LogIn', 'Actions/LogIn.php', 'Public');
- $ACTIONS[] = array('CookieTest', 'Actions/CookieTest.php', 'Public');
- $ACTIONS[] = array('SlowAction', 'Actions/SlowAction.php', 'Public');
-
- /*********************************************************/
-
- // Variables that might not be in the TABLLES. List any extra parameters your application might need
- $POST_VARIABLES = array();
-
- $POST_VARIABLES[] = "Action";
- $POST_VARIABLES[] = "APIKey";
- $POST_VARIABLES[] = "IP";
- $POST_VARIABLES[] = "UpperLimit";
- $POST_VARIABLES[] = "LowerLimit";
- $POST_VARIABLES[] = "Date";
- $POST_VARIABLES[] = "TimeStamp";
- $POST_VARIABLES[] = "Rand";
- $POST_VARIABLES[] = "Hash";
- $POST_VARIABLES[] = "DeveloperID";
- $POST_VARIABLES[] = "OutputType";
- $POST_VARIABLES[] = "Callback";
- $POST_VARIABLES[] = "LimitLockPass";
- $POST_VARIABLES[] = "Password";
-
- /*********************************************************/
- require('config_cleaner.php');
-
-}
-
-?>
22 PHP-DAVE-API/WriteToLog.php
View
@@ -1,22 +0,0 @@
-<?php
-
-/***********************************************
-DAVE PHP API
-https://github.com/evantahler/PHP-DAVE-API
-Evan Tahler | 2011
-
-Even when an action fails, we should log that it happened. This is importnat to bloc IPs that access the IP too much, etc. This page should not use the safety string or do error checks, because we want it to always happen even if there is an error.
-
-***********************************************/
-
-if (!(in_array($PARAMS["Action"],$NoLogActions)) && !(in_array($PARAMS["APIKey"],$NoLogAPIKeys)))
-{
- $Status = $DBObj->GetStatus();
- if ($Status === true)
- {
- $SQL= 'INSERT INTO `'.$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).'");';
- $DBObj->Query($SQL);
- }
-}
-
-?>
42 PHP-DAVE-API/SERVER.php → SERVER/SERVER.php
View
@@ -8,14 +8,17 @@
How to test post: curl -d "param1=value1&param2=value2" http://localhost:3000/some/page/php
*** Due to metaprogramming limitations in the default PHP installs on most servers/machines, it is impossible to modify the behavior of header() and setcookie(). To remedy this, please use _header() and _setcookie() in your DAVE projects. You can see below that they will first attempt to use the default versions of these functions, and if they fail (AKA when using the StandAlone server), will emulate thier behavior in other ways. ***
+
+TODO: Catch Exceptions from script_runner which may cause failures and not yeild a return
***********************************************/
-// CONFIG
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
+// CONFIG
-require("CONFIG.php");
+require("server_config.php");
+date_default_timezone_set($SERVER['systemTimeZone']);
function _server_log($string)
{
@@ -128,7 +131,7 @@ function cleanInternalInput($string)
function _run($URL, $remote_ip, $client_id)
{
- global $_GET, $_POST, $_COOKIE, $SERVER, $PHP_Path;
+ global $_GET, $_POST, $_COOKIE, $SERVER;
$_SERVER = array(
"PHP_SELF" => $URL,
@@ -137,20 +140,20 @@ function _run($URL, $remote_ip, $client_id)
"SERVER_PROTOCOL" => "HTTP/1.0",
"REMOTE_ADDR" => $remote_ip,
);
- $_FILE = getcwd()."/".$URL;
+ $_FILE = getcwd()."/".$SERVER['root_path'].$URL;
- $sys = escapeshellcmd($PHP_Path." ".getcwd()."/script_runner.php --FILE=".serialize($_FILE)." --SERVER=".serialize($_SERVER)." --GET=".serialize($_GET)." --POST=".serialize($_POST)." --COOKIE=".serialize($_COOKIE)." --CLIENT_ID=".serialize($client_id)." --PARENT_PORT=".serialize($SERVER['internal_port'])." --PARENT_URL=".serialize($SERVER['domain']))." > /dev/null 2>&1 & ";
+ $sys = escapeshellcmd($SERVER['PHP_Path']." ".getcwd()."/script_runner.php --FILE=".serialize($_FILE)." --SERVER=".serialize($_SERVER)." --GET=".serialize($_GET)." --POST=".serialize($_POST)." --COOKIE=".serialize($_COOKIE)." --CLIENT_ID=".serialize($client_id)." --PARENT_PORT=".serialize($SERVER['internal_port'])." --PARENT_URL=".serialize($SERVER['domain']))." > /dev/null 2>&1 & ";
$sys = str_replace('"','\"',$sys);
$script_output = `$sys`;
return $script_output;
}
-// INIT
+
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
+// INIT
-/* Setup */
$ServerStartTime = time();
set_time_limit (0);
ini_set( 'default_socket_timeout', (60*60)); // 60 min keep alive
@@ -174,6 +177,7 @@ function _run($URL, $remote_ip, $client_id)
// Start listening for connections
socket_listen($sock);
+
_server_log('..........Starting Server @ port '.$SERVER['public_port'].'..........');
////////////////////////////////////////////////////////////////////////////////
@@ -186,6 +190,7 @@ function _run($URL, $remote_ip, $client_id)
echo "$errstr_internal ($errno_internal) \r\n";
exit;
}
+_server_log('..........Listening internally @ port '.$SERVER['internal_port'].'..........');
$internal_master[] = $internal_socket;
$internal_read = $internal_master;
@@ -196,7 +201,7 @@ function _run($URL, $remote_ip, $client_id)
$connection_counter = 0;
$RESPONSES = array(); // array to hold worker output from interal workers
-
+_server_log('..........SERVER Ready..........');
while (true) {
// Setup clients listen socket for reading
$read[0] = $sock;
@@ -233,7 +238,9 @@ function _run($URL, $remote_ip, $client_id)
-
+ ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
// If a client is trying to write - handle it now
for ($i = 0; $i < $SERVER['max_clients']; $i++) // for each client
{
@@ -315,13 +322,16 @@ function _run($URL, $remote_ip, $client_id)
-
+ ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
// Return page content
+
if ($URL == "/"){ $URL = "index.php"; }
else{ $URL = substr($URL,1); }
- if(file_exists($URL))
+ if(file_exists($SERVER['root_path'].$URL))
{
- $contents = file_get_contents($URL);
+ $contents = file_get_contents($SERVER['root_path'].$URL);
if ($contents === false){
$headers = make_headers(404, $URL);
SendDataToClient($client[$i], $headers);
@@ -357,7 +367,9 @@ function _run($URL, $remote_ip, $client_id)
-
+ ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
// Handle data recipt and closure
if ($client[$i]['mode'] == 'wait')
{
@@ -404,7 +416,9 @@ function _run($URL, $remote_ip, $client_id)
-
+ ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
// HANDLE INTERNAL CONNECTIONS
$internal_read = $internal_master;
$mod_fd = stream_select($internal_read, $_w = NULL, $_e = NULL, 0, $SERVER['poll_timeout']);
41 PHP-DAVE-API/script_runner.php → SERVER/script_runner.php
View
@@ -15,7 +15,40 @@
/usr/bin/php /PROJECTS/php-dave-api/PHP-DAVE-API/script_runner.php --FILE=s:45:\"/PROJECTS/php-dave-api/PHP-DAVE-API/index.php\"\; --SERVER=a:5:\{s:8:\"PHP_SELF\"\;s:9:\"index.php\"\;s:11:\"SERVER_ADDR\"\;s:9:\"localhost\"\;s:11:\"SERVER_NAME\"\;s:9:\"localhost\"\;s:15:\"SERVER_PROTOCOL\"\;s:8:\"HTTP/1.0\"\;s:11:\"REMOTE_ADDR\"\;s:9:\"127.0.0.1\"\;\} --GET=a:0:\{\} --POST=a:3:\{s:13:\"LimitLockPass\"\;s:6:\"Sekret\"\;s:10:\"OutputType\"\;s:3:\"XML\"\;s:6:\"Action\"\;s:0:\"\"\;\} --COOKIE=a:0:\{\} --CLIENT_ID=i:0\; --PARENT_PORT=i:3001\; --PARENT_URL=s:9:\"localhost\"\;
***********************************************/
-require("helper_functions/parseArgs.php");
+
+// FROM PHP.NET
+function __parseArgs(){
+ global $argv;
+ array_shift($argv);
+ $out = array();
+ foreach ($argv as $arg){
+ if (substr($arg,0,2) == '--'){
+ $eqPos = strpos($arg,'=');
+ if ($eqPos === false){
+ $key = substr($arg,2);
+ $out[$key] = isset($out[$key]) ? $out[$key] : true;
+ } else {
+ $key = substr($arg,2,$eqPos-2);
+ $out[$key] = substr($arg,$eqPos+1);
+ }
+ } else if (substr($arg,0,1) == '-'){
+ if (substr($arg,2,1) == '='){
+ $key = substr($arg,1,1);
+ $out[$key] = substr($arg,3);
+ } else {
+ $chars = str_split(substr($arg,1));
+ foreach ($chars as $char){
+ $key = $char;
+ $out[$key] = isset($out[$key]) ? $out[$key] : true;
+ }
+ }
+ } else {
+ $out[] = $arg;
+ }
+ }
+ return $out;
+}
+
function __ErrorHandler($errno, $errstr, $errfile, $errline)
{
if (!(error_reporting() & $errno)) {
@@ -65,8 +98,6 @@ function __ErrorHandler($errno, $errstr, $errfile, $errline)
$__PARENT_URL = @unserialize($__input["PARENT_URL"]);
$__PARENT_PORT = @unserialize($__input["PARENT_PORT"]);
-echo "-->".$__PARENT_URL."\r\n\r\n";
-
foreach ($_GET as $k => $v){ $_REQUEST[$k] = $v; }
foreach ($_POST as $k => $v){ $_REQUEST[$k] = $v; }
foreach ($_COOKIE as $k => $v){ $_REQUEST[$k] = $v; }
@@ -93,8 +124,8 @@ function _setcookie($name, $value = null, $expire = null, $path = null, $domain
{
// TODO: Handle $domain, $secure and $httponly
- if (!($expire > 0)){$expire = time() + 60*60;} // 1 hour default cookie duration
- $datetime = new DateTime(date("Y-m-d H:i:s",$expire), new DateTimeZone('GMT'));
+ if (!($expire > 0)){$expire = time() + 60*60*24;} // 1 day default cookie duration
+ $datetime = new DateTime(date("Y-m-d H:i:s",$expire));
$cookie_time = $datetime->format(DATE_COOKIE);
// $cookie_time = date("D, d-M-Y H:i:s T",$expire);
if ($path == null){$path = "/";}
22 SERVER/server_config.php
View
@@ -0,0 +1,22 @@
+<?php
+/***********************************************
+DAVE PHP API
+https://github.com/evantahler/PHP-DAVE-API
+Evan Tahler | 2011
+
+I hold all the configuration variables for the API
+***********************************************/
+
+$SERVER = array();
+$SERVER['public_port'] = 3000;
+$SERVER['internal_port'] = 3001;
+$SERVER['poll_timeout'] = 10000; // in micro-seconds.
+$SERVER['max_clients'] = 100;
+$SERVER['domain'] = "localhost";
+$SERVER['root_path'] = "../API/"; // from location of SERVER.php
+$SERVER['PHP_Path'] = "/usr/bin/php";
+$SERVER['systemTimeZone'] = "America/Los_Angeles";
+$SERVER['log_file'] = "LOG/SERVER_LOG.txt";
+@mkdir("LOG");
+
+?>
0  PHP-DAVE-API/spec/TEST.php → SPEC/TEST.php
View
File renamed without changes
2  PHP-DAVE-API/spec/actions/DescribeActions.php → SPEC/actions/DescribeActions.php
View
@@ -13,7 +13,7 @@
$PostArray = array(
"OutputType" => "PHP",
"Action" => "DescribeActions",
- "LimitLockPass" => $CorrectLimitLockPass
+ "LimitLockPass" => $CONFIG['CorrectLimitLockPass']
);
var_dump($TestURL);
$APIRequest = new APIRequest($TestURL, $PostArray);
17 PHP-DAVE-API/spec/spec_helper.php → SPEC/spec_helper.php
View
@@ -5,17 +5,18 @@
Evan Tahler | 2011
I setup the testing enviorment and include handy functions for the test suite
-***********************************************/
-$path = substr(__FILE__,0,(strlen(__FILE__) - strlen($_SERVER['SCRIPT_NAME'])));
-require_once("../../AccessTools/APIRequest.php");
-require_once("../../helper_functions/colors.php");
-require_once("../../ConnectToDatabase.php");
-require_once("../../CONFIG.php");
-date_default_timezone_set($systemTimeZone);
+TODO: Handle errrors in testing elegantly so next tests continue
+TODO: Aggregate testing scores for whole suite
+***********************************************/
+require_once("../../API/AccessTools/APIRequest.php");
+require_once("../../API/helper_functions/colors.php");
+require_once("../../API/ConnectToDatabase.php");
+require_once("../../API/CONFIG.php");
$TestLog = "LOG/test_log.txt"; // from project root
-$TestURL = $SERVER['domain'].":".$SERVER['public_port']
+@mkdir("LOG");
+$TestURL = "localhost:3000"; // be sure to include the proper port (default for using included SERVER.php)
if (!class_exists(DaveTest))
{
6 PHP-DAVE-API/spec/system/general.php → SPEC/system/general.php
View
@@ -22,7 +22,7 @@
$T->assert("<",$second,$first);
// computation time should be > 0 but less than 10 seconds
-$PostArray = array("OutputType" => "PHP", "LimitLockPass" => $CorrectLimitLockPass);
+$PostArray = array("OutputType" => "PHP", "LimitLockPass" => $CONFIG['CorrectLimitLockPass']);
$APIRequest = new APIRequest($TestURL, $PostArray);
$APIDATA = $APIRequest->DoRequest();
$ComputationTime = $APIDATA["ComputationTime"];
@@ -30,14 +30,14 @@
$T->assert("<",$ComputationTime,10);
//I should have an IP address
-$PostArray = array("OutputType" => "PHP", "LimitLockPass" => $CorrectLimitLockPass);
+$PostArray = array("OutputType" => "PHP", "LimitLockPass" => $CONFIG['CorrectLimitLockPass']);
$APIRequest = new APIRequest($TestURL, $PostArray);
$APIDATA = $APIRequest->DoRequest();
$IP = $APIDATA["IP"];
$T->assert("true",IP_check($IP));
//The sever should have an IP address and a ServerName
-$PostArray = array("OutputType" => "PHP", "LimitLockPass" => $CorrectLimitLockPass);
+$PostArray = array("OutputType" => "PHP", "LimitLockPass" => $CONFIG['CorrectLimitLockPass']);
$APIRequest = new APIRequest($TestURL, $PostArray);
$APIDATA = $APIRequest->DoRequest();
$ServerAddress = $APIDATA["IP"];
6 PHP-DAVE-API/spec/system/output_types.php → SPEC/system/output_types.php
View
@@ -10,14 +10,14 @@
$T = new DaveTest("Output Tests");
// PHP
-$PostArray = array("OutputType" => "PHP", "LimitLockPass" => $CorrectLimitLockPass);
+$PostArray = array("OutputType" => "PHP", "LimitLockPass" => $CONFIG['CorrectLimitLockPass']);
$APIRequest = new APIRequest($TestURL, $PostArray);
$APIDATA = $APIRequest->DoRequest();
$T->assert(">",count($APIDATA),0);
$T->assert(">",strlen($APIDATA["ERROR"]),0);
// JSON
-$PostArray = array("OutputType" => "JSON", "LimitLockPass" => $CorrectLimitLockPass);
+$PostArray = array("OutputType" => "JSON", "LimitLockPass" => $CONFIG['CorrectLimitLockPass']);
$APIRequest = new APIRequest($TestURL, $PostArray);
$APIRequest->DoRequest();
$JSON_resp = json_decode($APIRequest->ShowRawResponse(), true);
@@ -25,7 +25,7 @@
$T->assert(">",strlen($JSON_resp["ERROR"]),0);
// XML
-$PostArray = array("OutputType" => "XML", "LimitLockPass" => $CorrectLimitLockPass);
+$PostArray = array("OutputType" => "XML", "LimitLockPass" => $CONFIG['CorrectLimitLockPass']);
$APIRequest = new APIRequest($TestURL, $PostArray);
$APIRequest->DoRequest();
$XML_resp = simplexml_load_string($APIRequest->ShowRawResponse());
Please sign in to comment.
Something went wrong with that request. Please try again.