This commit is contained in:
Ulrich Block 2013-08-20 20:44:19 +02:00
parent 681cc4abe8
commit 0369fe0c8b
5 changed files with 664 additions and 0 deletions

20
external/api_config.php vendored Normal file
View File

@ -0,0 +1,20 @@
<?php
/**
* File: api_config.php.
* Author: Ulrich Block
* Copyright 2010-2012
* Contact: support@easy-wi.com
* Page: easy-wi.com
*/
// Configuring the API. Should be placed in another file and included
// The database access
$config['dbHost']='localhost';
$config['dbName']='database';
$config['dbUser']='databaseUser';
$config['dbPwd']='securePassword';
// Access to the file
$config['passwordToken']='myPasswordToken';
$config['allowedIPs']=array('1.1.1.1','1.1.1.2');

139
external/api_users.php vendored Normal file
View File

@ -0,0 +1,139 @@
<?php
/**
* File: api_users.php.
* Author: Ulrich Block
* Copyright 2010-2012
* Contact: support@easy-wi.com
* Page: easy-wi.com
*/
// include config file
require_once ('api_config.php');
// Initial parameters
$error=array();
// There is no need to check every user every time
// Start looking only for new IDs
if (isset($_GET['lastID']) and is_numeric($_GET['lastID'])) {
$lastID=(int)$_GET['lastID'];
} else {
$lastID=0;
}
// this requieres that a column exists which is updated every time the account gets an update:
// ALTER TABLE `yourUserTable` ADD COLUMN `updatetime` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
// This might lead to false posivives if data like the logintime is stored in that table.
// The more accurate way would be to fill/update the column only in wanted cases
if (isset($_GET['updateTime']) and @strtotime($_GET['updateTime'])) {
// convert to string and back to date so proper format is ensured
$updateTime=date('Y-m-d H:i:s',strtotime($_GET['updateTime']));
} else {
$updateTime='0000-00-00 00:00:00';
}
// Processing all users at once can lead to memory issues if system is small or userbase large.
if (isset($_GET['chunkSize']) and is_numeric($_GET['chunkSize'])) {
$chunkSize=(int)$_GET['chunkSize'];
} else {
$chunkSize=10;
}
// To be able to properly get data in chunks the starting point needs to be defined.
if (isset($_GET['start']) and is_numeric($_GET['start'])) {
$start=(int)$_GET['start'];
} else {
$start=0;
}
// Check if the IP is whitelisted
if(isset($_SERVER['REMOTE_ADDR']) and in_array($_SERVER['REMOTE_ADDR'],$config['allowedIPs'])) {
$config['externalIP']=$_SERVER['REMOTE_ADDR'];
} else {
$error[]='Scipt called locally or IP is not whitelisted.';
}
// Check if access token was send and is correct
if (!isset($_GET['passwordToken'])) {
$error[]='No password token has been send.';
} else if ($_GET['passwordToken']!=$config['passwordToken']) {
$error[]='Bad password token has been send.';
}
// Send header data
header("Content-type: application/json; charset=UTF-8");
// If there was an error send error and stop script
if (count($error)>0) {
echo json_encode(array('error'=>$error));
// Else check for new users
} else {
// Establish database connection
try {
$connection=new PDO("mysql:host=".$config['dbHost'].";dbname=".$config['dbName'],$config['dbUser'],$config['dbPwd'],array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET NAMES utf8"));
$connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
// Get amount of users that are new or received an update
// The Query needs to be altered to your database. This is just an example!
$sql="SELECT COUNT(`userID`) AS `amount` FROM `ws_C4J_user`
WHERE (`userID`>? OR `updatetime`>?) AND `activated`=1 AND `banned` IS NULL";
$query=$connection->prepare($sql);
$query->execute(array($lastID,$updateTime));
$total=$query->fetchColumn();
// JSON array
$json=array();
// This query fetches the actual data.
// The Query needs to be altered to your database. This is just an example!
// specify the needed columns to reduce database load.
$sql="SELECT `userID`,`email`,`username`,`firstname`,`lastname`,`birthday`,`country`,`tel`,`fax`,`mobile`,`town`,`postcode`,`street`,`streetnr`,`updatetime`
FROM `usertable`
WHERE (`userID`>? OR `updatetime`>?) AND `activated`=1 AND (`banned` IS NULL OR `banned`='')
ORDER BY `userID`
LIMIT $start,$chunkSize";
$query=$connection->prepare($sql);
$query->execute(array($lastID,$updateTime));
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {
// Easy-Wi stores the salutation with numbers
if (isset($row['salutation']) and $row['salutation']=='mr') {
$salutation=1;
} else if (isset($row['salutation']) and $row['salutation']=='ms') {
$salutation=2;
} else {
$salutation='';
}
// the keys need to be adjusted to your table layout and query!
$json[]=array(
'externalID'=>$row['userID'],
'salutation'=>$salutation,
'email'=>$row['email'],
'loginName'=>$row['username'],
'firstName'=>$row['firstname'],
'lastName'=>$row['lastname'],
'birthday'=>$row['birthday'],
'country'=>$row['country'],
'phone'=>$row['tel'],
'fax'=>$row['fax'],
'handy'=>$row['mobile'],
'city'=>$row['town'],
'cityn'=>$row['postcode'],
'street'=>$row['street'],
'streetn'=>$row['streetnr'],
'updatetime'=>$row['updatetime']
);
}
// Echo the JSON reply with
echo json_encode(array('total'=>$total,'users'=>$json));
}
// Catch database error and display
catch(PDOException $error) {
echo json_encode(array('error'=>$error->getMessage()));
}
}

285
external/easywiapi.php vendored Normal file
View File

@ -0,0 +1,285 @@
<?php
class EasyWiRestAPI {
// define internal vars
private $method,$timeout,$connect=false,$user,$pwd,$handle=null,$ssl,$port,$url;
protected $response=array();
// Constructor that sets defaults which can be overwritten
__construct($url,$user,$pwd,$timeout=10,$ssl=false,$port=80,$method='xml',$connect='curl') {
$this->timeout=$timeout;
// check if curl is choosen and available and initiate cURL-Session
if ($connect=='curl' and function_exists('curl_init')) {
if ($this->startCurl($url,$ssl,$port)===true) {
$this->connect='curl';
}
// Use and or fallback to fsockopen if possible and create socket
} else if (($connect=='fsockopen' or !function_exists('curl_init')) and function_exists('fsockopen')) {
if ($this->startSocket($url,$ssl,$port)===true) {
$this->connect='fsockopen';
}
}
// If connection was successfull, go on and set values
if ($this->connect!==false) {
$this->user=$user;
$this->pwd=$pwd;
$this->ssl=$ssl;
$this->port=$port;
$this->url=$url;
// Use json, or xml to communicate
if ($method=='json') {
$this->method='json';
} else {
$this->method='xml';
}
} else {
$this->throwException(10);
}
}
// False usage of the object needs to be handled and execution stopped
private function throwException ($rawError,$extraText=false) {
// If an exception is caught from imbedded class use the raw error
if (is_object($rawError)) {
$errorcode=$rawError->getMessage();
// else use the custom messages
} else {
// default custom messages
$errorArray=array(
1=>'Bad data: Only Strings and Integers are allowed!',
2=>'Bad data: Only Strings are allowed!',
3=>'Bad data: Only Integers are allowed!',
4=>'Bad data: Only arrays are allowed!',
5=>'Bad data: Unknown Error!',
6=>'Bad data: Empty values!',
10=>'Connection Error: Could not connect to!'.$this->url
);
// if the message is not predifined use the raw input
if (array_key_exists($rawError,$errorArray)) {
$errorcode=$errorArray["${rawError}"];
} else {
$errorcode=$rawError;
}
}
// Add some extra info if given
if ($extraText!==false) {
$errorcode.=$extraText;
}
throw new Exception('<p>'.$errorcode.'</p>');
die;
}
//
private function startCurl ($url,$ssl,$port) {
// create the URL to call
if (substr($url,-1)=='/') {
$url=substr($url,0,-1);
}
$url=str_replace(array('http://','https://',':8080',':80',':443'),'',$url);
if ($ssl==true) {
$url='https://'.$url;
} else {
$url='http://'.$url;
}
$url=$url.'/api.php';
// create cURL-Handle
$this->handle=curl_init($url);
// check success
if ($this->handle===false) {
return false;
} else {
// Set options
$this->setbasicCurlOpts();
return true;
}
}
// in case of curl setopts
private function setbasicCurlOpts () {
curl_setopt($this->handle,CURLOPT_CONNECTTIMEOUT,$this->timeout);
curl_setopt($this->handle,CURLOPT_USERAGENT,"cURL (Easy-WI; 1.0; Linux)");
curl_setopt($this->handle,CURLOPT_RETURNTRANSFER,true);
curl_setopt($this->handle,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($this->handle,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($this->handle,CURLOPT_HEADER,1);
//curl_setopt($this->handle,CURLOPT_ENCODING,'deflate');
if (($this->ssl===true and $this->port!=443) or ($this->ssl===false and $this->port!=80)) {
curl_setopt($this->handle,CURLOPT_PORT,$this->port);
}
}
// method to execute a curl request
private function execCurl($type,$send) {
// Setting up POST data and add it to the opts
$postArray['user']=$this->user;
$postArray['pwd']=$this->pwd;
$postArray['type']=$type;
$postArray['xmlstring']=$send;
curl_setopt($this->handle,CURLOPT_POSTFIELDS,$postArray);
// Execute request, get the response and return it.
$this->response=curl_exec($this->handle);
$this->header=curl_getinfo($this->handle);
return $this->response;
}
// Ioncube obfuscated files add sometimes data to the REST responses.
// This will be picked up if fsockopen is used.
// So there is a need to strip this data.
private function convertRawData ($rawdata) {
if ($this->method=='json') {
$checkStart='{';
$checkStop='}';
} else {
$checkStart='<';
$checkStop='>';
}
$response=$rawdata;
while (substr($response,0,1)!=$checkStart and strlen($response)>0) {
$response=substr($response,1);
}
while (substr($response,-1)!=$checkStop and strlen($response)>0) {
$response=substr($response,0,-1);
}
// Decode the rest of the response string into an object.
if ($this->method=='json') {
$decoded=@json_decode($response);
} else {
$decoded=@simplexml_load_string($response);
}
// If decoding was not possible return the raw response, else return the object.
if ($decoded) {
unset($rawdata);
return $decoded;
} else if ($this->connect=='fsockopen') {
return substr($rawdata,4,-3);
} else {
return $rawdata;
}
unset($decoded);
}
// create the JSON that will be send to the API
private function JSONPostValue ($paramArray,$action,$params) {
$jsonArray=array();
foreach ($paramArray as $param) {
if (array_key_exists($param,$params)) {
if (is_array($params[$param])) {
$jsonArray[$param]=array();
foreach ($params[$param] as $val) {
$jsonArray[$param][]=$params[$param];
}
} else {
$jsonArray[$param]=$params[$param];
}
} else {
$jsonArray[$param]='';
}
}
$json=json_encode($jsonArray);
unset($type,$params,$paramArray,$jsonArray);
return $json;
}
// create the XML that will be send to the API
private function XMLPostValue ($paramArray,$action,$params) {
$xml=new SimpleXMLElement(<<<XML
<?xml version='1.0' standalone='yes'?>
<server></server>
XML
);
foreach ($paramArray as $param) {
if (array_key_exists($param,$params)) {
if (is_array($params[$param])) {
foreach ($params[$param] as $val) {
$xml->addChild($param,$val);
}
} else {
$xml->addChild($param,$params[$param]);
}
} else {
$jsonArray[$param]='';
}
}
unset($type,$params,$paramArray);
return $xml;
}
// Method the external script calls
public function makeRestCall($type,$action,$params) {
// some param validation. On fail throw an exception
if (!is_string($type)) {
$this->throwException(2,': $type');
}
if (!is_string($action)) {
$this->throwException(2,': $action');
}
if (!is_array($params)) {
$this->throwException(4,': $params');
}
if (!in_array($type,array('user','gserver','mysql','voice','restart'))) {
$this->throwException('Error: $type is not defined correctly. Allowed methods are (user, gserver, mysql, vserver, restart)');
}
if (!in_array($action,array('mod','add','del','ls','st','re'))) {
$this->throwException('Error: $action is not defined correctly. Allowed methods are (md, ad, dl, st, re, list)');
}
// Array keys that all methods have in common
$generalArray=array('username','user_localid','active');
// Array keys server have in common
$generalServerArray=array('identify_user_by','user_externalid','identify_server_by','server_external_id','server_local_id','master_server_id','master_server_external_id');
// Keys specfic to user
$paramArray['user']=array('identify_by','external_id','localid','email','password');
// Keys specfic to gserver
$paramArray['gserver']=array('private','shorten','slots','primary','taskset','cores','eacallowed','tvenable','pallowed','opt1','opt2','opt3','opt4','opt5','port2','port3','port4','port5','minram','maxram','brandname');
// Keys specfic to voice
$paramArray['voice']=array('private','shorten','slots','max_download_total_bandwidth','max_upload_total_bandwidth','maxtraffic','forcebanner','forcebutton','forceservertag','forcewelcome');
// Keys specfic to mysql
$paramArray['mysql']=array();
// create the post value
if ($this->method=='json') {
$post=$this->JSONPostValue(array_unique(array_merge($generalArray,$generalServerArray,$paramArray[$type])),$action,$params);
} else {
$post=$this->XMLPostValue(array_unique(array_merge($generalArray,$generalServerArray,$paramArray[$type])),$action,$params);
}
// Call method to send the data depending on the connection type
if ($this->connect=='curl' and is_recource($this->handle)) {
$this->execCurl($type,$post);
} else if ($this->connect=='fsockopen' and is_recource($this->handle)) {
fclose($this->handle);
} else {
$this->throwException(10);
}
}
// destructor
__destruct () {
if ($this->connect=='curl' and is_recource($this->handle)) {
curl_close($this->handle);
} else if ($this->connect=='fsockopen' and is_recource($this->handle)) {
fclose($this->handle);
}
unset($method,$timeout,$connect,$user,$pwd,$handle,$ssl,$port,$response);
}
}

177
external/easywiapitest.php vendored Normal file
View File

@ -0,0 +1,177 @@
<?php
$host = 'wi.domain.de';
$path = '/api.php';
$user = 'user';
$pwd = '123456';
if (isset($_GET['id'])) {
$localID=$_GET['id'];
} else {
$localID='';
}
if (isset($_GET['userID'])) {
$userID=$_GET['userID'];
} else {
$userID='';
}
if (isset($_GET['action'])) {
$action=$_GET['action'];
} else {
$action='add';
}
if ($_GET['test']=='user') {
$type = 'user';
$postxml = <<<XML
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE users>
<users>
<action>$action</action>
<identify_by>localid</identify_by>
<username></username>
<external_id>26</external_id>
<localid>$localID</localid>
<groupID>570</groupID>
<email>testing2@mail.de</email>
<password></password>
<active>Y</active>
</users>
XML;
} else if ($_GET['test']=='gserver') {
$type = 'gserver';
$postxml = <<<XML
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE server>
<server>
<action>$action</action>
<identify_user_by>user_localid</identify_user_by>
<identify_server_by>server_local_id</identify_server_by>
<username></username>
<user_externalid></user_externalid>
<user_localid>$userID</user_localid>
<shorten>css</shorten>
<shorten>cstrike</shorten>
<primary>cstrike</primary>
<slots>12</slots>
<restart>re</restart>
<private>N</private>
<server_external_id></server_external_id>
<server_local_id>$localID</server_local_id>
<active>N</active>
<master_server_id></master_server_id>
<master_server_external_id></master_server_external_id>
<taskset></taskset>
<cores></cores>
<eacallowed></eacallowed>
<brandname></brandname>
<tvenable></tvenable>
<pallowed></pallowed>
<opt1>123</opt1>
<opt2></opt2>
<opt3></opt3>
<opt4></opt4>
<opt5></opt5>
<port>2000</port>
<port2>2001</port2>
<port3>2003</port3>
<port4>2004</port4>
<port5></port5>
<minram></minram>
<maxram></maxram>
<initialpassword></initialpassword>
</server>
XML;
if(isset($_GET['restart']) and $_GET['restart']=='re' or $_GET['st']) {
$restart=$_GET['restart'];
$postxml = <<<XML
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE server>
<server>
<action>$action</action>
<identify_server_by>server_local_id</identify_server_by>
<restart>$restart</restart>
<server_external_id></server_external_id>
<server_local_id>$localID</server_local_id>
</server>
XML;
}
} else if ($_GET['test']=='voice') {
$type = 'voice';
$postxml = <<<XML
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE server>
<server>
<action>$action</action>
<identify_user_by>user_localid</identify_user_by>
<identify_server_by>server_local_id</identify_server_by>
<username></username>
<user_externalid></user_externalid>
<user_localid>$userID</user_localid>
<shorten>ts3</shorten>
<slots>12</slots>
<private>N</private>
<server_external_id></server_external_id>
<server_local_id>$localID</server_local_id>
<active>N</active>
<master_server_id>44</master_server_id>
<master_server_external_id></master_server_external_id>
<max_download_total_bandwidth></max_download_total_bandwidth>
<max_upload_total_bandwidth></max_upload_total_bandwidth>
<maxtraffic></maxtraffic>
<forcebanner></forcebanner>
<forcebutton></forcebutton>
<forceservertag></forceservertag>
<forcewelcome></forcewelcome>
</server>
XML;
} else {
echo '<pre>';
print_r();
echo '<pre>';
}
if (!isset($stop)) {
if (isset($postxml)) echo $postxml.'<br />';
$data = 'pwd='.urlencode($pwd).'&user='.$user.'&xml='.urlencode(base64_encode($postxml)).'&type='.$type;
$useragent=$_SERVER['HTTP_HOST'];
$fp = @fsockopen($host, 80, $errno, $errstr, 30);
$buffer="";
if ($fp) {
$send = "POST ".$path." HTTP/1.1\r\n";
$send .= "Host: ".$host."\r\n";
$send .="User-Agent: $useragent\r\n";
$send .= "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n";
$send .= "Content-Length: ".strlen($data)."\r\n";
$send .= "Connection: Close\r\n\r\n";
$send .= $data;
fwrite($fp, $send);
while (!feof($fp)) {
$buffer .= fgets($fp, 1024);
}
fclose($fp);
}
list($header,$response)=explode("\r\n\r\n",$buffer);
$raw=$response;
$header=str_replace(array("\r\n","\r"),"\n",$header);
$header=str_replace("\t",' ',$header);
$ex=explode("\n",$header);
list($type,$errocode,$errortext)=explode(' ',$ex[0]);
echo 'Here comes the response:<br /><pre>';
if ($errocode>400) {
print_r(substr($response,4,-3));
} else {
while(substr($response,0,1)!='<' and strlen($response)>0) {
$response=substr($response,1);
}
while(substr($response,-1)!='>' and strlen($response)>0) {
$response=substr($response,0,-1);
}
$object=@simplexml_load_string($response);
if ($object) {
echo '<pre>';
print_r($object);
echo '</pre>';
} else {
echo 'Could not decode response<br />';
echo $raw;
}
}
}

43
external/easywitester.php vendored Normal file
View File

@ -0,0 +1,43 @@
<?php
if (isset($_POST['ip']) and isset($_POST['port']) and isset($_POST['submit']) and !empty($_POST['ip']) and !empty($_POST['port'])) {
//Verbindung
$ssh2=ssh2_connect($_POST['ip'],$_POST['port']);
if ($ssh2==true) {
echo 'Connect to: '.$_POST['ip'].':'.$_POST['port'].'<br />';
// Login
if (isset($_POST['user']) and isset($_POST['password']) and !empty($_POST['user']) and !empty($_POST['password'])) {
$connect_ssh2=ssh2_auth_password($ssh2,$_POST['user'],$_POST['password']);
if ($connect_ssh2==true) {
echo 'Logindata works';
} else {
echo 'Logindata does not work';
}
} else {
echo 'No Logindata entered';
}
} else {
echo 'could not connect to: '.$_POST['ip'].':'.$_POST['port'];
}
} else {
echo extension_loaded('ionCube Loader') ? 'Ioncube extension is installed<br />' : 'Ioncube extension is not installed, please install it.<br />';
echo extension_loaded('ssh2') ? 'SSH2 extension is installed.<br />' : 'SSH2 extension is not installed, please install it.<br />';
echo extension_loaded('openssl') ? 'openssl extension is installed.<br />' : 'openssl extension is not installed, please install it.<br />';
echo extension_loaded('json') ? 'json extension is installed.<br />' : 'json extension is not installed, please install it.<br />';
echo extension_loaded('hash') ? 'hash extension is installed.<br />' : 'hash extension is not installed, please install it.<br />';
echo extension_loaded('ftp') ? 'openssl extension is installed.<br />' : 'ftp extension is not installed, please install it.<br />';
echo extension_loaded('SimpleXML') ? 'session SimpleXMLis installed.<br />' : 'SimpleXML extension is not installed, please install it.<br />';
echo extension_loaded('curl') ? 'curl extension is installed.<br />' : 'curl extension is not installed, please install it.<br />';
echo extension_loaded('gd') ? 'gd extension is installed.<br />' : 'gd extension is not installed, please install it.<br />';
echo extension_loaded('PDO') ? 'PDO extension is installed.<br />' : 'PDO extension is not installed, please install it.<br />';
echo extension_loaded('pdo_mysql') ? 'pdo_mysql extension is installed.<br />' : 'pdo_mysql extension is not installed, please install it.<br />';
echo function_exists('fopen') ? 'fopen function can be used.<br />' : 'fopen function cannot be used) and isset( please enable it.<br />';
if (extension_loaded('ssh2')) {
echo 'SSH2 extension is installed.<br />';
echo '<h1>Test SSH2 connection</h1><form method=post action='.$_SERVER['PHP_SELF'].' >IP: <input type=text name=ip required /><br />Port: <input type=text name=port required /><br />User: <input type=text name=user required /><br />Password: <input type=text name=password required /><br /><input type=submit name=submit value=Test /><br /></form>';
} else {
echo 'SSH2 extension is not installed, please install it.<br />';
}
}