cannot access to Json with restler library - php

I create an rest api with php usring restler libary, its work well in my PC but when I uploaded the api to server, problems begin..
this function in my api
<?php
class user {
/**
#url GET /
*/
public function getAllInfo(){
$link = new PDO('mysql:host=localhost;dbname=---;charset=utf8','---','-----');
$handle = $link->prepare('select * from user');
$handle->execute();
$result = $handle->fetchAll(PDO::FETCH_OBJ);
if(empty($result)){
$err = new stdClass();
$err->error = "No user found";
return $err;
}
else{
return $result;
}
}
require_once 'restler.php';
$r = new Restler();
$r->setSupportedFormats('JsonFormat');
$r->addAPIClass('user');
$r->handle();
?>
when I access to this page nothing appear in browser
I thought the problem is this page can't access to require_once 'restler.php';
but I was wrong, because whan I print $r->handle(); like this print_r($r->handle());
this is what I see in browser
Luracast\Restler\EventDispatcher Object ( [listeners:Luracast\Restler\EventDispatcher:private] => Array ( ) [events:protected] => Array ( ) )
I don't know what is that or what I should do to print my json,
my database is full of data, its return json if my query doesn't have restler, but I need use restler with my code

Related

Amazon MWS (PHP) - Report Request API functions return without data, no error thrown

I am currently working with the Amazon MWS to integrate some features into wordpress via a plugin. I am using the client libraries provided by amazon found here:
https://developer.amazonservices.com/api.html?group=bde&section=reports&version=latest
Using these client libraries and the sample php files included I have set up my plugin to make two API calls. The first is requestReport
public function requestInventoryReport() {
AWI_Amazon_Config::defineCredentials(); // Defines data for API Call
$serviceUrl = "https://mws.amazonservices.com";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebService_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
$config,
APPLICATION_NAME,
APPLICATION_VERSION);
$request = new MarketplaceWebService_Model_RequestReportRequest();
$request->setMerchant(MERCHANT_ID);
$request->setReportType('_GET_MERCHANT_LISTINGS_DATA_');
self::invokeRequestReport($service, $request);
}
private function invokeRequestReport(MarketplaceWebService_Interface $service, $request) {
try {
$response = $service->requestReport($request);
if ($response->isSetRequestReportResult()) {
// Print Out Data
}
} catch (MarketplaceWebService_Exception $ex) {
// Print Out Error
}
}
and the second is getReportRequestList which has code similar to the first function. I am able to run these functions without any errors. The issue that I am having is that $response->isSetRequestReportResult() returns false. From my understanding and looking into the response object, this would suggest that the response object does not have the result. (Upon printing out the response object I can see that the FieldValue of the result array is NULL.) The call, however, does not throw an error but neither does it have the result.
I did some digging through the code and found that the result does actually get returned from the api call but never gets set to the return object when the library attempts to parse it from XML. I've tracked the error down to this block of code (This code is untouched by me and directly from the amazon mws reports library).
private function fromDOMElement(DOMElement $dom)
{
$xpath = new DOMXPath($dom->ownerDocument);
$xpath->registerNamespace('a', 'http://mws.amazonaws.com/doc/2009-01-01/');
foreach ($this->fields as $fieldName => $field) {
$fieldType = $field['FieldType'];
if (is_array($fieldType)) {
if ($this->isComplexType($fieldType[0])) {
// Handle Data
} else {
// Handle Data
}
} else {
if ($this->isComplexType($fieldType)) {
// Handle Data
} else {
$element = $xpath->query("./a:$fieldName/text()", $dom);
$data = null;
if ($element->length == 1) {
switch($this->fields[$fieldName]['FieldType']) {
case 'DateTime':
$data = new DateTime($element->item(0)->data,
new DateTimeZone('UTC'));
break;
case 'bool':
$value = $element->item(0)->data;
$data = $value === 'true' ? true : false;
break;
default:
$data = $element->item(0)->data;
break;
}
$this->fields[$fieldName]['FieldValue'] = $data;
}
}
}
}
}
The data that should go into the RequestReportResult exists at the beginning of this function as a node in the dom element. The flow of logic takes it into the last else statement inside the foreach. The code runs its query and returns $element however $element->length = 13 in my case which causes it to fail the if statement and never set the data to the object. I have also looked into $element->item(0) to see what was in it and it appears to be a dom object itself matching the original dom object but with a bunch of empty strings.
Now, I'm new to working with the MWS and my gut feeling is that I am missing a parameter somewhere in my api call that is messing up how the data is returned and is causing this weird error, but I'm out of ideas at this point. If anyone has any ideas or could point me in the right direction, I would greatly appreciate it.
Thanks for your time!
** Also as a side note, Amazon Scratchpad does return everything properly using the same parameters that I am using in my code **
These works for me, check if you are missing anything.
For RequestReportRequest i am doing this:
$request = new MarketplaceWebService_Model_RequestReportRequest();
$marketplaceIdArray = array("Id" => array($pos_data['marketplace_id']));
$request->setMarketplaceIdList($marketplaceIdArray);
$request->setMerchant($pos_data['merchant_id']);
$request->setReportType($this->report_type);
For GetReportRequestList i am doing this:
$service = new MarketplaceWebService_Client($pos_data['aws_access_key'], $pos_data['aws_secret_access_key'], $pos_data['config'], $pos_data['application_name'], $pos_data['application_version']);
$report_request = new MarketplaceWebService_Model_GetReportRequestListRequest();
$report_request->setMerchant($pos_data["merchant_id"]);
$report_type_request = new MarketplaceWebService_Model_TypeList();
$report_type_request->setType($this->report_type);
$report_request->setReportTypeList($report_type_request);
$report_request_status = $this->invokeGetReportRequestList($service, $report_request, $report_requestID);

No thumbnails are returned in youtube api

I've attempted to use the YouTube service API V3 and have run into an issue I'm unsure of how to proceed.
I'm calling my script through Jquery's Ajax. Nothing crazy.
Passing in an id for the video I want and away I go.
The script is as such:
session_start();
$return_msg = array();
// ===================================
// Require Google libraries
// ===================================
set_include_path("../../includes/");
if(!(#require_once('Google/Client.php')))
{
$return_msg['error'] = 'Unable to includes Google Client Library:<br>'.$e->getMessage();
return $return_msg;
}
if(!(#require_once('Google/Service/YouTube.php')))
{
$return_msg['error'] = 'Unable to includes Google YouTube Library:<br>'.$e->getMessage();
return $return_msg;
}
// ===================================
// Include Global settings
// ===================================
if(!(#require_once('Global-Settings.php')))
{
$return_msg['error'] = 'Unable to includes site settings:<br>'.$e->getMessage();
return $return_msg;
}
$globals = new Globals();
// Set API key
$api_key = $globals->youtube_key;
if(!isset($data['id']))
{
$return_msg['error'] = 'Unable to determine the video you are attempting to find.';
return $return_msg;
}
// ===================================
// Create Client
// ===================================
try
{
$client = new Google_Client();
$client->setApplicationName("YouTube_Test");
$client->setDeveloperKey($api_key);
}catch(Exception $e){
$return_msg['error'] = 'Error creating Google client:<br>'.$e->getMessage();
return $return_msg;
}
// ===================================
// Get video
// ===================================
try
{
$service = new Google_Service_YouTube($client);
$response = $service->videos->listVideos('id,snippet,contentDetails', array(
"id" => $data['id']
));
$return_msg['results'] = $response;
foreach($response->items as $video)
{
$item = array();
$item['id'] = $video['id'];
$item['snippet'] = $video['snippet'];]
$item['contentDetails'] = $video['contentDetails'];
$return_msg['items'][$item['id']] = $item;
}
}catch(Exception $e){
$return_msg['error'] = 'Error finding video:<br>'.$e->getMessage();
return $return_msg;
}
return $return_msg;
The reason I am storing the individual items in an array is because line $return_msg['results'] = $response; returns fields, yet not the items object as I'd expect.
Anywho, once I return all this to JS and log it to console, I see that inside the 'snippets' array there are no thumbnails.
Not sure why, or what I'm doing incorrectly as far as that goes. I've tried to log as much info as I could and I simply can't find any trace of the thumbnails collection.
A simple way to get thumbnail of a video from youtube is by using the video id:
http://img.youtube.com/vi/<your_video_id>/0.jpg
[0.jpg, 1.jpg, 2.jpg and 3.jpg can be used]
For Eg:
http://img.youtube.com/vi/-w8KI3A5zu4/0.jpg
if you got the video_id from youtube API, you can simply use this to get the image.

PHP Parse.com query error

I don't know how many of you are familiar with the parse.com platform, but I am utilizing the third party php library that is linked on their website and I am running into a couple problems.
Link: Parse.com PHP Library
I am trying to query my db but it keeps returning Notice: Trying to get property of non-object. From what I can see my code is correct but the error originates from one of the files included in the library.
Here is my code thus far:
function storeInParseDB ($message, $unit) {
$parse = new parseQuery($class = 'PushNotifications');
$parse->whereEqualTo('unit', $unit);
$result = $parse->find();
echo "RESULT: ";
print_r($result);
}
Code that is throwing the error:
private function checkResponse($response,$responseCode,$expectedCode){
//TODO: Need to also check for response for a correct result from parse.com
if($responseCode != $expectedCode){
$error = json_decode($response);
$this->throwError($error->error,$error->code);
}
else{
//check for empty return
if($response == '{}'){
return true;
}
else{
return json_decode($response);
}
}
}
Any help would be greatly appreciated.
I'm running the following code after cloning https://github.com/apotropaic/parse.com-php-library.git - created a parseConfig.php file with appid, restkey and masterkey as decribed in the readme.
I created a new Class in the Parse Data Browser with a single column "unit" of type string and added one row to it, unit = test.
<?php
include 'parse.com-php-library/parse.php';
function storeInParseDB ($message, $unit) {
$parse = new parseQuery('PushNotifications');
$parse->whereEqualTo('unit', $unit);
$result = $parse->find();
echo "RESULT: ";
print_r($result);
}
storeInParseDB('hi', 'test');
As you can see I get the desired output back, make sure you have setup your parseConfig.php file correctly.
RESULT: stdClass Object
(
[results] => Array
(
[0] => stdClass Object
(
[unit] => test
[createdAt] => 2013-01-21T14:57:26.613Z
[updatedAt] => 2013-01-21T14:57:26.613Z
[objectId] => 0uiYuJcRYY
)
)
)

How to get all subfolders from "root" recursively via SOAP from Exchange?

After searching the web for hours you are my last hope:
I have to build a system which reads sent and incoming mails from a Microsoft Exchange Server. I found the following script for that:
Exchange-Web-Services-for-PHP (Heartspring)
https://github.com/Heartspring/Exchange-Web-Services-for-PHP
The existing get_messages() function returns all messages for a folder, for example "inbox". So far everything is clear. My problem starts when I want to get all messages from "sent" - Folder - i've tried many words, from "send" to "Sent Items"; without any result (mailbox not available)
My idea was to get all subfolders for the folder "root" and wrote this:
include "init.php";
$ec = new ExchangeClient();
$ec->init("bambullis#123.de", "", NULL, "https://amxprd3610.outlook.com/EWS/Services.wsdl");
$folders = $ec->get_subfolders("root");
foreach($folders as $folder) {
print_r($folder);
}
This is what I get:
stdClass Object
(
[FolderId] => stdClass Object
(
[Id] => AAAeAGJhbWJ1bGxpc0BzdHVrZSbi5kZQAuAAAAAABw352p5E4yS5voYF9ELBmiAQBXYPdO6NZAQ6T9C3xviT7xAAAAC1iXAAA=
[ChangeKey] => AQAAABYAAABXYPdO6NZAQ6T9C3xviAALNCey
)
[DisplayName] => Oberste Ebene des Informationsspeichers
[TotalCount] => 0
[ChildFolderCount] => 16
[UnreadCount] => 0
)
(I know that FolderId->Id is base64 encoded, I've modified the string above for security reasons ;o))
Now I tried to list the subfolders for this directory (I added a mailbox to see, if the value "ChildFolderCount" will change, it does):
...
print_r($folder);
print_r($ec->get_subfolders($folder->FolderId->Id));
...
This is the error I get:
The request failed schema validation: The 'Id' attribute is invalid
What did I do wrong? How to get all subfolders from "root" recursively? Thanks to this lovely guy who can help me!
The EWS-PHP get_subfolders method uses by default a TraversalType "Shallow", so it searches only the identified folder and returns only the folder IDs for items that have not been deleted.
To search in all subfolders of the identified parent folder and return only the folder IDs for items that have not been deleted you should use the "Deep" TraversalType.
For example:
<?php
include "init.php";
class myExchangeClient extends ExchangeClient {
public function get_subfolders_deep($ParentFolderId = "inbox", $Distinguished = TRUE) {
$this->setup();
$FolderItem = new stdClass();
$FolderItem->FolderShape = new stdClass();
$FolderItem->ParentFolderIds = new stdClass();
$FolderItem->FolderShape->BaseShape = "Default";
/*
** See http://msdn.microsoft.com/en-us/library/exchange/exchangewebservices.folderquerytraversaltype(v=exchg.140).aspx
** Deep Traversal: Searches in all subfolders of the identified parent folder and returns only the folder IDs for items that
** have not been deleted.
*/
$FolderItem->Traversal = "Deep";
if ($Distinguished) {
$FolderItem->ParentFolderIds->DistinguishedFolderId = new stdClass();
$FolderItem->ParentFolderIds->DistinguishedFolderId->Id = $ParentFolderId;
} else {
$FolderItem->ParentFolderIds->FolderId = new stdClass();
$FolderItem->ParentFolderIds->FolderId->Id = $ParentFolderId;
}
$response = $this->client->FindFolder($FolderItem);
if ($response->ResponseMessages->FindFolderResponseMessage->ResponseCode == "NoError") {
$folders = array();
if (!is_array($response->ResponseMessages->FindFolderResponseMessage->RootFolder->Folders->Folder)) {
$folders[] = $response->ResponseMessages->FindFolderResponseMessage->RootFolder->Folders->Folder;
} else {
$folders = $response->ResponseMessages->FindFolderResponseMessage->RootFolder->Folders->Folder;
}
return $folders;
} else {
$this->lastError = $response->ResponseMessages->FindFolderResponseMessage->ResponseCode;
}
}
}
$ec = new myExchangeClient();
$ec->init("bambullis#123.de", "", NULL, "https://amxprd3610.outlook.com/EWS/Services.wsdl");
$folders = $ec->get_subfolders_deep("root");
echo "<pre>".print_r($folders,true)."</pre>\n";
?>
Anyway, looking at the ExchangeClient class source code, the FolderID for the sent items should be "sentitems".

nusoap simple server

Hi i am using this code for nusoap server but when i call the server in web browser it shows message "This service does not provide a Web description" Here is the code
<?
//call library
require_once ('lib/nusoap.php');
//using soap_server to create server object
$server = new soap_server;
//register a function that works on server
$server->register('hello');
// create the function
function hello($name)
{
if(!$name){
return new soap_fault('Client','','Put your name!');
}
$result = "Hello, ".$name;
return $result;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
An help ...
Please change your code to,
<?php
//call library
require_once('nusoap.php');
$URL = "www.test.com";
$namespace = $URL . '?wsdl';
//using soap_server to create server object
$server = new soap_server;
$server->configureWSDL('hellotesting', $namespace);
//register a function that works on server
$server->register('hello');
// create the function
function hello($name)
{
if (!$name) {
return new soap_fault('Client', '', 'Put your name!');
}
$result = "Hello, " . $name;
return $result;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
You didnt Define namespace..
Please see simple example here :-
http://patelmilap.wordpress.com/2011/09/01/soap-simple-object-access-protocol/
The web browser is not calling the Web service - you could create a PHP client :
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
// Create the client instance
$client = new soapclient('your server url');
// Call the SOAP method
$result = $client->call('hello', array('name' => 'StackOverFlow'));
// Display the result
print_r($result);
This should display Hello, StackOverFlow
Update
To create a WSDL you need to add the following :
$server->configureWSDL(<webservicename>, <namespace>);
You can also use nusoap_client
<?php
// Pull in the NuSOAP code
require_once('lib/nusoap.php');
// Create the client instance
$client = new nusoap_client('your server url'); // using nosoap_client
// Call the SOAP method
$result = $client->call('hello', array('name' => 'Pingu'));
// Display the result
print_r($result)
?>

Categories