The LogMeIn API's "getSession" call is driving me a bit crazy. According to their documentation, you should be able to input an iNodeID either from the getHierarchy call or just the tech's ID# from the LogMeIn admin page and it will report their open session information, but no matter what I use, I get an error "stdClass Object ( [getSessionResult] => getSession_InvalaidParam_NodeID )" Has anyone ever seen this?
Here is my code:
<?php
require("/usr/local/lib/php/nusoap/nusoap.php");
$loginParams = array(
'sEmail' => *hidden*,
'sPassword' => *hidden*
);
$soapclient = new soapclient("https://secure.logmeinrescue.com/API/API.asmx?WSDL");
$loginResult = $soapclient->login($loginParams);
$hierparams = array(""=>"");
$hierarchyResult = $soapclient->getHierarchy($hierparams);
$hierarchy = $hierarchyResult->aHierarchy;
$nodes = $hierarchy->HIERARCHY;
$numberofnodes = count($nodes);
echo "<table border =\"0\" cellspacing = \"5\">";
for ($iNodes = 0; $iNodes < $numberofnodes; $iNodes += 1)
{
if($nodes[$iNodes]->eStatus == "Online" && $nodes[$iNodes]->eType == "Technician"){
print_r("<tr>");
print_r("<td>Name: " . $nodes[$iNodes]->sName . "<br /></td>");
####This works
print_r("<td>ID: " . $nodes[$iNodes]->iNodeID . "<br /></td>");.
###############
print_r("<td>Email: " . $nodes[$iNodes]->sEmail . "<br /></td>");
####This doesn't.
$sessioninfo = $soapclient->getSession($nodes[$iNodes]->iNodeID);
################
print_r("<td>Session Dump: ". print_r($sessioninfo) . "</td>");
print_r("</td>");
}
}
print_r("</table>");
$soapclient->logout();
?>
Turns out there was a parameter that I overlooked, eNodeRef, which has a default parameter of "NODE".
$iNodeID = $nodes[$iNodes]->iNodeID;
$eNodeRef = "NODE";
$sessionparams = array(
'iNodeID' => $iNodeID,
'eNodeRef' => $eNodeRef
);
$sessionresult = $soapclient->getSession($sessionparams);
Related
I have the following code that is overwriting my array on the second pass through of the while loop.
Here is my code:
<?php
require '../vendor/autoload.php';
require_once 'constants/constants.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
require('includes/application_top.php');
define("AUTHORIZENET_LOG_FILE", "phplog");
function getUnsettledTransactionList()
{
//get orders that are in the exp status
$orders_pending_query = tep_db_query("select orders_id as invoice_number from " . TABLE_ORDERS . " where orders_status = '14' order by invoice_number");
$orders_pending = array();
while ($row = mysqli_fetch_array($orders_pending_query, MYSQLI_ASSOC)) {
$orders_pending[] = $row;
}
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(\SampleCodeConstants::MERCHANT_LOGIN_ID);
$merchantAuthentication->setTransactionKey(\SampleCodeConstants::MERCHANT_TRANSACTION_KEY);
// Set the transaction's refId
$refId = 'ref' . time();
$pagenum = 1;
do {
$request = new AnetAPI\GetUnsettledTransactionListRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$paging = new AnetAPI\PagingType;
$paging->setLimit("1000");
$paging->setOffset($pagenum);
$request->setPaging($paging);
$controller = new AnetController\GetUnsettledTransactionListController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);
$transactionArray = array();
$resulttrans = array();
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
if (null != $response->getTransactions()) {
foreach ($response->getTransactions() as $tx) {
$transactionArray[] = array(
'transaction_id' => $tx->getTransId(),
'invoice_number' => $tx->getInvoiceNumber()
);
// echo "TransactionID: " . $tx->getTransId() . "order ID:" . $tx->getInvoiceNumber() . "Amount:" . $tx->getSettleAmount() . "<br/>";
}
$invoiceNumbers = array_column($orders_pending, "invoice_number");
$result = array_filter($transactionArray, function ($x) use ($invoiceNumbers) {
return in_array($x["invoice_number"], $invoiceNumbers);
});
$resulttrans = array_column($result, "transaction_id");
} else {
echo "No unsettled transactions for the merchant." . "\n";
}
} else {
echo "ERROR : Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " . $errorMessages[0]->getText() . "\n";
}
$numResults = (int) $response->getTotalNumInResultSet();
$pagenum++;
print_r($resulttrans);
} while ($numResults === 1000);
return $resulttrans;
}
getUnsettledTransactionList();
?>
the print_r($resulttrans); is actually printing 2 separate arrays, instead of my desired 1 array.
If I move the print_r($resulttrans) to after the while loop, I am only seeing the second array, meaning the first array was overwritten. I am not seeing where this is happening though as to me it seems like all results should be added onto the array.
Your code is supposed to work as you described because you are reassigning the array variable in your loop like this
$resulttrans = array_column($result, "transaction_id");
If you need to get all the resulting values in the same array you need to append it to the array. you can do that by merging the new result into your array variable like this
$resulttrans = array_merge($resulttrans, array_column($result, "transaction_id"));
Hubspot's API allows you retrieve a list of contacts, however it only allows a max of 100 per call.
I do that with this call:
$contacts_batch1 = $contacts->get_all_contacts(array( 'count' => '100'));
And then if I want to get the next 100 I do this:
$offset1 = $contacts_batch1->{'vid-offset'};
$contacts_batch2 = $contacts->get_all_contacts(array('count' => '100', 'vidOffset'=>$offset1));
I am trying to get all the contacts without having to create a new variable each time I want the next 100. My first question would be how would I go about getting the vid-offset of the last set, and then how would I put that as a parameter into the next variable automatically.
Here's an example of getting all contacts into one array using HubSpot's API.
<?php
require "haPiHP/class.contacts.php";
require "haPiHP/class.exception.php";
define("HUBSPOT_API_KEY", "<YOUR API KEY HERE>");
$contacts = new HubSpot_Contacts(HUBSPOT_API_KEY);
$all_contacts = array();
do
{
$params = array("count" => 100);
if (isset($vidOffset))
{
$params["vidOffset"] = $vidOffset;
}
echo "count=" . $params["count"] . (isset($params["vidOffset"]) ? ", vidOffset=" . $params["vidOffset"] : "") . "\n";
$some_contacts = $contacts->get_all_contacts($params);
if ($some_contacts !== NULL)
{
$all_contacts = array_merge($all_contacts, $some_contacts->contacts);
}
else
{
break;
}
$vidOffset = $some_contacts->{'vid-offset'};
} while ($some_contacts->{'has-more'});
echo "Received " . count($all_contacts) . " contacts.\n";
?>
I have this code that store a "student" object in $_SESSION:
if(isset($_POST["name"]) && isset($_POST["note"]) && isset($_POST["year"]))
{
$nom = $_POST["name"];
$note = $_POST["note"];
$session = $_POST["year"];
$vec = array("name" => $name, "note" => $note, "year" => $year);
$_SESSION["students"][] = $vec;
echo "The student has been added.<br><br>";
}
Then I have this code in another page:
function calculateAverage()
{
$av = 0;
$count = 0;
foreach($_SESSION['students'] as $student)
{
$av = $av + $student["note"];
$count = $count + 1;
}
return $av / $count;
}
function bestNote()
{
//$best = array_search(max())
return $best;
}
function worstNote()
{
$worst = min(array_search(["note"], $_SESSION['students']));
return $worst;
}
if(isset($_SESSION['students']))
{
echo "The average note of the group is = " . calculateAverage() . "\n";
echo "The one with the best note is " . bestNote()["name"] . " is " . hauteNote()["note"] . " points.\n";
echo "The one with the worst note is " . worstNote()["name"] . " with " . basseNote()["note"] . " points.\n";
}
As you can see, it is not finished. What I want to do is to be able to get the note of a student that is stored in $_SESSION["students"]. How can I do this?
Thanks for answers.
you can access the stored values within a nested array like so:
$studentNote = $_SESSION["students"][YourActiveStudent]["note"];
However, you are currently not adding but overwriting data. Use array_push() to add data to an array (your students).
And when adding a student to the array, make sure to give it a name to make it associative so you can simply "call a student":
$_SESSION["students"][$nom] = $vec;
this way, if the $nom was "Max", you could say
$_SESSION["students"]["Max"]["note"]
to get Max's note (BTW, I assume you are talking about grades or marks, rather than notes?)
I do not understand fully why this PHP code is not saving the data in the arrays. when I echo out the array during the while loop, the values are set but after I exit the loop, the values in the array are missing. The other variables did contain their values after leaving the array.
<?php
class VIEWARRAY {
public $year;
public $month;
public $day = array();
public $views = array();
}
$viewdatabase = array();
$connection = MySQL_Connection($host, Session_Get("username"), Session_Get("password"), $database);
$dayviewindex = 0; $monthyearindex = 0; $previousmonth = "";
$information = MySQL_Script($connection, "SELECT * FROM viewdatabase");
while ($index = mysqli_fetch_array($information)) {
if ($index["month"] != $previousmonth) {
$viewdatabase[$monthyearindex] = new VIEWARRAY;
$viewdatabase[$monthyearindex]->year = $index["year"];
$viewdatabase[$monthyearindex]->month = $index["month"];
$dayviewindex = 0;
$monthyearindex++;
$previousmonth = $index["month"];
}
$viewdatabase[$monthyearindex]->day[$dayviewindex] = $index["day"];
$viewdatabase[$monthyearindex]->views[$dayviewindex] = $index["views"];
$dayviewindex++;
}
MySQL_Disconnect($connection);
//testing area
echo "->" . $viewdatabase[0]->year . " + " . $viewdatabase[0]->month . "<br />"; //prints out ->2013 + 8
echo "------>" . $viewdatabase[0]->day[2] . " + " . $viewdatabase[0]->views[2] . "<br />"; //prints out ------> +
echo count($viewdatabase[0]->views) . "<br />"; //prints out 0
echo count($viewdatabase[1]->views) . "<br />"; //prints out 0
?>
I made sure that I was able to connect to my database just fine and that my database did return information. This is how my database is setup
year month day views
2013 8 25 1
2013 8 26 1
2013 8 27 1
2013 9 3 1
At first run, after if ($index["month"] != $previousmonth), $monthyearindex will be 1.
That means you'll next try to access $viewdatabase[1] but it's NULL.
On the next iteration you won't enter the if, $monthyearindex will be 1, and $viewdatabase[1] will still be NULL.
So you never actually get to set anything in day and views.
Use
if ($index["month"] !== $previousmonth) {
instead of
if ($index["month"] != $previousmonth) {
, because
0 == ''
, but
0 !== ''
. Because,
$index['month'] != ''
is
false
, your if statement fails.
Currently, I am attempting to use the metadata from our streaming provider, StreamOn to send a request out to Last.FM to get the original sized album artwork. I am new to the world of APIs so it is rather confusing to me, however I am managing. My problem arises in the sending and receiving of the image over XML. In the code below, the contents of the metadata page are set as variables, which are then A.) displayed, and B.) used to look for the appropriate album artwork.
<?php
$request = file_get_contents('http://ckpk.streamon.fm/card.php');
$doubleQuotation = '"';
//Artist Request
$artistTitle = '"artist": "';
$artistTitlePosition = intval(strpos($request, $artistTitle));
$artistBeginningPosition = $artistTitlePosition + 11;
$artistEndingPosition = intval(strpos($request, $doubleQuotation, $artistBeginningPosition));
$artistName = substr($request, $artistBeginningPosition, $artistEndingPosition - $artistBeginningPosition);
echo '<b>' . $artistName . '</b>';
echo '<br />';
$artist = $artistName;
//Track Request
$trackTitle = '"title": "';
$trackTitlePosition = intval(strpos($request, $trackTitle));
$trackBeginningPosition = $trackTitlePosition + 10;
$trackEndingPosition = intval(strpos($request, $doubleQuotation, $trackBeginningPosition));
$trackName = substr($request, $trackBeginningPosition, $trackEndingPosition - $trackBeginningPosition);
echo '<i>' . $trackName . '</i>';
echo '<br />';
//Album Name Request
$albumTitle = '"album": "';
$albumTitlePosition = intval(strpos($request, $albumTitle));
$albumBeginningPosition = $albumTitlePosition + 10;
$albumEndingPosition = intval(strpos($request, $doubleQuotation, $albumBeginningPosition));
$albumName = substr($request, $albumBeginningPosition, $albumEndingPosition - $albumBeginningPosition);
echo $albumName;
$album = $albumName;
/*
* Last.FM Artwork Class
* Author: Caleb Mingle (#dentafrice)
* http://dentafrice.com
*/
class LastFM {
const API_KEY = "7facb82a2a573dd483d931044030e30c";
public static $size_map = array("small" => 0, "medium" => 1, "large" => 2, "extralarge" => 3, "mega" => 4);
public static function getArtwork($artist, $return_image = false, $size = "image_mega", $album) {
$artist = urlencode($artist);
$returnedInfo = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=" . self::API_KEY . "&artist=" . $artist . "&album=" . $album . "&image=" . self::$size_map[$size] . "&format=json";
$returnedInfo = #file_get_contents($returnedInfo);
if(!$returnedInfo) {
return; // Artist lookup failed.
}
$xml = new SimpleXMLElement($xml);
$xml = $xml->artist;
$xml = $xml->image[self::$size_map[$size]];
return (!$return_image) ? $xml : '<img src="' . $xml . '" alt="' . urldecode($artist) . '" />';
}
}
$artwork = LastFM::getArtwork($artist, true, $size, $album);
if($artwork) {
echo $artwork;
}
else{
return;
}
?>
I temporarily styled the elements to distinguish between them and I will worry about the styling later. However, I would like to know how to go about using the data to send a request to the Lsat.FM servers and receive the image to then properly display it. It's different with StreamOn than with something else, such as ShoutCast.
According to your reply in the comments, my hypothesis is confirmed.
Because you are requesting the Last.FM API to return JSON, you get the error:
Fatal error: Uncaught exception 'Exception' with message 'String could
not be parsed as XML
Because it is JSON, not XML.
You can fix this in two ways. Either change the response format to XML or do not use SimpleXML but json_decode() instead.
The first is probably the easiest to adjust. Try to change the &format=json part to &format=xml
I haven't tested this but highly probably that this will be supported by Last.fm.
Also note that you don't supply an image size, and "image_mega" the default value is not a valid value (see API specs # http://www.last.fm/api/show/artist.getInfo). You probably want want to use "mega" not "image_mega"
Updated, working code using JSON:
<?php
class LastFM {
const API_KEY = "7facb82a2a573dd483d931044030e30c";
public static $size_map = array("small" => 0, "medium" => 1, "large" => 2, "extralarge" => 3, "mega" => 4);
public static function getArtwork($artist, $return_image = false, $size = "mega", $album) {
$artist = urlencode($artist);
$album = urlencode($album);
$returnedInfo = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=" . self::API_KEY . "&artist=" . $artist . "&album=" . $album . "&image=" . self::$size_map[$size] . "&format=json";
$returnedInfo = #file_get_contents($returnedInfo);
if(!$returnedInfo) {
return; // Artist lookup failed.
}
$json = json_decode($returnedInfo, true);
$albumArt = $json["artist"]["image"][self::$size_map[$size]]["#text"];
return (!$return_image) ? print_r($json) : '<img src="' . $albumArt . '" alt="' . urldecode($artist) . '" />';
}
}
$artist = "Daft Punk";
$album = "Random Access Memories";
$size = "mega";
$artwork = LastFM::getArtwork($artist, true, $size, $album);
if($artwork) {
echo $artwork;
}
else{
return;
}
I know I rock. I choose JSON because I find it easier to work with. It returns exactly what you want, e.g.:
<img src="http://userserve-ak.last.fm/serve/500/10923145/Daft+Punk+6a00e398210d13883300e55ui6.png" alt="Daft Punk" />
Finally, I added urlencoding() for the album name, since I had issues with that in my example.
Working PHPFiddle