I have managed to create a mysql database with itemIDs and Item types. so far all I have managed to do is generate a button that opens a url to eve api that grabs the prices from eve central. I can't currently post images.
The php code then generates an api url to show the prices which eventually my plan is to grab the Max Buy Prices and Min sell prices and perform on of the following on them:
if the corp needs the item it will be (maxbuyprice + Minsellprice)/2
if the corp doesn't need the item the calculation will be ((maxbuyprice + Minsellprice)/2) * 0.9
My problem is getting php to parse the xml instead of showing the xml document - I did this for debugging or seeing the data that is available.
for an example the url that I generated with Veldspar is:
generated url using Veldspar is the item name
index.php file:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/db.inc.php';
$pagetitle = 'HoMs Asset Management System - Create Contract';
$pagedescription = 'HoMs Asset Management System for managing Corporation Contracts and Pricing';
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/access.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/ObjectClasses.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/helpers.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/EveCentral.inc.php';
if (isset($_POST['action']) and $_POST['action']=='View Eve Central Prices')
{
$itemname = html($_POST['ItemName']);
calculateAskingPrice($itemname);
}
include 'createcontract.html.php';
?>
db.inc.php file:
<?php
//local dbstrings
//production dbstrings
$dbhost='localhost';
$dbusername='homedata1';
$dbpassword='EzPKfmxcTKAeSnDs';
$dbname='homdata';
Function connect2db()
{
Global $dbhost;
Global $pagetitle;
Global $pagedescription;
Global $mysqlport;
Global $dbname;
Global $dbusername;
Global $dbpassword;
Global $pdo;
Global $error;
Global $curNewsMessage;
Global $logged;
Global $ItemList;
try
{
$pdo = new PDO('mysql:host=' .$dbhost .';dbname=' .$dbname .';port=' .$mysqlport, $dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
return TRUE;
}
catch (PDOException $dbconerr)
{
$pagetitle = 'Hom Asset Management - Database Connection Error';
$pagedescription = 'There was a problem connecting to the database';
$error = 'Unable to connect to the database server:' ."\n\n"
.'The database in which this pages content relies on is unavailable or, for other reasons is not contactable' ."\n"
.'I am liasing with my website host to get this resolved as quickly as possible. Please check later.' ."\n"
.'sorry for any inconvenience' ."\n\n" .'This information may help to diagnose the problem: <br>' .$dbconerr;
$logged = 'Sorry. The interactive areas are unavailable because the database is unavailable';
$curNewsMessage = 'News message unavailable. ' ."\n" .' Database connection error';
return FALSE;
}
return TRUE;
}
EveCentral.inc.php file:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/helpers.inc.php';
function calculateAskingPrice($Item)
{
// Connect to the database and search for the item posted
include_once $_SERVER['DOCUMENT_ROOT'] .'/includes/db.inc.php';
Global $pdo;
Global $itemname;
if (connect2db())
{
$sql = "SELECT * FROM `itemtypes` WHERE ItemName=:itemname";
$s = $pdo->Prepare($sql);
$s->bindValue(':itemname',$Item);
$s->execute();
$row = $s->fetch();
if ($row > 0)
{
$itemid = html($row['ID']);
$evecurl = 'http://api.eve-central.com/api/marketstat?typeid=' .$itemid .'&usesystem=30000142';
header('Location: ' .$evecurl);
}
else
htmlout('Item not found: ' . $itemname);
}
else
{
echo 'problem connecting to database';
}
}
?>
here i got some version how can help us both:
$xml = simplexml_load_file('http://api.eve-central.com/api/marketstat?usesystem=30000142&hours=24&typeid=3683&minQ=10000');
echo $xml->marketstat->type->sell->min; // 257.99
Im a little comfused, are you wanting help parsing the EVE API xml or the mineral pull XML from eve central?
If it is the price XML, here is what i use, this is on my main page...
// Get Mineral Prices
GetCurrentMineralPrice();
$TritPrice = $ItemPrice[1];
$PyerPrice = $ItemPrice[2];
$MexPrice = $ItemPrice[3];
$IsoPrice = $ItemPrice[4];
$NocxPrice = $ItemPrice[5];
$ZydPrice = $ItemPrice[6];
$MegaPrice = $ItemPrice[7];
$MorPrice = $ItemPrice[8];
and this is the function it calls.
function GetCurrentMineralPrice() {
global $ItemPrice;
$xml = simplexml_load_file("http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&typeid=36&typeid=37&typeid=38&typeid=39&typeid=40&typeid=11399&usesystem=30000142");
$i = 1;
foreach ($xml->marketstat->type as $child) {
$ItemPrice[$i] = $child->buy->max;
$i++;
}
return $ItemPrice;
}
For the sell max price change this line...$ItemPrice[$i] = $child->sell->min;
if you are wanting to parse the EVE API, thats an entirely different story, that I havent mastered yet since each API XML is different...
Related
In an AD server we have an attribute called directreports. I want to be able to go top to bottom in the chain. CEO his direct reports are A,B,C. As direct reports are D,E,F while Bs direct report is G,H,I. Then Ds direct reports are X,Y,Z, etc all the way down.
I've looked at this as a nested group kind of thing, but it's not. I'm lost as how to tackle this all together. I'm trying to do this in PHP. My php code right now just searches a user and gives me the direct reports.
<?php
function aduserlookup ($UserName)
{
include_once 'config.php';
$ldapconn = ldap_connect("ldap://<IP>:389") or die("Could not connect to the ldap server");
if($ldapconn) {
$r = #ldap_bind($ldapconn, $ldapuser."#test.com", $ldappass);
$sr=ldap_search($ldapconn, "OU=Employees,OU=Users,DC=test,DC=com",
"cn=" . $UserName);
$info = ldap_get_entries($ldapconn, $sr);
ldap_close($ldapconn);
return $info;
} else {
echo "<h4>Unable to connect to LDAP server</h4>";
}
}
$user = aduserlookup('test');
$directreports = $user[0]['directreports'];
echo '<pre>';
var_dump($directreports);
echo '</pre>';
foreach ($directreports as $key => $value)
{
$directreports = substr($value, 0, strpos($value, ","));
$directreports = strstr($directreports, '=');
$directreports = str_replace('=', '', $directreports);
$directreports1 = aduserlookup('\'' . $directreports . '\'');
echo $directreports1 . "<br>";
}
?>
IF you are using Microsoft Active Directory and If I understood what you are looking for,
You can Query All users that report to a department manager or their subordinates by using this query
(manager:1.2.840.113556.1.4.1941:=CN=manager,OU=users,DC=willeke,DC=com)
DirectReports is a server generated list of users that directly report to the "manager". The users that are listed as reports are those that have the property manager property set to this user. Each item in the list is a Linked Attribute to the object that represents the user.
I would like to be able to save a JSON file that is in a database to the user's PC. In summary, I'm storing setup files from a sim racing game, that use a JSON format, in a database, and I'd like the user to be able to upload/download these JSON files (to share with others, etc).
I've got the upload working, using PDO, so there is a column called setup that is a text data type. I'm using a form, with a $FILES() to fetch the uploaded json file, with some checks to ensure it's a valid setup json.
$setup = file_get_contents($_FILES['setupjson']['tmp_name']); //get json from file uploaded
$setupJSON = json_decode($setup); //decode into object
$car = $setupJSON->carName; //carName from object
if ($obj->searchCarName($car) > 0) // if search matches (car exists)
{
if($obj->insertSingleSetup($_POST["name"], $_POST["description"], $_POST["type"], $car, $_POST["track"], $setup) !== false)
{
header('Location: add.php?success');
exit();
}
else
{
header('Location: add.php?error=Error+adding+the+setup');
exit();
}
}
else
{
header('Location: add.php?error=Please+submit+a+valid+setup');
exit();
}
}
The issue i'm having is downloading the file again. I've been able to view the JSON directly
<?php
include('../db.php');
$setup_id = $_POST['setup'];
try {
$connectionString = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4",
DB::DB_HOST,
DB::DB_NAME);
$pdo = new PDO($connectionString, DB::DB_USER, DB::DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = 'SELECT * FROM setups WHERE setup_id= :setupID';
$query = $pdo->prepare($sql);
$query->bindValue(':setupID', $setup_id);
$result = $query->execute();
$setup = $query->fetch(PDO::FETCH_ASSOC);
processSetup($setup);
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
$setupJSON = json_decode($setup);
echo '<pre>';
echo $setup;
echo '</pre>';
}
?>
but I can't work out how to download it. I've researched that it's related to headers, but everytime I try something, it never works. I just want the save file dialog to appear with the json, and preferably, the option to set the filename outputted to a chosen variable.
Just figured it out, on the processSetup function, I changed the code to this
function processSetup($setupRow)
{
$setup = $setupRow['setup'];
header('Content-type: application/json');
header('Content-disposition: attachment; filename=setup.json');
echo $setup;
}
If I add some code to give the JSON it's proper filename, it'll be perfect :D
I am configuring FullCalendar with a MySQL DB, using PHP to process and return a JSON.
db-connect.php - fetches results from my Db and encodes to JSON.
get-events.php - reads JSON, converts to FullCalendar
json.html - is my front-end calendar view
File contents below, but before reading: db-connect.php successfully outputs JSON that I have verified on JSONLint.
[{"title":"Test new calendar","start":"2015-07-21","end":"2015-07-22"}]
get-events.php is successfully 'reading' db-connect.php as the "php/get-events.php must be running." error message on my front-end view has disappeared (shows if for example it can't establish that db-connect.php is in the directory, or spelling error in file name, etc).
However when I either pass the query via params or check in Firebug console, the JSON array is empty.
/cal/demos/php/get-events.php?start=2015-07-01&end=2015-07-31
returns [] whereas my test calendar entry does fall within these parameters.
I'm convinced it's my db-connect.php that is the error, but I'm scratching my head about it. Relative newbie so I'm sure it's obvious!
db-connect.php
<?php
$db = mysql_connect("localhost:3306","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db("test",$db);
$result = mysql_query("select * from cal", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['title'] = $row['title'];
$row_array['start'] = $row['start'];
$row_array['end'] = $row['end'];
array_push($json_response,$row_array);
}
echo json_encode($json_response);
mysql_close($db);
?>
get-events.php
<?php
// Require our Event class and datetime utilities
require dirname(__FILE__) . '/utils.php';
if (!isset($_GET['start']) || !isset($_GET['end'])) {
die("Please provide a date range.");
}
$range_start = parseDateTime($_GET['start']);
$range_end = parseDateTime($_GET['end']);
$timezone = null;
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
}
$json = file_get_contents(dirname(__FILE__) . '/db-connect.php');
$input_arrays = json_decode($json, true);
$output_arrays = array();
if (is_array($input_arrays) || is_object($input_arrays))
{
foreach ($input_arrays as $array) {
$event = new Event($array, $timezone);
if ($event->isWithinDayRange($range_start, $range_end)) {
$output_arrays[] = $event->toArray();
}
}
}
echo json_encode($output_arrays);
file_get_contentsdoesn't parse the php file. It will output the programmcode in this case. Add this function to your get-events.php
function loadPhpFile($file) {
ob_start();
include $file;
$content = ob_get_contents();
ob_end_clean();
return $content;
}
And then replace
$json = file_get_contents(dirname(__FILE__) . '/db-connect.php');
with
$json = loadPhpFile(dirname(__FILE__) . '/db-connect.php');
And as a hint: Please use objects (OOP) and mysqli. PHP Mysqli
A little help if possible. I have a Page that pulls from two data tables (MySQL) and one function is providing empty results.
function ShowClient() {
global $agent;
$sql = 'SELECT * FROM nuke_bulletins WHERE user=\'' . $agent . '\' AND isActive="Y" ORDER BY id';
$client = mysql_query($sql) or die('ERROR: OOPS Something went wrong' . mysql_error());
echo '<center><p><b>Current Campaigns</b></p>';
// Pull the loop and display the data
while($row = mysql_fetch_array($client)) {
$agent = stripslashes($row['user']);
$campaign = stripslashes($row['id']);
$title = stripslashes($row['title']);
echo '<p><b>' . $title . '</b></p>';
}
echo '<p>Click the Campaign Title to get the Bulletin Code</p><p> </p>';
echo '<p align="center"><b>Return to All Client\'s</p>';
}
The $agent variable is pulled from a main function that creates a url based on the user ($agent).
What am I doing wrong here?
$agent is a global variable. Using global variables is generally considered bad practice, as this could be getting set or unset somewhere before this function is called.
Have you checked the PHP Error Log to see if you are getting any errors?
If no errors in log I would look to see if $agent conatins a value either by echoing to screen (if dev environment) or dumping the value in the error log file to see if it actually contains anything. http://www.php.net/manual/en/function.error-log.php
Then I would look at the SQL itself; do the Column headings in your table nuke_bulletins match the $row array keys exactly for instance are they the same case?
$row['title']
or
$row['Title']
Here we go...
Don't use the mysql extension. It is unmaintained and officially deprecated
Don't use globals. Relying on external state makes for smelly code
You're overwriting said global variable ($agent) in a loop. Terrible idea.
or die must die ~ http://www.phpfreaks.com/blog/or-die-must-die
I wouldn't recommend using echo within a function. Makes for spaghetti code
Your HTML is a bit of a mess
Here's my suggestion using the mysqli extension
function getCampaigns(mysqli $con, $agent) {
if (!$stmt = $con->prepare("SELECT id, title FROM nuke_bulletins WHERE user = ? AND isActive = 'Y' ORDER BY id")) {
throw new Exception($con->error, $con->errno);
}
$stmt->bind_param('s', $agent); // if the user column is a integer, use 'i' instead
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$stmt->bind_result($id, $title);
$campaigns = []; // or array() if you're on PHP < 5.4
while ($stmt->fetch()) {
$campaigns[$id] = $title;
}
return $campaigns;
}
Now you can call this function like this...
<?php
// assuming you have a mysqli instance in a $con variable, eg $con = new mysqli(...)
// and an $agent variable
$campaigns = getCampaigns($con, $agent);
?>
<p><strong>Current Campaigns</strong></p>
<?php foreach ($campaigns as $id => $title) : ?>
<p>
<a href="bullies2.php?op=ShowCampaign&id=<?= $id ?>">
<strong><?= htmlspecialchars($title) ?></strong>
</a>
</p>
<?php endforeach ?>
<p>Click the Campaign Title to get the Bulletin Code</p>
<p> </p>
<p align="center"><strong>Return to All Client's</strong></p>
And, as always, your development environment should have the following properties set in your php.ini file
display_errors = On
error_reporting = E_ALL
Similar issues -
INVALID_SESSION_ID using partner/enterprise wsdl for two different SF users - Tried solution but didn't work.
I was trying to use Salesforce PHP toolkit with ZF 2. I have added namespace to php files in salesforce soap client and used it in zend controller.
Added follwing line to all php files in Salesforce SOAP client library.
namespace Salesforce\Soapclient;
Then included it in ZF controller.
use Salesforce\Soapclient;
Here is the connetion code -
$empid = 'e1234567';
$sf_WSDL = 'C:\wamp\www\myapp\app\vendor\salesforce\wsdl\enterprise.wsdl.xml';
$sf_username = $config['salesforce']['username'];
$sf_password = $config['salesforce']['password'];
$sf_token = $config['salesforce']['token'];
/***********/
try {
// Create SOAP client instance
$sfSoapClient = new Soapclient\SforceEnterpriseClient();
// Create connection
$sfSoapClient->createConnection($sf_WSDL);
var_dump($_SESSION['enterpriseSessionId']);
if (isset($_SESSION['enterpriseSessionId'])) {
$location = $_SESSION['enterpriseLocation'];
$sessionId = $_SESSION['enterpriseSessionId'];
$sfSoapClient->setEndpoint($location);
$sfSoapClient->setSessionHeader($sessionId);
} else {
// Login to SF
$sfSoapClient->login($sf_username,$sf_password . $sf_token);
$_SESSION['enterpriseLocation'] = $sfSoapClient->getLocation();
$_SESSION['enterpriseSessionId'] = $sfSoapClient->getSessionId();
}
var_dump($_SESSION['enterpriseSessionId']);
// Get candidate profile by employee id
$candidate_profile = $this->getCandidateTable()->getCandidateByEmpId($empid);
$ids = array();
array_push($ids, $empid);
// If no profile for logged internal employee
if (!$candidate_profile){
$query = "SELECT Id, First_Name__c from Employee__c";
$response = $sfSoapClient->query($query);
echo "Results of query '$query'<br/><br/>\n";
foreach ($response->records as $record) {
echo $record->Id . ": " . $record->First_Name__c . "<br/>\n";
}
}
} catch (Exception $exc) {
//TODO Handle error login exception
die('Connection could not established.');
}
But I'm getting following error -
INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal
Session
Note that "Lock sessions to the IP address from which they originated" setting is turned off.