PHP Parse.com query error - php

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
)
)
)

Related

cannot access to Json with restler library

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

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);

API Request $_POST returning empty array

I'm using Zurmo and trying to create a new account using REST API. I followed this documentation precisely: http://zurmo.org/wiki/rest-api-specification-accounts to pass the required parameters as json array.
This is my php code:
public function actionCreateOrUpdate()
{
$params=$_POST;
$modelClassName=$this->getModelName();
foreach ($params as $param)
{
if (!isset($param))
{
$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);
}
$r=$this->GetParam($param);
$res= array('status' => 'SUCCESS', 'data' => array($r));
print_r(json_encode($res,true));
}
}
function GetParam ($param){
$modelClassName=$this->getModelName();
if (isset($param['mobile_id'] ) && !$param['mobile_id']=='' &&!$param['mobile_id']==null)
{ $id=$param['mobile_id'];
$params=array();
foreach ($param as $k => $v) {
if(!($k=='mobile_id')) {
$params[$k] = $v;}
}
if ($params=null){$message = Zurmo::t('ZurmoModule', 'Please provide data.');
throw new ApiException($message);}
$tableName = $modelClassName::getTableName();
$beans = ZurmoRedBean::find($tableName, "mobile_id = '$id'");
if (count($beans) > 0)
{
$result = $this->processUpdate($id, $params);
}else{
$result = $this->processCreate($params,$id);
}
}
return $result;
}
The problem is that the $_POST method is returning an empty array. While debugging I tried to use print_r($_POST) and it also returned an empty array. I also tried to pass parameters as plain text and got the same result. I tried $_GET method and it worked. I think the problem is in the $_POST method, maybe I need to change something in my .php files. Any ideas please?
You should first hit the api with static data, to check if it works fine, then try to integrate php within that static data. You will need to read the documentation for which action accepts which format, and which method is supported(GET OR POST). Then try die(); , before sending if the array formed is as per the documentation.
I had similar issue when creating Account using REST API from java client. The problem was I did not send the proper POST request.
Another symptom also was on server side print_r(file_get_contents("php://input"),true); php code returned the correct request data.
Specifically the root cause was:
The Content-Type HTTP header was not "application/x-www-form-urlencoded"
The value field value in POST request was not properly encoded ( I used java.net.URLEncoder.encode method to overcome this)
After fixing these it worked.

Github API List all repositories and repo's content

If I was to go about displaying just MY github repositories and their contents on an external website how would i go about doing this? Are there any source code's you can provide me with, if not point me in the right direction? I'm quite a beginner to programming so any help is appreciated. Thank you everyone.
Taking a glance at their website
I glanced over relevant links- but still have no clue how I would accomplish this.
-Github List all Repo's
-Github List all Repo content
all of the previous answers are great. however if you are looking for a quick and dirty example of how to get a list of publicly available repos then check out my jsfiddle.
which uses this ajax call to list all of a users public repos:
$("#btn_get_repos").click(function() {
$.ajax({
type: "GET",
url: "https://api.github.com/users/google/repos",
dataType: "json",
success: function(result) {
for(var i in result ) {
$("#repo_list").append(
"<li><a href='" + result[i].html_url + "' target='_blank'>" +
result[i].name + "</a></li>"
);
console.log("i: " + i);
}
console.log(result);
$("#repo_count").append("Total Repos: " + result.length);
}
});
});
to see what kind of data is returned just check the console after clicking the button or you can install Google Chromes JSONView extension and then just visit the url that the ajax request is making i.e. https://api.github.com/users/google/repos
Here is a nice way just with the curl. You should change the $user and the $token variableso to make this script work for your case. The code is tested with a valid token so I hope it will work for you. As you could see in the comments of the code the token could be generated from your github account from here https://github.com/settings/applications
<?php
// for example your user
$user = 'flesheater';
// A token that you could generate from your own github
// go here https://github.com/settings/applications and create a token
// then replace the next string
$token = 'ced38b0e522a5c5e8ab10';
// We generate the url for curl
$curl_url = 'https://api.github.com/users/' . $user . '/repos';
// We generate the header part for the token
$curl_token_auth = 'Authorization: token ' . $token;
// We make the actuall curl initialization
$ch = curl_init($curl_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// We set the right headers: any user agent type, and then the custom token header part that we generated
curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent: Awesome-Octocat-App', $curl_token_auth));
// We execute the curl
$output = curl_exec($ch);
// And we make sure we close the curl
curl_close($ch);
// Then we decode the output and we could do whatever we want with it
$output = json_decode($output);
if (!empty($output)) {
// now you could just foreach the repos and show them
foreach ($output as $repo) {
print '' . $repo->name . '<br />';
}
}
?>
Also since we like github, we should cache the results in the end and fetch them once per day or so.
All these examples are just as pseudo without "authentication" and you can improve them yourself as you like;
<?php
// a simple way to get a user's repo
$res = file_get_contents("https://api.github.com/repos/qeremy/mii");
$res = json_decode($res);
print_r($res);
?>
stdClass Object
(
[language] => JavaScript
[merges_url] => https://api.github.com/repos/qeremy/mii/merges
[contributors_url] => https://api.github.com/repos/qeremy/mii/contributors
[assignees_url] => https://api.github.com/repos/qeremy/mii/assignees{/user}
[url] => https://api.github.com/repos/qeremy/mii
[description] => Multipurpose JavaScript Library
[ssh_url] => git#github.com:qeremy/mii.git
[comments_url] => https://api.github.com/repos/qeremy/mii/comments{/number}
[statuses_url] => https://api.github.com/repos/qeremy/mii/statuses/{sha}
[keys_url] => https://api.github.com/repos/qeremy/mii/keys{/key_id}
...
<?php
// getting a repo's README
$res = file_get_contents("https://api.github.com/repos/qeremy/mii/readme");
$res = json_decode($res);
print_r($res);
?>
stdClass Object
(
[_links] => stdClass Object
(
[self] => https://api.github.com/repos/qeremy/mii/contents/README.md
[git] => https://api.github.com/repos/qeremy/mii/git/blobs/49f0c4d5e25ac44921ba4372aebd76d2da5128e2
[html] => https://github.com/qeremy/mii/blob/master/README.md
)
[url] => https://api.github.com/repos/qeremy/mii/contents/README.md
[type] => file
[sha] => 49f0c4d5e25ac44921ba4372aebd76d2da5128e2
[path] => README.md
[size] => 8213
[encoding] => base64
[content] => QWN0dWFsbHksIEkga25vdyB0aGF0IHRoZXJlIGFyZSBidWNoIG9mIEphdmFT
Y3JpcHQgbGlicmFyeSwgZXZlbiBtb3JlIHBvd2VyZnVsbC4gQnV0IHNvbWV0
...
But, I think needs more complicated structure;
<?php
class GRepo
{
protected
// needs "user"
$src_userRepos = "https://api.github.com/users/%s/repos",
// needs "user,repo"
$src_userRepoDetails = "https://api.github.com/repos/%s/%s",
$responseCode, $responseText,
$user;
public function __construct($user) {
$this->user = $user;
}
public function listRepos() {
$this->_request(
sprintf($this->src_userRepos, $this->user));
if ($this->responseCode != 200) {
throw new Exception('Server error!'); // e.g
}
return json_decode($this->responseText);
}
public function getRepoDetails($repo) {
$this->_request(
sprintf($this->src_userRepoDetails, $this->user, $repo));
if ($this->responseCode != 200) {
throw new Exception('Server error!'); // e.g
}
return json_decode($this->responseText);
}
// Could be extended, e.g with CURL..
protected function _request($url) {
$contents =# file_get_contents($url);
$this->responseCode = (false === $contents) ? 400 : 200;
$this->responseText = $contents;
}
}
// Test
$gr = new GRepo('qeremy');
print_r( $gr->listRepos() );
print_r( $gr->getRepoDetails('mii') );
?>
When you say "display a repo and its contents" you actually say "display the state of the repo after the latest commit of the master branch", right? That's actually the better way of thinking about the problem and will be a better guide through using GitHub's API.
You need to look at the Git data part of the API. Here's what you need to do:
1) fetch the list of refs for your repo using:
https://api.github.com/repos/:user/:repo/git/refs
Working example:
https://api.github.com/repos/izuzak/noam/git/refs
Notice that it lists the references in your repo and gives you links to continue.
2) fetch the commit object of the ref that interests you, namely "master", using the link provided in the response to 1):
https://api.github.com/repos/:user/:repo/git/commits/:sha
Working example:
https://api.github.com/repos/izuzak/noam/git/commits/5cf12775b844664d5f7af6663706195680181374
Notice that you get back an object with a link to a tree.
3) fetch the tree object of the last commit in the master ref, using the link provided in the response to 2) :
https://api.github.com/repos/:user/:repo/git/trees/:sha
Working example:
https://api.github.com/repos/izuzak/noam/git/trees/8a721bea8d2f281c87b39c74cbf5a70075d686b4
Notice that you get back a list of files in the root directory that is your repo. This is what you want. If you have subdirectories, you will get links to fetch the files in those subdirectories.
This should be enough to get you started :). Good luck!
Please try following library also available on git hub:
https://github.com/ornicar/php-github-api
You need to parse the respone Githubs API sends you back. In PHP you can do this by using json_decode() which will give you an array to work with. You can use something like curl to issue the requests from PHP and then get the results and parse them as described above.
Another way to do this are REST Client classes for PHP, have a look at this one here for example.
If you want some source code to analyze, about javascript you can try to start from GitHub Repositories (more specifically here), it's a nice open project for a Chrome extension which does something similiar to what you're looking for.
you can use github api
organization="write-here-the-organization"
githubuser="your-github-user"
token=`curl -i -u ${githubuser} -d '{"scopes": ["repo"]}' https://api.github.com/authorizations | grep token | cut -d\" -f 4`
curl -i -H "Authorization: token ${token}" https://api.github.com/orgs/${organization}/repos
as result of the above you will get a long json with all repositories, and their information. you can continue from here.

check if object exists in Cloud Files (PHP API)

I've just started working with the PHP API for Rackspace Cloud Files. So far so good-- but I am using it as sort of a poor man's memcache, storing key/value pairs of serialized data.
My app attempts to grab the existing cached object by its key ('name' in the API language) using something like this:
$obj = $this->container->get_object($key);
The problem is, if the object doesn't exist, the API throws a fatal error rather than simply returning false. The "right" way to do this by the API would probably be to do a
$objs = $this->container->list_objects();
and then check for my $key value in that list. However, this seems way more time/CPU intensive than just returning false from the get_object request.
Is there a way to do a "search for object" or "check if object exists" in Cloud Files?
Thanks
I sent them a pull request and hope it'll get included.
https://github.com/rackspace/php-cloudfiles/pull/35
My pull-request includes an example, for you it would be similar to this:
$object = new CF_Object($this->container, 'key');
if ($object->exists() === false) {
echo "The object '{$object->name}' does not exist.";
}
I have more general way to check if object exists:
try {
$this->_container->get_object($path);
$booExists = true;
} catch (Exception $e) {
$booExists = false;
}
If you dump the $object, you'll see that content_length is zero. Or, last modified will be a zero length string.
Example:
$object = new CF_Object($container, 'thisdocaintthere.pdf');
print_r($object->content_length);
There is also, deep in the dumped parent object, a 404 that will return, but it's private, so you'd need to some hackin' to get at it.
To see this, do the following:
$object = new CF_Object($container, 'thisdocaintthere.pdf');
print_r($object->container->cfs_http);
You'll see inside that object a response_status that is 404
[response_status:CF_Http:private] => 404
I know I'm a little late to the party, but hopefully this will help someone in the future: you can use the objectExists() method to test if an object is available.
public static function getObject($container, $filename, $expirationTime = false)
{
if ($container->objectExists($filename)) {
$object = $container->getPartialObject($filename);
// return a private, temporary url
if ($expirationTime) {
return $object->getTemporaryUrl($expirationTime, 'GET');
}
// return a public url
return $object->getPublicUrl();
}
// object does not exist
return '';
}
Use like...
// public CDN file
$photo = self::getObject($container, 'myPublicfile.jpg');
// private file; temporary link expires after 60 seconds
$photo = self::getObject($container, 'myPrivatefile.jpg', 60);
If you do not want to import opencloud to perform this check you can use the following:
$url = 'YOUR CDN URL';
$code = FALSE;
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1,
'max_redirects' => 0
);
$body = file_get_contents($url, NULL, stream_context_create($options));
sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
if($code!='200') {
echo 'failed';
} else {
echo 'exists';
}

Categories